pytest assert introspection in helper function

折月煮酒 提交于 2019-12-03 11:47:27

问题


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 ========================================================

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')

回答1:


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')


来源:https://stackoverflow.com/questions/41522767/pytest-assert-introspection-in-helper-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!