python - 中断 Python 单元测试时关闭资源

标签 python unit-testing python-unittest

我正在使用标准库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/

相关文章:

Python - 当 `new` 参数不是默认值时,为什么模拟补丁装饰器不将模拟对象传递给测试函数

python - 使用 unittest 测试 argparse - 退出错误

Python Goose 无法提取日期

java - 在 Mockito 中设置后重置模拟的正确替代方法是什么?

python - 如何测试写入文件的Python函数

reactjs - 如何在 Enzyme React 测试中访问嵌套组件

python - Pytest - 错误与失败

python - 通过没有循环的二维索引数组索引二维 numpy 数组

python - python中通过键迭代字典多个值

python - SQLAlchemy 表之间的多种关系