- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
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/
我在 Python 2 下使用 unittest.TestCase.assertItemsEqual 函数遇到了一个有趣的情况;在这里发布我的发现以供后代使用。 以下单元测试在 Python 2 下应
我在使用 unittest.TestCase.assertItemsEqual(或 Python 3 中的 assertCountEqual)时遇到了一个让我有点困惑的问题,我无法在这里找到解决方案,
Python 2.7 docs声明 assertItemsEqual “等同于 assertEqual(sorted(expected), sorted(actual))”。在下面的示例中,除了 te
unittest.TestCase 有一个 assertCountEqual method (Python 2 中的 assertItemsEqual,可以说这是一个更好的名称),它比较两个可迭代对象
我是一名优秀的程序员,十分优秀!