Search code examples
pycharmpytestassert

Pytest and PyCharm: how to get <Click to see difference> always?


There is a difference in the assert output of Pytest in PyCharm depending on if function with assert in the same file or in the another file.

Let's consider an example.

tmp.py:

from utils.tmp_1 import assert_in_another_file


def test_assert():
    d1 = {
        1: 2,
        3: 4
    }
    d2 = {
        3: 4,
        5: 6
    }
    assert_in_the_same_file(d1, d2)
    # assert_in_another_file(d1, d2)


def assert_in_the_same_file(d1, d2):
    assert d1 == d2

tmp_1.py:

def assert_in_another_file(d1, d2):
    assert d1 == d2

If I run with assert_in_the_same_file:

def test_assert():
    d1 = {
        1: 2,
        3: 4
    }
    d2 = {
        3: 4,
        5: 6
    }
    assert_in_the_same_file(d1, d2)

Output:

Expected :{3: 4, 5: 6}
Actual   :{1: 2, 3: 4}
<Click to see difference>

If I run with assert_in_another_file:

def test_assert():
    d1 = {
        1: 2,
        3: 4
    }
    d2 = {
        3: 4,
        5: 6
    }
    assert_in_another_file(d1, d2)

Output:

>       assert d1 == d2
E       AssertionError

No Click to see difference, No Actual, Expected

Is it Pytest or Pycharm issue? How to fix it and get "Click to see difference" always?


Solution

  • I can reproduce that if I use this tmp_1.py name. I you rename the file to the discoverable by pytest name like test_tmp_1.py you will see normal assertion.

    This is because nice assertion output is thanks to pytest assertion introspection.

    You can read more in https://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html

    If you do not want to rename the file to make it discoverable by pytest you can add register_assert_rewrite

    pytest.register_assert_rewrite("tmp_1")
    

    And see nice pytest-style assertions from it.