unittest.TestCase有一个 assertCountEqual method(Python 2中的assertItemsEqual,可以说是一个更好的名称),它比较两个可迭代对象,并检查它们是否包含相同数量的相同对象,而无需考虑其顺序。

pytest提供类似的东西吗?所有显而易见的替代方法(例如,文档中提到的在每侧调用set(x)sorted(x)Counter(list(x)))均无效,因为我要比较的对象是字典列表,并且字典不可散列。

最佳答案

pytest没有提供assertCountEqual,但是我们可以使用unittest的来:

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

关于python - pytest是否具有等效的assertItemsEqual/assertCountEqual,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41605889/

10-09 21:37