I would like to assert that two dictionaries are equal, using Python's unittest
, but ignoring the values of certain keys in the dictionary, in a convenient syntax, like this:
from unittest import TestCase
class Example(TestCase):
def test_example(self):
result = foobar()
self.assertEqual(
result,
{
"name": "John Smith",
"year_of_birth": 1980,
"image_url": ignore(), # how to do this?
"unique_id": ignore(), #
},
)
To be clear, I want to check that all four keys exist, and I want to check the values of "name"
and "year_of_birth"
, (but not "image_url"
or "unique_id
"), and I want to check that no other keys exist.
I know I could modify result
here to the key-value pairs for "image_url"
and "unique_id"
, but I would like something more convenient that doesn't modify the original dictionary.
(This is inspired by Test::Deep
for Perl 5.)
The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.
Using == operator to Compare Two Dictionaries Here we are using the equality comparison operator in Python to compare two dictionaries whether both have the same key value pairs or not.
assertEqual() in Python is a unittest library function that is used in unit testing to check the equality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are equal assertEqual() will return true else return false.
to say that something is certainly true: [ + that ] He asserts that she stole money from him.
There is unittest.mock.ANY
which compares equal to everything.
from unittest import TestCase
import unittest.mock as mock
class Example(TestCase):
def test_happy_path(self):
result = {
"name": "John Smith",
"year_of_birth": 1980,
"image_url": 42,
"unique_id": 'foo'
}
self.assertEqual(
result,
{
"name": "John Smith",
"year_of_birth": 1980,
"image_url": mock.ANY,
"unique_id": mock.ANY
}
)
def test_missing_key(self):
result = {
"name": "John Smith",
"year_of_birth": 1980,
"unique_id": 'foo'
}
self.assertNotEqual(
result,
{
"name": "John Smith",
"year_of_birth": 1980,
"image_url": mock.ANY,
"unique_id": mock.ANY
}
)
def test_extra_key(self):
result = {
"name": "John Smith",
"year_of_birth": 1980,
"image_url": 42,
"unique_id": 'foo',
"maiden_name": 'Doe'
}
self.assertNotEqual(
result,
{
"name": "John Smith",
"year_of_birth": 1980,
"image_url": mock.ANY,
"unique_id": mock.ANY
}
)
def test_wrong_value(self):
result = {
"name": "John Smith",
"year_of_birth": 1918,
"image_url": 42,
"unique_id": 'foo'
}
self.assertNotEqual(
result,
{
"name": "John Smith",
"year_of_birth": 1980,
"image_url": mock.ANY,
"unique_id": mock.ANY
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With