Below program:
import unittest
class my_class(unittest.TestCase):
def setUp(self):
print "In Setup"
self.x=100
self.y=200
def test_case1(self):
print "-------------"
print "test case1"
print self.x
print "-------------"
def test_case2(self):
print "-------------"
print "test case2"
print self.y
print "-------------"
def tearDown(self):
print "In Tear Down"
print " "
print " "
if __name__ == "__main__":
unittest.main()
Gives the output:
>>> ================================ RESTART ================================
>>>
In Setup
-------------
test case1
100
-------------
In Tear Down
.In Setup
-------------
test case2
200
-------------
In Tear Down
.
----------------------------------------------------------------------
Ran 2 tests in 0.113s
OK
>>>
>>>
Questions:
what's the meaning of:
if __name__ == "__main__": unittest.main()?Why do we have double underscores prefixed and postfixed for
nameandmain?Where will the object for
my_classbe created?
1 Answer 1
The if __name__ == "__main__": bit allows your code to be imported as a module without invoking the unittest.main() code - that will only be run if this code is invoked as the main entry point of your program (i.e. if you called it like python program.py if your program was in program.py).
The prefix and postfix of double underscores means:
__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g.__init__,__import__or__file__. Never invent such names; only use them as documented.
That comes from the PEP 8 Style Guide - this is a really useful resource to read and internalize.
Finally, your my_class class will be instantiated within the unittest framework as it runs, as it inherits from unittest.TestCase.
main, or a variablename). See e.g. stackoverflow.com/q/19216895/3001761 3. What do you mean "where"?!