【问题标题】:assertEqual two dicts except one keyassertEqual 除了一个键之外的两个字典
【发布时间】:2020-01-26 09:24:55
【问题描述】:

我需要测试一个函数,它将在django 中返回一个带有rest_framework.test.APITestCase's assertEqual 的字典。字典是这样的:

{
    "first_name": "John",
    "last_name": "Doe",
    "random": some random number
}

除了random 键之外,我如何检查返回的dict 与我的合适结果?

我的意思是 assertEqual(a, result) 应该返回 True 如果这两个字典被传递:

a = {
        "first_name": "John",
        "last_name": "Doe",
        "random": 12
    }

result = {
        "first_name": "John",
        "last_name": "Doe",
        "random": 24
    }

assertEqual 中是否有这种例外,或者我必须使用assert

更新:

感谢大家,我得到了很好的解决方案,但是如果我有一个包含这些字典的列表,比如:

assertEqual(list_of_dicts, expected_result_list)

我的意思是在这两个列表中:

list1 = [
 d1,
 d2,
 d3
]

list2 = [
 d1,
 d2,
 d3
]

应该相等而不考虑每个字典中的random

我是否必须遍历列表并逐一比较字典,还是有最快的解决方案?

【问题讨论】:

  • 您想比较列表中的所有字典吗?即应该[d1, d2, d3]检查d1 == d2d1 == d3d2 == d3
  • @DeepSpace 仅编号 d1 == d1, d2 ==d2, ...
  • 我不确定我是否遵循...为什么d1 不等于d1?是同一个字典
  • @DeepSpace 也许我没有澄清自己。我的意思是来自list1d1 应该等于来自list 2d1。我将编辑我的问题

标签: python django testing assert


【解决方案1】:

您可以复制并修改其中一个字典来纠正差异,而不是复制两个副本并修改两个副本:

a_copy = a.copy()
a_copy['random'] = b['random']
assertEqual(a_copy, b)

【讨论】:

    【解决方案2】:

    您可以创建字典的副本并从那里弹出随机数

    a_copy = a.copy()
    a_copy.pop("random")
    result_copy = result.copy()
    result_copy.pop("random")
    
    assertEqual(a_copy, result_copy)
    

    如果您不想保留原来的使用pop(),直接在现有字典上。

    如果您有两个 dicts 列表,您可以使用 zip 遍历这两个列表并比较每一对

    for l, r in zip(copy.deepcopy(list_of_dicts), copy.deepcopy(expected_result_list)):
        l.pop("random")
        r.pop("random")
        assertEqual(l, r)
    

    【讨论】:

    • 你确定吗?据我所知dict.pop 返回弹出的值
    • @Pynchia 只注意到我自己,已修复。
    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    相关资源
    最近更新 更多