如何对 assertDictNotEqual 进行单元测试?

How to unittest assertDictNotEqual?

我写了一个更新环境变量的上下文库,并为 unittest 写了测试:

previous_env = copy.deepcopy(os.environ)
with MYContext() as my_context:
    with self.assertRaises(AssertionError):
        self.assertDictEqual(dict(os.environ), dict(previous_env))
self.assertDictEqual(dict(os.environ), dict(previous_env))

但我想知道我是否可以比使用 with self.assertRaises(AssertionError) 断言字典差异做得更好?

我在 Python bugtracker 中发现了一个 ticket,与 unittest 模块中遗漏的方法有关。以下是讨论中的引述:

Hi,

I am the original reporter of the bug. Please forgive me if this is not the place for discussing the issue.

I've thought about it, and stuff like assertDictNotEqual or assertSequenceNotEqual aren't really necessary - it is much easier (and shorter) to use assertNotEqual, and there's no need for any special formatting needed to say that something is equal when it shouldn't.

This is not the case for assertNotRegexpMatches, though. assertNot(re.match(...)) tells me only that False is not True. I'd like it to say how the text matches the regex (the matching part that is). (Sorry for repeating myself, I try to be clearer this time.)

So, this issue could be renamed to "Implement assertNotRegexpMatches."

而且,就我而言,我不认为 assertDictNotEqual 是否有用,因为 只有一种情况 ,断言可能会失败。你应该只使用 assertNotEqual