【问题标题】:pytest assert introspection in helper functionpytest 在辅助函数中断言自省
【发布时间】:2017-01-07 14:56:42
【问题描述】:

pytest 非常棒 assert 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()

测试报告显示了测试中断言的有用信息,但not for asserts within the 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 断言自省吗?

我找到了一个different, but related question 不幸的是,到目前为止我无法让解决方案正常工作:

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

【问题讨论】:

  • 我不得不将 register_assert_rewrite 放入 __init__.py 文件中。现在它可以工作了......最好删除这个问题,对吧?
  • 不要删除问题,我刚遇到这个问题。所以谢谢。

标签: python pytest


【解决方案1】:

我不得不像这样将 register_assert_rewrite 放入 tests/__init__.py 中:

import pytest

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

【讨论】:

  • 虽然这是问题的正确答案,但我想补充一点,如果您可以选择,您可以将辅助函数移动到 conftest.py 中,该函数默认注册为进行断言重写。
猜你喜欢
  • 2022-11-09
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多