gpt4 book ai didi

python - pytest 在辅助函数中断言自省(introspection)

转载 作者:太空狗 更新时间:2023-10-29 17:18:09 24 4
gpt4 key购买 nike

pytest 做的很棒 assert introspection 所以很容易找到字符串中的差异,尤其是当差异在空白处时。现在我使用一个稍微复杂的测试助手,我在许多测试用例中重复使用它。助手也有自己的模块,我想为该模块添加断言内省(introspection)。

helpers.py:

...
def my_helper():
assert 'abcy' == 'abcx'

test_mycase.py:

from .helpers import my_helper


def test_assert_in_tc():
assert 'abcy' == 'abcx'


def test_assert_in_helper():
my_helper()

测试报告显示了对测试中的断言有用的信息,但对助手中的断言没有帮助:

=============================================================== FAILURES ================================================================
___________________________________________________________ test_assert_in_tc ___________________________________________________________

def test_assert_in_tc():
> assert 'abcy' == 'abcx'
E assert 'abcy' == 'abcx'
E - abcy
E ? ^
E + abcx
E ? ^

tests/test_pytest_assert.py:9: AssertionError
_________________________________________________________ test_assert_in_helper _________________________________________________________

def test_assert_in_helper():
> my_helper()

tests/test_pytest_assert.py:13:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

def my_helper():
> assert 'abcy' == 'abcx'
E AssertionError

tests/helpers.py:258: AssertionError
======================================================= 2 failed in 0.24 seconds ========================================================

作为解决方法,我使用断言输出了额外的信息,但输出看起来仍然很奇怪,并使代码崩溃。关于如何在帮助程序文件中激活 pytest 断言自省(introspection)的任何想法?

我找到了一个 different, but related question不幸的是,到目前为止我无法使解决方案起作用:

import pytest
from .helpers import my_helper
pytest.register_assert_rewrite('helpers.my_helper')

最佳答案

我必须像这样将 register_assert_rewrite 放入 tests/__init__.py 中:

import pytest

# we want to have pytest assert introspection in the helpers
pytest.register_assert_rewrite('tests.helpers')

关于python - pytest 在辅助函数中断言自省(introspection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522767/

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