pytest:如何在会话结束时获取所有失败测试的列表?(以及使用xdist时)

Ita*_*tay 11 python testing unit-testing pytest xdist

我想列出在会话结束时使用的所有测试

Pytest允许您定义一个hook pytest_sessionfinish(session, exitstatus),在会话结束时调用该钩子,我希望在该列表中找到该钩子。

session_pytest.main.Session具有属性items(type list)的实例,但是我无法找到item该列表中的每一个是否传递失败。

  1. 在会话结束时如何检索所有失败测试的列表?
  2. 使用pytest-xdist插件时该如何完成,我想在主流程中获取该列表。使用此插件,session甚至items在母版中都没有属性:

    def pytest_sessionfinish(session, exitstatus):
        if os.environ.get("PYTEST_XDIST_WORKER", "master") == "master":
             print(hasattr(session, "items"))  # False
    
    Run Code Online (Sandbox Code Playgroud)

Aar*_*n V 8

运行pytest with -rf使其在末尾打印失败测试的列表。

来自py.test --help

  -r chars              show extra test summary info as specified by chars
                        (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed,
                        (p)passed, (P)passed with output, (a)all except pP.
                        Warnings are displayed at all times except when
                        --disable-warnings is set
Run Code Online (Sandbox Code Playgroud)

这是您得到的:

$ py.test -rf
================= test session starts =================
platform darwin -- Python 3.7.2, pytest-4.3.1, py-1.6.0, pluggy-0.7.1
[...]
=============== short test summary info ===============
FAILED test_foo.py::test_foo_is_flar
FAILED test_spam.py::test_spam_is_mostly_pork
FAILED test_eggs.py::test_eggs_are_also_spam
=== 3 failed, 222 passed, 8 warnings in 12.52 seconds ==
Run Code Online (Sandbox Code Playgroud)


z0r*_*z0r 5

--result-log已弃用。您可以改为-v在运行时输出测试用例名称。如果将其通过管道传输到文件中,则可以查询它。因此,如果您从脚本运行测试,您可以执行以下操作:

pytest -v | tee log.txt
grep -E '::.*(FAILURE|ERROR)' log.txt
Run Code Online (Sandbox Code Playgroud)


小智 4

如果您想要测试结果,可以使用 hook runtest_makereport

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == 'call' and rep.failed:
        mode = 'a' if os.path.exists('failures') else 'w'
        try:  # Just to not crash py.test reporting
          pass  # the test 'item' failed
        except Exception as e:
            pass
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!当 xdist 未使用时,这似乎效果很好,我可以将失败的测试保存到一个全局变量中,以供最后的“pytest_sessionfinish”使用。**当使用 xdist** 时,仅为工作进程调用 `pytest_runtest_makereport`,而不为 master 调用,因此它们可以通过文件进行通信,但更好的解决方案是使用 **在 master 中调用的 `pytest_report_teststatus` 和 `pytest_runtest_logreport` ** 可用于收集失败的测试。 (3认同)