重新导入被测模块以丢失上下文 [英] re-import module-under-test to lose context
本文介绍了重新导入被测模块以丢失上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
许多Python模块保留内部状态而不定义类,例如 logging
维护多个记录器可通过 getLogger()
访问。
Many Python modules preserve an internal state without defining classes, e.g. logging
maintains several loggers accessible via getLogger()
.
如何测试这样的模块?
使用标准的 unittest
工具,我想在 TestCase
类中进行各种测试以重新导入我的模块 - 测试,以便每次失去其背景。可以这样做吗?
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 __name__ == '__main__':
unittest.sys.argv.insert(1,'--verbose')
unittest.main(argv = unittest.sys.argv)
%test.py Test.test_logging
传递:
test_logging (__main__.Test) ... ok
但
%test.py Test.test_logging2
不会:
test_logging2 (__main__.Test) ... ERROR
自内部状态记录
已重置。
这篇关于重新导入被测模块以丢失上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文