re-import module-under-test to lose context
Many Python modules preserve an internal state without defining classes, e.g. logging maintains several loggers accessible via getLogger() . How do you test such a module? Using the standard unittest tools, I would like the various tests inside a TestCase class to re-import my module-under-test so that each time it loses its context. Can this be done? import unittest import sys class Test(unittest.TestCase): def tearDown(self): try: del sys.modules['logging'] except KeyError: pass def test_logging(self): import logging logging.foo=1 def test_logging2(self): import logging print(logging.foo) if