Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's unittest logic

Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.

>>> class MyTest(unittest.TestCase):
    def setUp(self):
        self.i = 1
    def testA(self):
        self.i = 3
        self.assertEqual(self.i, 3)
    def testB(self):
        self.assertEqual(self.i, 3)


>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3

----------------------------------------------------------------------
Ran 2 tests in 0.016s
like image 742
mbesso Avatar asked Dec 02 '22 08:12

mbesso


2 Answers

From http://docs.python.org/lib/minimal-example.html :

When a setUp() method is defined, the test runner will run that method prior to each test.

So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test, with setUp() being run on each new instantiation before the test is executed.

like image 159
pjz Avatar answered Dec 03 '22 20:12

pjz


Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.

Additionally, as others have pointed out, setUp is called before each test.

like image 43
Sebastian Rittau Avatar answered Dec 03 '22 21:12

Sebastian Rittau