Ali SAID OMAR
Ali SAID OMAR

Reputation: 6792

How to unittest assertDictNotEqual?

I wrote a contextlib that update environment variable and for unittest wrote test as:

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))

But I wonder if I can do better than the use of with self.assertRaises(AssertionError) to assert on dict difference ?

Upvotes: 3

Views: 550

Answers (1)

awesoon
awesoon

Reputation: 33691

I found a ticket in the Python bugtracker, related to missed methods in the unittest module. Here is the quote from the discussion:

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."

And, as for me, I don't think if assertDictNotEqual could be useful, since there is exactly one case, when the assert could fail. You should just use assertNotEqual

Upvotes: 4

Related Questions