我的测试中有一个自定义装饰器,只是为测试提供了一些额外的信息。我喜欢这样,当测试失败时,我可以打印一些这些信息并将其显示在故障部分,因此我们的构建工具可以很好地显示它。
现在我只有一些看起来像这样的代码:
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
if outcome.get_result().outcome != "passed":
print("Some extra info: {}".format(item.function.detail1))
问题在于,当测试失败时,我得到如下输出:
test_foo.py .Some extra info: more info
F
================================== FAILURES ===================================
__________________________________ test_foo2 __________________________________
@info("more info")
def test_foo():
> raise ValueError("OH NO")
E ValueError: OH NO
test_foo.py:11: ValueError
我想在底部显示Some extra info: more info
。是否有可能以某种方式挂钩?
答案 0 :(得分:0)
这是一个快速有效的解决方案,尽管我敢肯定有更多的py(test)thonic方法可以做到这一点。
test.py
def test_fail():
assert False
def test_pass():
assert True
def test_fail_2():
assert False
conftest.py
import pytest
FAIL_EXTRA_INFO = []
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
if outcome.get_result().outcome != "passed":
FAIL_EXTRA_INFO.append("Some extra info: {}".format(item))
def pytest_terminal_summary(terminalreporter, exitstatus):
for extra_info in FAIL_EXTRA_INFO:
print(extra_info)
执行结果:
$ pytest -v
======================== test session starts =======================
platform linux -- Python 3.7.0, pytest-3.6.2, py-1.5.4, pluggy-0.6.0
-- /home/user/.virtualenvs/test3.7/bin/python3.7
cachedir: .pytest_cache
rootdir: /home/user/projects/so, inifile:
collected 3 items
so/test_api.py::test_fail FAILED [ 33%]
so/test_api.py::test_pass PASSED [ 66%]
so/test_api.py::test_fail_2 FAILED [100%]
============================== FAILURES ============================
______________________________ test_fail ___________________________
def test_fail():
> assert False
E assert False
slotr_tracker/test_api.py:2: AssertionError
_____________________________ test_fail_2 _________________________
def test_fail_2():
> assert False
E assert False
slotr_tracker/test_api.py:10: AssertionError
Some extra info: <Function 'test_fail'>
Some extra info: <Function 'test_fail_2'>
================ 2 failed, 1 passed in 0.03 seconds ===============
如果您想更深入地研究主题,这里为pytest hooks reference。