Pytest 和 PyCharm:如何始终获得 <Click to see difference>?

问题描述 投票:0回答:1

PyCharm 中 Pytest 的断言输出存在差异,具体取决于同一文件或另一个文件中带有断言的 if 函数。

让我们考虑一个例子。

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

如果我使用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)

输出:

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

如果我使用assert_in_another_file运行:

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

输出:

>       assert d1 == d2
E       AssertionError

没有点击查看差异,没有实际,预期

是Pytest还是Pycharm的问题?如何修复它并始终获得“点击查看差异”?

pycharm pytest assert
1个回答
0
投票

如果我使用这个

tmp_1.py
名称,我可以重现这一点。 如果您将文件重命名为可通过 pytest 发现的名称,例如
test_tmp_1.py
,您将看到正常的断言。

这是因为良好的断言输出归功于 pytest 断言内省。

您可以阅读更多内容 https://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html

如果您不想重命名文件以使其可以被 pytest 发现,您可以添加 register_assert_rewrite

pytest.register_assert_rewrite("tmp_1")

并从中看到漂亮的 pytest 风格的断言。

© www.soinside.com 2019 - 2024. All rights reserved.