gpt4 book ai didi

python - 如何在 py.test 运行结束时获取 TestReports 列表?

转载 作者:太空狗 更新时间:2023-10-30 02:53:27 26 4
gpt4 key购买 nike

我想在所有测试结束时获得所有测试的列表(例如以 py.test TestReport 的形式)。

我知道 pytest_runtest_makereport 做类似的事情,但只针对单个测试。但我想在 conftest.py 中实现一个 Hook 或其他东西,以便在 py.test 应用程序终止之前处理整个测试列表。

有办法吗?

最佳答案

这里是一个可以帮助你的例子。文件结构:

/example:
__init__.py # empty file
/test_pack_1
__init__.py # empty file
conftest.py # pytest hooks
test_my.py # a few tests for demonstration

test_my.py 中有 2 个测试:

def test_one():
assert 1 == 1
print('1==1')


def test_two():
assert 1 == 2
print('1!=2')

conftest.py 示例:

import pytest
from _pytest.runner import TestReport
from _pytest.terminal import TerminalReporter


@pytest.hookimpl(hookwrapper=True)
def pytest_terminal_summary(terminalreporter): # type: (TerminalReporter) -> generator
yield
# you can do here anything - I just print report info
print('*' * 8 + 'HERE CUSTOM LOGIC' + '*' * 8)

for failed in terminalreporter.stats.get('failed', []): # type: TestReport
print('failed! node_id:%s, duration: %s, details: %s' % (failed.nodeid,
failed.duration,
str(failed.longrepr)))

for passed in terminalreporter.stats.get('passed', []): # type: TestReport
print('passed! node_id:%s, duration: %s, details: %s' % (passed.nodeid,
passed.duration,
str(passed.longrepr)))

Documentation says that pytest_terminal_summary has exitstatus arg

在没有任何附加选项的情况下运行测试:py.test ./example。输出示例:

example/test_pack_1/test_my.py .F
********HERE CUSTOM LOGIC********
failed! node_id:test_pack_1/test_my.py::test_two, duration: 0.000385999679565, details: def test_two():
> assert 1 == 2
E assert 1 == 2

example/test_pack_1/test_my.py:7: AssertionError
passed! node_id:test_pack_1/test_my.py::test_one, duration: 0.00019907951355, details: None

=================================== FAILURES ===================================
___________________________________ test_two ___________________________________

def test_two():
> assert 1 == 2
E assert 1 == 2

example/test_pack_1/test_my.py:7: AssertionError
====================== 1 failed, 1 passed in 0.01 seconds ======================

希望这对您有所帮助。

Note! Make sure that .pyc files was removed before running tests

关于python - 如何在 py.test 运行结束时获取 TestReports 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49445609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com