【问题标题】:Show exhaustive information for passed tests in pytest在 pytest 中显示通过测试的详尽信息
【发布时间】:2018-02-08 05:37:01
【问题描述】:

当测试失败时,会有一个输出指示测试的上下文,例如

=================================== FAILURES ===================================
______________________________ Test.test_sum_even ______________________________

numbers = [2, 4, 6]

    @staticmethod
    def test_sum_even(numbers):
        assert sum(numbers) % 2 == 0
>       assert False
E       assert False

test_preprocessing.py:52: AssertionError

如果我也想通过测试获得同样的东西怎么办?这样我就可以快速检查传递给测试的参数是否正确?

我尝试了命令行选项行 --full-trace-l--tb long-rpP,但它们都不起作用。

有什么想法吗?

【问题讨论】:

  • 你想让pytest注释代码的每一行成功吗?你很快就会失去上下文。
  • @phd 好吧,PyCharm 会帮我处理的。

标签: python testing pytest


【解决方案1】:

使用 --verbose 标志执行 pytest 将导致它在执行时列出每个测试的完全限定名称,例如:

tests/dsl/test_ancestor.py::TestAncestor::test_finds_ancestor_nodes
tests/dsl/test_and.py::TestAnd::test_aliased_as_ampersand
tests/dsl/test_and.py::TestAnd::test_finds_all_nodes_in_both_expressions
tests/dsl/test_anywhere.py::TestAnywhere::test_finds_all_nodes_when_no_arguments_given_regardless_of_the_context
tests/dsl/test_anywhere.py::TestAnywhere::test_finds_multiple_kinds_of_nodes_regardless_of_the_context
tests/dsl/test_anywhere.py::TestAnywhere::test_finds_nodes_regardless_of_the_context
tests/dsl/test_axis.py::TestAxis::test_finds_nodes_given_the_xpath_axis
tests/dsl/test_axis.py::TestAxis::test_finds_nodes_given_the_xpath_axis_without_a_specific_tag

【讨论】:

  • 谢谢。此外,如果您将--color=yes 添加到其中,输出将具有绿色的“:PASSED”。
【解决方案2】:

如果您只是从通过的测试用例中获取标准输出,那么您需要将-s 选项传递给pytest 以防止捕获标准输出。 pytest docs 中提供了有关标准输出抑制的更多信息。

【讨论】:

  • 不是通过的测试用例的标准输出,而是pytest的输出,好像测试失败了。
【解决方案3】:

pytest 没有这个功能。它的作用是在断言失败时向您显示异常中的错误。

一种解决方法是使用 python 的logging 模块明确包含您希望从通过测试中看到的信息,然后使用来自pytestcaplog 固定装置。

例如,func.py 的一个版本可能是:

import logging

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('my-even-logger')


def is_even(numbers):
    res = sum(numbers) % 2 == 0
    if res is True:
        log.warning('Sum is Even')
    else:
        log.warning('Sum is Odd')

#... do stuff ...

然后是test_func.py:

import logging
import pytest
from func import is_even

@pytest.fixture
def my_list():
    numbers = [2, 4, 6]
    return numbers
 
def test_is_even(caplog, my_list):
    with caplog.at_level(logging.DEBUG, logger='my-even-logger'):
        is_even(my_list)
    assert 'Even' in caplog.text

如果您运行 pytest -s test_even.py 并且由于测试通过,记录器会向您显示以下消息:

test_even.py WARNING:my-sum-logger:Sum is Even

【讨论】:

  • 我无法查看 INFO 级别的日志。在pytest.ini 中添加log_cli=true 解决了它。找到解决方案here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多