【问题标题】:Describing failing assert statements in imported functions with pytest用 pytest 描述导入函数中失败的断言语句
【发布时间】:2018-02-28 16:05:57
【问题描述】:

Pytest 可以很好地打印失败的断言语句中的变量值(例如,here)。

但是,这不适用于导入函数中的断言失败,

example.py

def func():
    b = 1
    assert b == 0

test_func.py

from example import func

def test_func():
    func()

运行pytest test_example.py 将产生,

    def test_func():
>       func()

test_example.py:4: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    def func():
        b = 1
>       assert b == 0
E       AssertionError

example.py:4: AssertionError

换句话说,它不会打印关于断言失败原因的调试信息(即 b 的值为 1)。

有没有办法解决这个问题?我应该在 Pytest 存储库中打开 Github 问题吗?

注意:如果我将函数定义放在同一个test_example.py 中,我确实会得到预期的结果,

    def func():
        b = 1
>       assert b == 0
E       assert 1 == 0

test_example.py:3: AssertionError

但在许多用例中无法做到这一点(例如,断言在某些包中失败),因此我的问题......

【问题讨论】:

  • 它应该可以工作,只是在本地测试它并报告它失败的原因并显示b 值。如果您还检查文档应该工作:assert & failure demo
  • 感谢您的检查。您会注意到,在这两个示例中,函数都是在同一个测试文件中定义的,而不是从其他地方导入的。这很好用。我在上面更新了我的问题。但在许多用例中你不能这样做(例如断言在某些包中失败),因此我的问题......
  • 啊哈,我明白了,你是对的。
  • 在 PTYHONPATH 目录中有 example.py 吗?你添加了什么 assert b==0, "b was not equal 0" 等等。
  • 它在当前文件夹中,所以是的。是的,这可行,但这里 pytest 的重点是应该为您生成异常消息...

标签: python pytest


【解决方案1】:

您可以使用pytest.register_assert_rewrite 函数为您的模块启用此功能。

在从模块中导入你的函数之前,你必须调用 register_assert_rewrite,所以你可以将它放在 conftest.py 中。

conftest.py

import pytest
pytest.register_assert_rewrite("example")

原始解决方案链接:https://github.com/pytest-dev/pytest/issues/4671

【讨论】:

    【解决方案2】:

    在基本方式中,您需要请求详细输出:

    py.test -vvvv

    此外,您还可以指定详细程度:

    logging.WARN,    # -v
    logging.INFO,    # -vv
    logging.DEBUG,   # -vvv
    logging.TRACE,   # -vvvv
    logging.GARBAGE  # -vvvvv
    

    如需更多自定义日志记录,您可以查看pytest docs

    【讨论】:

    • 感谢您的回复。刚刚尝试过(使用 Python 3.6.4、pytest-3.3.2、Linux),这并没有改变我只得到一个 AssertionError 而没有其他详细信息的事实..
    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多