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

前端 未结 3 2044
闹比i
闹比i 2021-01-04 11:45

Wow. I found out tonight that Python unit tests written using the unittest module don\'t play well with coverage analysis under the trace module.

3条回答
  •  佛祖请我去吃肉
    2021-01-04 12:27

    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.

提交回复
热议问题