1

I have a data structure that is created in one function and passed onto other functions. I am trying to unit test all those functions.

Do I need to re-create that data structure (the environment) at each function? I tried using a global variable but I cannot guarantee which test case will run before the other.

I know I cannot override __init__ of unittest.TestCase without much headache.

How else can I achieve that? Passing a parameter or somehow making it a variable and avoiding a race condition?

1 Answer 1

1

It sounds like you do not want to redefine the data structure before each test. As long as the tests do not modify the data, I don't think there is any problem with defining the data structure in __init__:

import unittest

class Test(unittest.TestCase):
    def __init__(self, methodName = 'runTest'):
        unittest.TestCase.__init__(self, methodName)
        self.data = range(5)

    def test_getitem(self):
        self.assertEqual(self.data[1],1)

    def test_reversed(self):
        self.assertEqual(list(reversed(self.data)),[4,3,2,1,0])

if __name__ == '__main__':
    import sys
    sys.argv.insert(1,'--verbose')
    unittest.main(argv = sys.argv)

yields

% test.py
test_getitem (__main__.Test) ... ok
test_reversed (__main__.Test) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
Sign up to request clarification or add additional context in comments.

2 Comments

So does setUp get called after EACH test method? The documentation says: before calling the test method. Does that mean each test method?
Yes, the data structure will be recreated before each test method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.