pytest中的自定义断言应该否决标准断言

时间:2016-03-17 08:42:43

标签: assert pytest

我编写了一个自定义断言函数来比较两个列表中的项目,这样订单并不重要,使用pytest_assertrepr_compare。这可以正常工作,并在列表内容不同时报告失败。

但是,如果自定义断言通过,则在默认的'=='断言上失败,因为一个列表的第0项不等于另一个列表的第0项。

有没有办法阻止默认声明启动?

assert ['a', 'b', 'c'] == ['b', 'a', 'c'] # custom assert passes 
                                          # default assert fails

自定义断言功能是:

def pytest_assertrepr_compare(config, op, left, right):
    equal = True
    if op == '==' and isinstance(left, list) and isinstance(right, list):
        if len(left) != len(right):
            equal = False
        else:
            for l in left:
                if not l in right:
                    equal = False
        if equal:
            for r in right:
                if not r in left:
                    equal = False
    if not equal:
        return ['Comparing lists:',
                '   vals: %s != %s' % (left, right)]

2 个答案:

答案 0 :(得分:2)

我找到了最简单的方法来组合py.test& pyhamcrest。在您的示例中,使用contains_inanyorder matcher:

很容易
from hamcrest import assert_that, contains_inanyorder

def test_first():
    assert_that(['a', 'b', 'c'], contains_inanyorder('b', 'a', 'c'))

答案 1 :(得分:1)

你可以使用python set

assert set(['a', 'b', 'c']) == set(['b', 'a', 'c']) 

这将返回true

相关问题