Self.attr is reset between tests in unittest.TestCase

I would like to use the self.attr class, but it does not seem to be persistent between tests:

 import unittest class TestNightlife(unittest.TestCase): _my_param = 0 def test_a(self): print 'test A = %d' % self._my_param self._my_param = 1 def test_b(self): print 'test B = %d' % self._my_param self._my_param = 2 if __name__ == "__main__": unittest.main() 

This gives the following result:

 test A = 0 test B = 0 

Does the unittest.TestCase instance unittest.TestCase between test runs? Why?

+6
source share
1 answer

This works because unittest.main () creates a separate object for each test (in this case, two objects are created).

About your motivation: the test should not change the global state. You must return the global state to the state before the test in tearDown or test yourself. It is very problematic if tests change their global state, you will end up in scenarios that you cannot predict sooner or later.

 import unittest class TestNightlife(unittest.TestCase): _my_param = 0 def test_a(self): print 'object id: %d' % id(self) print 'test A = %d' % self._my_param self._my_param = 1 def test_b(self): print 'object id: %d' % id(self) print 'test B = %d' % self._my_param self._my_param = 2 if __name__ == "__main__": unittest.main() 

exit:

 object id: 10969360 test A = 0 .object id: 10969424 test B = 0 . ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK 
+7
source

Source: https://habr.com/ru/post/915596/


All Articles