Harshdeep Singh Harshdeep Singh - 1 month ago 19
Python Question

Change of value of variable in unittest python

import unittest

class TestTemplate(unittest.TestCase):

@classmethod
def setUpClass(self):
self.result = 'error'
print "setUpClass"

@classmethod
def tearDownClass(self):
print "The value of result is, ",self.result
if self.result == 'ok':
print "it is working"
print "The value of cls result is : ", self.result
print "TearDownClass"


class MyTest(TestTemplate):

def test_method_one(self):
self.result = 'ok'
print self.result


if __name__ == '__main__':
unittest.main()


In the
tearDownClass
the value of self.result is
error
, but rather it should be
okay
because I changed it in the method? Is there any resolve to this?

Answer

You are changing a class attribute in the setUp method, and reading it again in the tearDown, because both are class methods. In your test however, you are setting an instance attribute.

You'd have to set it on the class directly instead:

type(self).result = 'ok'

or

MyTest.result = 'ok'

The latter ties it to the current test class, the first option lets it work even in subclasses.

Demo:

>>> import unittest
>>> class TestTemplate(unittest.TestCase):
...     @classmethod
...     def setUpClass(self):
...         self.result = 'error'
...         print "setUpClass"
...     @classmethod
...     def tearDownClass(self):
...         print "The value of result is, ",self.result
...         if self.result == 'ok':
...             print "it is working"
...         print "The value of cls result is : ", self.result
...         print "TearDownClass"
...
>>> class MyTest(TestTemplate):
...     def test_method_one(self):
...         type(self).result = 'ok'
...         print self.result
...
>>> unittest.main(exit=False)
setUpClass
ok
.The value of result is,  ok
it is working
The value of cls result is :  ok
TearDownClass

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
<unittest.main.TestProgram object at 0x103945090>

However, you generally want to avoid changing the test class state during individual tests. Use the existing test runner facilities to track test results instead; all

The setUpClass and tearDownClass methods can apply to multiple tests (depending on how the tests are run), so the state is shared.