[Tutor] Do not understand why test is running.

Steven D'Aprano steve at pearwood.info
Fri Aug 21 05:13:21 CEST 2015

On Thu, Aug 20, 2015 at 09:01:50PM -0500, boB Stepp wrote:

> import unittest
> # import modules to be tested:
> import mcm.db.manager
> class ManagerTestCase(unittest.TestCase):
>     def setUp(self):
>         # Insert setup code here...
>         pass
>     def test_open_db(self):
>         pass
>     def tearDown(self):
>         # Insert tear-down code here...
>         pass
> #if __name__ == "__main__":
> #    unittest.main()

The two commented out lines at the end would, if uncommented, run 
unittest.main() if and only if you are running this specific module as a 
thread. In other words, if you were to run:

python /path/to/the/test.py

then __name__ would be set to the string "__main__", the if clause would 
trigger, and unittest.main() would run. Since those lines are commented 
out, that cannot happen.

But that's not the only way to run unit tests. Another way to run unit 
tests is to tell the unittest module to run whatever tests it discovers 
inside a module or package. Which is what you have done:

> Out of curiosity, I changed the last two lines to comments, as I am
> still feeling my way around this package structure and how things
> work.  I was surprised when I ran my test now:
> E:\Projects\mcm>py -m unittest discover -v
> test_open_db (test.db.test_manager.ManagerTestCase) ... ok
> ----------------------------------------------------------------------
> Ran 1 test in 0.000s
> OK
> Obviously I was not expecting this!  Why did the test run?  I thought
> it would not happen without those final two lines.

No, although they both involve unittest, the method of invoking unittest 
are different. What you actually did was:

"Hey unittest, see what tests you can discover, and run those tests."

instead of:

"Hey Python, run this script."
(script says) "Hey unittest, run the tests you find inside me."


More information about the Tutor mailing list