如何在pytest中捕获KeyboardInterrupt?

How to capture KeyboardInterrupt in pytest?

UnitTests 具有捕获 KeyboardInterrupt、完成测试然后报告结果的功能。

-c, --catch

Control-C during the test run waits for the current test to end and then reports all the results so far. A second Control-C raises the normal KeyboardInterrupt exception.

See Signal Handling for the functions that provide this functionality.

c.f. https://docs.python.org/2/library/unittest.html#command-line-options

在 PyTest 中,Ctrl+C 将停止会话。

有没有办法做到与 UniTests 相同的方法:

谢谢

[编辑 2016 年 11 月 11 日]

我试图将钩子放入我的 conftest.py 文件中,但它似乎不起作用并无法捕获。特别是,下面的toto.txt.

什么都不写
def pytest_keyboard_interrupt(excinfo):
    with open('toto.txt', 'w') as f: f.write("Hello")
    pytestmark = pytest.mark.skip('Interrupted Test Session')

有没有人有新的建议?

看看pytest的hookspec.

他们有关键字中断的钩子。

def pytest_keyboard_interrupt(excinfo):
""" called for keyboard interrupt. """

您的问题可能出在挂钩的执行顺序上,因此 pytest 在执行挂钩之前退出。如果在预先存在的键盘中断处理中发生未处理的异常,则可能会发生这种情况。

为确保您的挂钩更快执行,请按照 here 所述使用 tryfirsthookwrapper

conftest.py文件中写入以下内容:

import pytest

@pytest.hookimpl(tryfirst=True)
def pytest_keyboard_interrupt(excinfo):
    with open('toto.txt', 'w') as f:
        f.write("Hello")
    pytestmark = pytest.mark.skip('Interrupted Test Session')