gpt4 book ai didi

python - 使用 pytest 描述导入函数中失败的 assert 语句

转载 作者:行者123 更新时间:2023-12-04 16:45:26 26 4
gpt4 key购买 nike

Pytest 很好地打印了失败的 assert 语句中的变量值(例如 here )。

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

示例.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

但在许多用例中不能这样做(例如,某些包中的断言失败),因此我的问题......

最佳答案

您可以使用 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

关于python - 使用 pytest 描述导入函数中失败的 assert 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49033809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com