Eman
Eman

Reputation: 83

python3 class generates same random value with unittest

This is an exercise from exorcism.io that I need to generate a random name with the class is initialized. One of the unit test cases is failing because the random string is same across two instances of the class. If I run the code outside of unittest, it appears to work correctly. Could it be that the var is pointing to the same address space in 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)

Upvotes: 1

Views: 244

Answers (1)

Dan
Dan

Reputation: 1884

Take out the second call to seed in your test. The random number generator will always generate the same sequence for a given seed, so by calling the seed twice you are rewinding the sequence and that is why you get the same values.

Upvotes: 1

Related Questions