如果可以用`==`比较字典,为什么需要assertDictEqual? - python

老实说,我一直使用assertDictEqual,因为有时候我不使用它,就会得到信息,相等的词是不一样的。

但是...我知道dict可以通过==运算符进行比较:

>>> {'a':1, 'b':2, 'c': [1,2]} == {'b':2, 'a':1, 'c': [1,2]}
True

我实际上可能需要assertDictEqual的地方?

参考方案

基本上,它允许unittest为您提供有关测试失败原因的更多信息。比较这两个测试:

class DemoTest(unittest.TestCase):

    D1 = {'a': 1, 'b': 2, 'c': [1, 2]}
    D2 = {'a': 1, 'b': 2, 'c': [1]}

    def test_not_so_useful(self):
        assert self.D1 == self.D2

    def test_useful(self):
        self.assertDictEqual(self.D1, self.D2)

及其输出:

Failure
Traceback (most recent call last):
  File "...x.py", line 86, in test_not_so_useful
    assert self.D1 == self.D2
AssertionError

Failure
Traceback (most recent call last):
  File "...x.py", line 80, in test_useful
    self.assertDictEqual(self.D1, self.D2)
AssertionError: {'a': 1, 'c': [1, 2], 'b': 2} != {'a': 1, 'c': [1], 'b': 2}
- {'a': 1, 'b': 2, 'c': [1, 2]}
?                         ---

+ {'a': 1, 'b': 2, 'c': [1]}

在后者中,您可以确切地看到它们之间的区别,而不必自己解决。注意,您可以使用标准的assertEqual而不是assertDictEqual,结果相同。每个the docs

...通常不需要直接调用这些方法。

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

python JSON对象必须是str,bytes或bytearray,而不是'dict - python

在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…