2017-12-08 31 views
1

이것은 exorcism.io에서 클래스가있는 임의의 이름을 생성해야하는 연습으로 초기화되었습니다. 단위 테스트 케이스 중 하나는 클래스의 두 인스턴스에서 임의의 문자열이 동일하기 때문에 실패합니다. unittest 외부에서 코드를 실행하면 올바르게 작동하는 것 같습니다. var가 unittest의 동일한 주소 공간을 가리킬 수 있습니까?python3 클래스는 unittest와 동일한 임의의 값을 생성합니다.

import string 
import random 
import unittest 


class Robot(object): 
    def __init__(self): 
     self.name = None 
     self.reset() 
     print('Name at Init', self.name) 

    def reset(self): 
     for _ in range(5): 
      new = random.choice(string.ascii_uppercase) + random.choice(string.ascii_uppercase) + str(random.randint(100, 999)) 

     self.name = new 


class SimpleTest(unittest.TestCase): 
    if not hasattr(unittest.TestCase, "assertRegex"): 
     assertRegex = unittest.TestCase.assertRegexpMatches 

    name_re = r'^[A-Z]{2}\d{3}$' 

    def test_names(self): 
     # Set a seed 
     seed = "This is some seed text" 

     # Initialize RNG using the seed 
     random.seed(seed) 

     # Call the generator 
     robot = Robot() 
     name = robot.name 

     # Reinitialize RNG using seed 
     random.seed(seed) 

     # Call the generator again 
     robot.reset() 
     name2 = robot.name 
     self.assertNotEqual(name, name2) 
     self.assertRegex(name2, self.name_re) 



if __name__ == '__main__': 
    unittest.main() 
    # print(Robot().name == Robot().name) # Returns False 



F 
Name at Init WY294 
====================================================================== 
FAIL: test_names (__main__.SimpleTest) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/.......robot.py", line 42, in test_names 
    self.assertNotEqual(name, name2) 
AssertionError: 'WY294' == 'WY294' 

---------------------------------------------------------------------- 
Ran 1 test in 0.001s 

FAILED (failures=1) 

답변

1

시험에서 시드를 두 번째로 호출하십시오. 난수 생성기는 지정된 시드에 대해 항상 동일한 시퀀스를 생성하므로 시드를 두 번 호출하면 시퀀스를 되감기 때문에 동일한 값을 얻게됩니다.