Ita*_*tay 11 python testing unit-testing pytest xdist
我想列出在会话结束时未使用的所有测试。
Pytest允许您定义一个hook pytest_sessionfinish(session, exitstatus),在会话结束时调用该钩子,我希望在该列表中找到该钩子。
session是_pytest.main.Session具有属性items(type list)的实例,但是我无法找到item该列表中的每一个是否传递失败。
使用pytest-xdist插件时该如何完成,我想在主流程中获取该列表。使用此插件,session甚至items在母版中都没有属性:
def pytest_sessionfinish(session, exitstatus):
    if os.environ.get("PYTEST_XDIST_WORKER", "master") == "master":
         print(hasattr(session, "items"))  # False
运行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
这是您得到的:
$ 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 ==
--result-log已弃用。您可以改为-v在运行时输出测试用例名称。如果将其通过管道传输到文件中,则可以查询它。因此,如果您从脚本运行测试,您可以执行以下操作:
pytest -v | tee log.txt
grep -E '::.*(FAILURE|ERROR)' log.txt
小智 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