2016-03-17 72 views
2

我写了一个自定义断言函数来比较两个列表中的项目,使用pytest_assertrepr_compare命令不重要。这工作正常,并在列表内容不同时报告失败。pytest中的自定义断言应该否定标准断言

但是,如果自定义断言通过,它会在默认的'=='声明中失败,因为一个列表的项目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)] 

回答

1

我发现最简单的方法combinate py.test & pyhamcrest。在您的例子很容易使用contains_inanyorder匹配:

from hamcrest import assert_that, contains_inanyorder 

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

你可以使用一个python集

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

这将返回true

+0

如果你想也比较的数量不工作项目。 –