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

时间:2018-03-23 08:49:45

标签: python pytest

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

我知道pytest_runtest_makereport做了类似的事情,但只针对一次测试。但是我想在conftest.py中实现一个钩子或什么来处理整个测试列表,然后py.test应用程序终止。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:2)

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

/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 pytest_terminal_summary 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 ======================

希望这有帮助。

  

请注意!确保在运行测试之前删除了.pyc文件