unittest.py doesn't play well with trace.py - why?

A simpler workaround is to pass the name of the module explicitly to unittest.main:

import unittest

class Tester(unittest.TestCase):
    def test_true(self):
        self.assertTrue(True)

if __name__ == "__main__":
    unittest.main(module='foobar')

trace messes up test discovery in unittest because of how trace loads the module it is running. trace reads the module source code, compiles it, and executes it in a context with a __name__ global set to '__main__'. This is enough to make most modules behave as if they were called as the main module, but doesn't actually change the module which is registered as __main__ in the Python interpreter. When unittest asks for the __main__ module to scan for test cases, it actually gets the trace module called from the command line, which of course doesn't contain the unit tests.

coverage.py takes a different approach of actually replacing which module is called __main__ in sys.modules.


I don't know why trace doesn't work properly, but coverage.py does:

$ coverage run foobar.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
$ coverage report
Name     Stmts   Miss  Cover
----------------------------
foobar       6      0   100%