是否可以在每次测试执行后让 pytest 调用 webhook?

Is it possible to have pytest call a webhook after each test executed?

我们正在使用 py.test 来执行我们的集成测试。由于我们有很多测试,我们想在我们使用的仪表板中监控进度。

是否可以配置 webhook 或 pytest 将使用每次测试执行的结果调用的东西 (passed/failed/skipped)?

我确实找到了 teamcity 集成,但我们更愿意在不同的仪表板上监控进度。

这取决于您要发出的数据。如果简单的完成检查就足够了,请在 conftest.py 文件中编写自定义 pytest_runtest_logfinish 挂钩,因为它直接提供了大量测试信息:

def pytest_runtest_logfinish(nodeid, location):
    (filename, line, name) = location
    print('finished', nodeid, 'in file', filename,
          'on line', line, 'name', name)

如果您需要访问测试结果,自定义 pytest_runtest_makereport 是一个不错的选择。您可以从 item 参数获得与上面相同的测试信息(以及更多):

import pytest

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    result = report.get_result()

    if result.when == 'teardown':
        (filename, line, name) = item.location
        print('finished', item.nodeid, 'with result', result.outcome,
              'in file', filename, 'on line', line, 'name', name)

您也可以按照评论中的建议使用夹具拆解选项:

@pytest.fixture(autouse=True)
def myhook(request):
    yield
    item = request.node
    (filename, line, name) = item.location
    print('finished', item.nodeid, 'in file', filename,
          'on line', line, 'name', name)

但是,这取决于您希望您的 webhook 何时发出 - 上面的自定义 hookimpls 将 运行 当测试完成并且所有 fixture 都已完成时,而对于 fixture 示例,您不能保证由于没有明确的灯具顺序,所有灯具都已完成。此外,如果您需要测试结果,则无法在夹具中访问它。