re-import module-under-test to lose context

依然范特西╮ 提交于 2019-11-30 18:51:38
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.

This will reimport the module as new for you:

import sys
del sys.modules['my_module']
import my_module
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!