【问题标题】:How can you test that two dictionaries are equal with pytest in python如何测试两个字典是否与 python 中的 pytest 相等
【发布时间】:2017-11-09 12:02:58
【问题描述】:

试图用 pytest 断言两个具有嵌套内容的字典彼此相等(顺序无关紧要)。这样做的pythonic方法是什么?

【问题讨论】:

  • 你试过assert d1 == d2吗?顺便说一句,您的嵌套内容是什么?

标签: python python-3.x pytest


【解决方案1】:

不要花时间自己编写此逻辑。使用默认测试库unittest提供的功能即可

from unittest import TestCase
TestCase().assertDictEqual(expected_dict, actual_dict)

【讨论】:

    【解决方案2】:

    pytest 的魔法足够聪明。通过写作

    assert {'a': {'b': 2, 'c': {'d': 4} } } == {'a': {'b': 2, 'c': {'d': 4} } }
    

    你将有一个关于相等性的嵌套测试。

    【讨论】:

      【解决方案3】:

      我想一个简单的断言相等测试应该没问题:

      >>> d1 = {n: chr(n+65) for n in range(10)}
      >>> d2 = {n: chr(n+65) for n in range(10)}
      >>> d1 == d2
      True
      >>> l1 = [1, 2, 3]
      >>> l2 = [1, 2, 3]
      >>> d2[10] = l2
      >>> d1[10] = l1
      >>> d1 == d2
      True
      >>> class Example:
          stub_prop = None
      >>> e1 = Example()
      >>> e2 = Example()
      >>> e2.stub_prop = 10
      >>> e1.stub_prop = 'a'
      >>> d1[11] = e1
      >>> d2[11] = e2
      >>> d1 == d2
      False
      

      【讨论】:

        【解决方案4】:

        通用方法是:

        import json
        
        # Make sure you sort any lists in the dictionary before dumping to a string
        
        dictA_str = json.dumps(dictA, sort_keys=True)
        dictB_str = json.dumps(dictB, sort_keys=True)
        
        assert dictA_str == dictB_str
        

        【讨论】:

        • 有效,但是后面要找两个对象的区别很繁琐
        【解决方案5】:
        assert all(v == actual_dict[k] for k,v expected_dict.items()) and len(expected_dict) == len(actual_dict)
        

        【讨论】:

        • 这是不必要的。如果两个 dicts 相等,那么它们的长度必然相同,它们的元素也将相同。 dict1==dict2 几乎没有效果。同样要严格,如果需要逐项检查,您也需要检查嵌套元素。
        • 所说的简单评估完全是多维检查,而不是 is 运算符,它只检查内存指针。
        【解决方案6】:

        您的问题不是很具体,但据我所知,您要么尝试检查长度是否相同

        a = [1,5,3,6,3,2,4]
        b = [5,3,2,1,3,5,3]
        
        if (len(a) == len(b)):
            print True
        else:
            print false
        

        或检查列表值是否相同

        import collections
        
        compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
        compare([1,2,3], [1,2,3,3])
        print compare #answer would be false
        compare([1,2,3], [1,2,3])
        print compare #answer would be true
        

        但你也可以使用字典

        x = dict(a=1, b=2)
        y = dict(a=2, b=2)
        
        if(x == y):
            print True
        else:
            print False
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多