python3类使用unittest生成相同的随机值

时间:2017-12-08 00:52:32

标签: python-3.x random python-unittest

这是exorcism.io的练习,我需要生成一个随机名称,并初始化该类。其中一个单元测试用例失败,因为该类的两个实例中的随机字符串相同。如果我在unittest之外运行代码,它似乎正常工作。可能是var指向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 个答案:

答案 0 :(得分:1)

在测试中取出第二次种子调用。随机数生成器将始终为给定的种子生成相同的序列,因此通过调用种子两次,您将重新排序序列,这就是您获得相同值的原因。