pytest 在辅助函数中断言自省 [英] pytest assert introspection in helper function

查看:78
本文介绍了pytest 在辅助函数中断言自省的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pytest 做了很棒的 assert introspection 所以很容易找到字符串中的差异,特别是如果差异是在空白处.现在我使用了一个稍微复杂的测试助手,我在许多测试用例中重用了它.帮助程序也有自己的模块,我想为该模块添加断言自省.

pytest does wonderful assert introspection so it is easy to find differences in strings especially if the difference is in white space. Now I use a slightly complicated test helper that I reuse in many testcases. The helper has its own module, too and for that module I want to add 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()

测试报告显示测试中断言的有用信息,但不显示助手中的断言:

test report shows helpful information for asserts within tests but 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 断言自省?

As a workaround I output additional info with the assert but the output still looks weird and makes the code blow up. Any ideas how I can activate pytest assert introspection within the helper file?

我发现了一个不同但相关的问题 不幸的是,到目前为止我无法得到解决方案:

I found a different, but related question unfortunately I could not get the solution working so far:

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

推荐答案

我不得不像这样把 register_assert_rewrite 放到 tests/__init__.py 中:

I had to put the register_assert_rewrite into tests/__init__.py like so:

import pytest

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

这篇关于pytest 在辅助函数中断言自省的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆