0

I came across the unittest module and I'm a bit confused. I have a question on the following code in my file test_number.py:

import unittest
from module import number

class NamesTestCase(unittest.TestCase):
    def test_number(self):
        verify = number(4)
        self.assertEqual(verify, True)
        
if __name__ == '__main__':
    unittest.main()

(function number from module.py just verifies some properities of given number)

I want to ask about the if __name__ == '__main__' part. I know this ensures that the testing will not take place if I import this module, but why do I have to add this if statement in my test file if I'm running this directly? Or, in other words, why do I have to add this line of code if I know that, when I'm going to use the number() function somewhere in the future, I won't be importing it from test_number.py as test_number() but rather directly from module?

Johny K.
  • 13
  • 3
  • 1
    Does this answer your question? [What does if \_\_name\_\_ == "\_\_main\_\_": do?](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – markwalker_ Dec 07 '20 at 11:30
  • 1
    *You* might not want to import the tests, but a *test runner* might. The last two lines allow you to run the test file directly if you want to, but it's more likely you'll use e.g. `python -m unittest` to import and run *all* test modules in a project. – jonrsharpe Dec 07 '20 at 11:33
  • 2
    @markwalker_ no, the OP knows what it does they're just now sure why they'd do it here. – jonrsharpe Dec 07 '20 at 11:34
  • It is also a safe habit to do so in every file/module, so you do not forget in other modules when it really matters. – Malo Dec 07 '20 at 11:40

0 Answers0