2017-01-12 61 views
8

unittest.TestCase具有(在Python 2,这可以说是一个更好的名字assertItemsEqual),其比较两个iterables并且它们包含相同数量的相同对象的检查,而无需考虑一个assertCountEqual method其订购。是否pytest具有assertItemsEqual/assertCountEqual等效

pytest是否提供类似的东西?所有显而易见的替代方案(例如,在文档中提到的每个方面调用set(x),sorted(x)Counter(list(x)))都不起作用,因为我比较的东西是字典列表,字典不可散列。

+1

为什么'排序'工作?它不需要任何可排除的东西。 –

+0

我同意@TheCompiler。你唯一需要的是指定'key'参数来比较字典:http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the -dictionary功能于蟒蛇。 –

+1

@TheCompiler不,你说得对,但它确实需要你排序的东西与>相媲美,哪些字典不是。 –

回答

1

pytest不提供assertCountEqual,但我们可以只使用单元测试的

import unittest 

def test_stuff(): 
    case = unittest.TestCase() 
    a = [{'a': 1}, {'b': 2}] 
    b = [{'b': 2}] 
    case.assertCountEqual(a, b) 

和输出是体面的,太

$ py.test 
============================= test session starts ============================== 
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 
rootdir: /home/they4kman/.virtualenvs/tmp-6626234b42fb350/src, inifile: 
collected 1 item 

test_stuff.py F 

=================================== FAILURES =================================== 
__________________________________ test_stuff __________________________________ 

    def test_stuff(): 
     case = unittest.TestCase() 
     a = [{'a': 1}, {'b': 2}] 
     b = [{'b': 2}] 
>  case.assertCountEqual(a, b) 

test_stuff.py:7: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/usr/lib/python3.6/unittest/case.py:1182: in assertCountEqual 
    self.fail(msg) 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <unittest.case.TestCase testMethod=runTest> 
msg = "Element counts were not equal:\nFirst has 1, Second has 0: {'a': 1}" 

    def fail(self, msg=None): 
     """Fail immediately, with the given message.""" 
>  raise self.failureException(msg) 
E  AssertionError: Element counts were not equal: 
E  First has 1, Second has 0: {'a': 1} 

/usr/lib/python3.6/unittest/case.py:670: AssertionError 
=========================== 1 failed in 0.07 seconds ========================== 

旁注:the implementation of assertCountEqual包括分支为不可分类的类型,其中does a bunch of bookkeeping and compares each item with every other item

相关问题