0
0
PytestHow-ToBeginner ยท 3 min read

How to Assert Dictionary Equality in pytest: Simple Guide

In pytest, you can assert that two dictionaries are equal using the simple assert dict1 == dict2 statement. Pytest will automatically compare keys and values and show differences if the assertion fails.
๐Ÿ“

Syntax

Use the assert keyword followed by the equality check between two dictionaries. Pytest handles the comparison and reports detailed differences if they are not equal.

  • dict1: The first dictionary to compare.
  • dict2: The second dictionary to compare.
  • ==: Checks if both dictionaries have the same keys and corresponding values.
python
assert dict1 == dict2
๐Ÿ’ป

Example

This example shows how to write a pytest test function that asserts two dictionaries are equal. If they differ, pytest will show which keys or values do not match.

python
def test_dict_equality():
    expected = {"name": "Alice", "age": 30, "city": "Paris"}
    actual = {"name": "Alice", "age": 30, "city": "Paris"}
    assert actual == expected
Output
============================= test session starts ============================== collected 1 item test_sample.py . [100%] ============================== 1 passed in 0.01s ===============================
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using assert dict1 is dict2 which checks identity, not equality.
  • Comparing dictionaries with different key types or missing keys.
  • Ignoring nested dictionaries where deep equality is needed.

Always use == for value equality, not is.

python
def test_wrong_assert():
    dict1 = {"a": 1}
    dict2 = {"a": 1}
    # Wrong: checks if both are the same object (will fail)
    # assert dict1 is dict2
    # Right: checks if contents are equal
    assert dict1 == dict2
๐Ÿ“Š

Quick Reference

ActionCode ExampleDescription
Check dict equalityassert dict1 == dict2Passes if both dicts have same keys and values
Check dict identity (not recommended)assert dict1 is dict2Checks if both variables point to same object
Compare nested dictsassert dict1 == dict2Works if nested dicts have same structure and values
โœ…

Key Takeaways

Use assert dict1 == dict2 to check dictionary equality in pytest.
Avoid using 'is' for dictionary comparison as it checks object identity, not content.
Pytest shows detailed differences when dictionary assertions fail.
Ensure nested dictionaries are structured the same for equality to pass.
Simple assert statements are enough; no extra pytest functions needed.