当前位置:  开发笔记 > 编程语言 > 正文

pytest是否具有assertItemsEqual/assertCountEqual等价物

如何解决《pytest是否具有assertItemsEqual/assertCountEqual等价物》经验,为你挑选了1个好方法。

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

pytest提供类似的东西吗?所有明显的替代方案(例如调用set(x),sorted(x)Counter(list(x))文档中提到的每一方)都不起作用,因为我正在比较的是字典列表,而且字典不可清除.



1> theY4Kman..:

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 = 
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 ==========================

旁注:的实现assertCountEqual包括专门用于不可哈希类型的分支,该分支执行大量记账并将每个项目与其他每个项目进行比较

推荐阅读
拾味湖
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有