简体   繁体   English

pytest-在输出中显示测试模块名称

[英]pytest - show test module name in output

How can I show the path to the test function next to the function name when a test fails? 测试失败时,如何在函数名称旁边显示测试函数的路径? What I would like to see: 我想看到的是:

======================FAILURES==========================
_____________path/to/module::function_name______________

The headline is controlled by the head_line property of the TestReport class, although beware it's marked experimental, so it's not impossible that it may be renamed or replaced in the next versions. 标题由TestReport类的head_line属性控制,尽管要注意它被标记为实验性的,所以在下一个版本中重命名或替换它并非不可能。 Create a file named conftest.py in your project root dir with the contents: 在项目根目录中创建一个名为conftest.py的文件,内容如下:

import pytest
from _pytest.reports import TestReport


class CustomReport(TestReport):

    @TestReport.head_line.getter
    def head_line(self):
        return f'my headline: {self.nodeid}'


@pytest.hookimpl(tryfirst=True)
def pytest_runtest_makereport(item, call):
    return CustomReport.from_item_and_call(item, call)

Example output: 输出示例:

$ pytest -v
======================================= test session starts =======================================
...
test_spam.py::test_spam PASSED                                                              [ 20%]
test_spam.py::test_eggs FAILED                                                              [ 40%]
test_spam.py::test_bacon[1] FAILED                                                          [ 60%]
test_spam.py::test_bacon[2] FAILED                                                          [ 80%]
test_spam.py::TestFizz::test_buzz FAILED                                                    [100%]

============================================ FAILURES =============================================
______________________________ my headline: test_spam.py::test_eggs _______________________________

    def test_eggs():
>       assert False
E       assert False

test_spam.py:8: AssertionError
____________________________ my headline: test_spam.py::test_bacon[1] _____________________________

n = 1

    @pytest.mark.parametrize('n', range(1,3))
    def test_bacon(n):
>       assert False
E       assert False

test_spam.py:13: AssertionError
____________________________ my headline: test_spam.py::test_bacon[2] _____________________________

n = 2

    @pytest.mark.parametrize('n', range(1,3))
    def test_bacon(n):
>       assert False
E       assert False

test_spam.py:13: AssertionError
_________________________ my headline: test_spam.py::TestFizz::test_buzz __________________________

self = <test_spam.TestFizz object at 0x7f5e44ba2438>

    def test_buzz(self):
>       assert False
E       assert False

test_spam.py:18: AssertionError
=============================== 4 failed, 1 passed in 0.06 seconds ================================

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM