re-import module-under-test to lose context

后端 未结 2 1580
情歌与酒
情歌与酒 2021-01-04 10:52

Many Python modules preserve an internal state without defining classes, e.g. logging maintains several loggers accessible via getLogger().

相关标签:
2条回答
  • 2021-01-04 11:29
    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 __name__ == '__main__':
        unittest.sys.argv.insert(1,'--verbose')
        unittest.main(argv = unittest.sys.argv)    
    

    % test.py Test.test_logging passes:

    test_logging (__main__.Test) ... ok
    

    but % test.py Test.test_logging2 does not:

    test_logging2 (__main__.Test) ... ERROR
    

    since the internal state of logging has been reset.

    0 讨论(0)
  • 2021-01-04 11:35

    This will reimport the module as new for you:

    import sys
    del sys.modules['my_module']
    import my_module
    
    0 讨论(0)
提交回复
热议问题