pytest是否具有assertItemsEquity/assertCountEquity等效项 [英] Does pytest have an assertItemsEqual / assertCountEqual equivalent

查看:25
本文介绍了pytest是否具有assertItemsEquity/assertCountEquity等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

unittest.TestCase有一个assertCountEqual method(Python2中的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:
First 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

这篇关于pytest是否具有assertItemsEquity/assertCountEquity等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆