0

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:

  1. what's the meaning of: if __name__ == "__main__": unittest.main()?

  2. Why do we have double underscores prefixed and postfixed for name and main?

  3. Where will the object for my_class be created?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Bahubali Patil
  • 1,127
  • 1
  • 16
  • 23
  • See this question http://stackoverflow.com/questions/419163/what-does-if-name-main-do – HavelTheGreat Feb 10 '15 at 18:08
  • 1. Ask one question at a time. 2. Leading and trailing double underscores are used to indicate *""magic" objects or attributes that live in user-controlled namespaces"*, per [PEP-0008](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles). This prevents them clashing with the user's names (e.g. you can call a function `main`, or a variable `name`). See e.g. http://stackoverflow.com/q/19216895/3001761 3. What do you mean *"where"*?! – jonrsharpe Feb 10 '15 at 18:12

1 Answers1

2

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.

Lukas Graf
  • 30,317
  • 8
  • 77
  • 92
jimjkelly
  • 1,631
  • 14
  • 15