Python unittest 的 assertDictContainsSubset 推荐替代方案 [英] Python unittest's assertDictContainsSubset recommended alternative

查看:33
本文介绍了Python unittest 的 assertDictContainsSubset 推荐替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 unittest 编写了一些 Python 测试.我想检查我的某些字典是否至少包含等于某些值的某些属性.如果有额外的值,那就没问题了.assertDictContainsSubset 将是完美的,只是它已被弃用.是否有更好的东西我应该使用,或者我应该递归地断言目标字典中的内容是否相等?

I have some tests in Python written in unittest. I want to check that some of my dictionaries contain at least certain attributes equal to certain values. If there are extra values, that would be fine. assertDictContainsSubset would be perfect, except that it's deprecated. Is there a better thing that I should be using or should I just recursively assert the contents to be equal if they are in the target dictionary?

文档推荐使用 addTypeEqualityFunc,但我确实想在某些情况下使用普通的 assertEqual 来处理 dicts.

The docs recommend using addTypeEqualityFunc, but I do want to use the normal assertEqual for dicts in some cases.

推荐答案

如果您正在测试 dict A 是否是 dict B 的子集,我想我会编写一个函数,尝试从 dict B 中提取 dict A 的内容创建一个新的 dict C,然后 assertEqual(A,C).

If you were testing if dict A is a subset of dict B, I think I would write a function that tries to extract the content of dict A from dict B making a new dict C and then assertEqual(A,C).

def extractDictAFromB(A,B):
    return dict([(k,B[k]) for k in A.keys() if k in B.keys()])

那你就可以了

assertEqual(A,extractDictAFromB(A,B))

这篇关于Python unittest 的 assertDictContainsSubset 推荐替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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