首页 > 解决方案 > pytest - 在输出中显示测试模块名称

问题描述

测试失败时,如何在函数名称旁边显示测试函数的路径?我想看到的:

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

标签: pythonpytest

解决方案


标题由类的head_line属性控制TestReport,但要注意它被标记为实验性的,因此在下一个版本中它可能被重命名或替换并非不可能。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)

示例输出:

$ 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 ================================

推荐阅读