我正在使用标准库unittest
模块(所以我使用 python -m unittest
运行测试)。
我已经定义了setUpModule
在后台启动子进程(使用 subprocess.Popen
)和 tearDownModule
关闭其输入和输出流,然后调用 os.killpg
其进程 ID。
如果我让测试运行它的过程,这一切都很好,但如果我使用 Ctrl-C
提前停止它,我收到一堆警告,我的终端速度慢得像爬行一样:
KeyboardInterrupt
sys:1: ResourceWarning: unclosed file <_io.FileIO name=6 mode='rb'>
/.../lib/python3.4/importlib/_bootstrap.py:2150: ImportWarning: sys.meta_path is empty
sys:1: ResourceWarning: unclosed file <_io.FileIO name=7 mode='wb'>
sys:1: ResourceWarning: unclosed file <_io.BufferedWriter name='/dev/null'>
有什么方法可以拦截 KeyboardInterrupt
为了正确清理?有没有更好的方法来启动和停止测试模块的外部程序?
最佳答案
根据测试的组织方式,您还可以捕获 KeyboardInterrupt
并在 except
block 中调用 tearDown
方法:
import unittest
class MyTestCase(unittest.TestCase):
def test_one(self):
for i in range(1<<20):
if i % 271 == 0:
print i
@classmethod
def tearDownClass(cls):
print("\nteardown")
if __name__ == '__main__':
try:
unittest.main()
except KeyboardInterrupt:
MyTestCase.tearDownClass()
关于python - 中断 Python 单元测试时关闭资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31865046/