Of course! Let's dive deep into assertEqual in Python.

What is assertEqual?
assertEqual is a function from Python's built-in unittest framework. It's a method used in unit testing to check if two values are equal.
In simple terms, you use it to write a test that verifies your code is working correctly. You tell the test: "I expect A to be equal to B. If they are, the test passes. If they're not, the test fails and raises an AssertionError."
The Basic Syntax
The general syntax is:
self.assertEqual(first, second, msg=None)
Let's break down the parameters:

first: The first value you want to compare.second: The second value you expectfirstto be equal to.msg(optional): A custom message to be displayed if the assertion fails. If you don't provide one, a default message will be shown.
How to Use assertEqual in a Test Case
You can't just call assertEqual anywhere. It must be used inside a class that inherits from unittest.TestCase.
Here is a complete, step-by-step example.
Step 1: Create a simple Python file with a function to test.
Let's say you have a file named calculator.py:
# calculator.py
def add(a, b):
"""Adds two numbers and returns the result."""
return a + b
def divide(a, b):
"""Divides two numbers and returns the result."""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
Step 2: Create a test file.
Now, create another file named test_calculator.py in the same directory. This is where we'll use assertEqual.

# test_calculator.py
import unittest
from calculator import add, divide
class TestCalculator(unittest.TestCase):
"""Test cases for the calculator functions."""
def test_add(self):
"""Test the add function."""
# Test case 1: Two positive numbers
result = add(2, 3)
self.assertEqual(result, 5, "2 + 3 should be 5")
# Test case 2: A positive and a negative number
result = add(-10, 5)
self.assertEqual(result, -5, "-10 + 5 should be -5")
# Test case 3: Two zeros
result = add(0, 0)
self.assertEqual(result, 0, "0 + 0 should be 0")
def test_divide(self):
"""Test the divide function."""
# Test case 1: Normal division
result = divide(10, 2)
self.assertEqual(result, 5, "10 / 2 should be 5")
# Test case 2: Division resulting in a float
result = divide(7, 2)
self.assertEqual(result, 3.5, "7 / 2 should be 3.5")
# Test case 3: Division by zero (This should raise an error)
with self.assertRaises(ValueError):
divide(5, 0)
if __name__ == '__main__':
unittest.main()
Step 3: Run the test.
Open your terminal or command prompt, navigate to the directory containing the files, and run the test file:
python -m unittest test_calculator.py
You will see output like this, indicating that all tests passed:
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
The represents the three test methods that ran successfully.
What Happens When assertEqual Fails?
Let's intentionally break a test to see the failure message.
Modify test_calculator.py and make a mistake in our expectation:
# In test_calculator.py, inside the test_add method
def test_add(self):
# ...
result = add(2, 3)
# Let's incorrectly expect the result to be 6
self.assertEqual(result, 6) # msg is optional
Now, run the test again:
python -m unittest test_calculator.py
The output will show a failure, including the file name, line number, and a helpful message:
F
======================================================================
FAIL: test_add (__main__.TestCalculator)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_calculator.py", line 10, in test_add
self.assertEqual(result, 6)
AssertionError: 5 != 6
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
This failure message is extremely useful for debugging. It tells you exactly what the actual value (5) was and what you expected it to be (6).
Important: assertEqual vs.
This is a crucial point of confusion for beginners.
assertEqual(a, b)is a test method. It checks ifa == bisTrue. If it'sFalse, it raises anAssertionError. It's for testing.a == bis an operator. It evaluates an expression and returns a boolean value (TrueorFalse). It's for comparison in your program's logic.
You should use assertEqual in your tests and in your application code.
Example of Misuse:
# WRONG: This is not how you write a test.
def test_add_wrong():
result = add(2, 3)
if result == 5:
print("Test passed!")
else:
print("Test failed!")
This "test" is not as robust. It doesn't automatically integrate with test runners, it doesn't provide structured output, and it doesn't stop the test suite on failure. The unittest framework handles all of that for you.
Variations of assertEqual
The unittest framework provides several related assertion methods for different comparison scenarios.
| Method | Checks if... | Example |
|---|---|---|
assertNotEqual(a, b) |
a is not equal to b. |
self.assertNotEqual(2 + 2, 5) |
assertTrue(x) |
x is True. |
self.assertTrue(is_user_logged_in) |
assertFalse(x) |
x is False. |
self.assertFalse(is_locked) |
assertIs(a, b) |
a and b are the exact same object (identity check). |
self.assertIs(obj, None) |
assertIsNot(a, b) |
a and b are not the same object. |
self.assertIsNot(obj, None) |
assertIsNone(x) |
x is None. |
self.assertIsNone(returned_value) |
assertIsNotNone(x) |
x is not None. |
self.assertIsNotNone(returned_value) |
assertIn(a, b) |
a is in b (e.g., in a list or string). |
self.assertIn('apple', ['apple', 'banana']) |
assertNotIn(a, b) |
a is not in b. |
self.assertNotIn('cherry', ['apple', 'banana']) |
Summary
| Feature | Description |
|---|---|
| What it is | A method from Python's unittest framework for testing equality. |
| Purpose | To verify that your code produces the expected output. |
| Usage | Inside a class that inherits from unittest.TestCase. |
| Syntax | self.assertEqual(actual_value, expected_value, "Optional failure message") |
| Success | The test continues to the next one. |
| Failure | Raises an AssertionError with a detailed message. |
| Key Distinction | Use assertEqual for testing and for program logic. |
