Debosmit Ray Debosmit Ray - 6 months ago 30
Python Question

Unittest - Test for dict equality

I am trying to do a unit-test but don't quite get why these 2 dicts show up as not equal. I was wondering if someone could give me an explanation for this occurrence. My code is...

import unittest

class TestEmailValidator(unittest.TestCase):

def test(self):
known_dict = {
'debo@foobar.com': True,
'debo@gmail.com': False
}

result_dict = {}

for key in known_dict.keys():
result_dict[key] = is_email_valid(key)

# debugger results
# result_dict = {
# 'debo@foobar.com': True,
# 'debo@gmail.com': False
# }

if self.assertEqual(known_dict, result_dict):
print "is_email_valid passed"
else:
print "is_email_valid failed"

if __name__ == '__main__':
unittest.main()


I get the same result for
assertEqual
,
assertEquals
and
assertDictEquals
. I have tried assigning
result_dict
to
known_dict
before the test, but that did not pass either.

It would be great if someone could point me to why this could be happening. Thanks for reading. :)

Answer

You are misusing the assert. All the assertXYZ methods don't return a boolean value, they just raise an exception if the assertion fails. As these methods don't return anything, they implicitly return None. When evaluating None as a boolean it's treated as false, and hence your test prints is_email_valid failed, even though the test actually passes.