gpt4 book ai didi

python - pytest 是否具有 assertItemsEqual/assertCountEqual 等价物

转载 作者:太空狗 更新时间:2023-10-29 17:34:05 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com