Skip to content

How to Fix AssertionError in Python Testing

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix AssertionError in Python Testing. We cover key concepts, practical examples, and best practices.

Python raises AssertionError when an assert statement evaluates to False, signaling that a condition the programmer assumed to be true is actually false.

The Wrong Way

def divide(a, b):
    assert b != 0
    return a / b

print(divide(10, 0))

This produces:

Traceback (most recent call last):
  File "script.py", line 5, in <module>
    print(divide(10, 0))
  File "script.py", line 2, in divide
    assert b != 0
AssertionError

The Right Way

Use proper error handling instead of assertions for runtime validation:

def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero is not allowed")
    return a / b

try:
    print(divide(10, 0))
except ValueError as e:
    print(f"Error: {e}")

Output:

Error: Division by zero is not allowed

Step-by-Step Fix

1. Use assert for debugging, not validation

def calculate_total(prices):
    assert all(p > 0 for p in prices), "Prices must be positive"
    return sum(prices)

# In production, use proper validation
def calculate_total_safe(prices):
    if not all(p > 0 for p in prices):
        raise ValueError("All prices must be positive")
    return sum(prices)

2. Disable assertions in production with -O

python3 -O script.py

With -O, all assert statements are ignored. Never rely on assertions for security or critical validation.

3. Use unittest assertions properly

import unittest

class TestMath(unittest.TestCase):
    def test_division(self):
        result = divide(10, 2)
        self.assertEqual(result, 5)

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

4. Add descriptive messages to assert

def validate_user(age):
    assert age >= 0, f"Age cannot be negative, got {age}"
    assert age < 150, f"Age seems unrealistic, got {age}"
    return True

Prevention Tips

  • Use assert for internal invariants and testing, not for user input validation.
  • Never rely on assertions for security checks -- they can be disabled.
  • Always provide a descriptive message with your assertions.
  • Use proper exception types (ValueError, TypeError) for input validation.
  • Run tests with assertions enabled and production code with them disabled.

Common Mistakes with assertionerror

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Can AssertionError be caught?

Yes. AssertionError is a regular exception that inherits from Exception. You can catch it with except AssertionError:, but this is usually a bad practice -- assertions should fail loudly.

When should I use assert instead of a conditional?

Use assert for conditions that should always be true if the code is correct (internal invariants). Use conditionals with proper exceptions for conditions that can fail due to bad input or external factors.

Are assertions removed in optimized Python?

Yes. Running Python with the -O flag removes all assert statements. Code that depends on assertions being executed will silently skip those checks in optimized mode.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro