How to Write pytest Test Function Assert Equal in Python

Write three pytest test functions that assert the result of an add() function equals an expected numeric value.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 12 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

16 lines
Python 3.9+
import pytest

def add(a, b):
    return a + b

def test_add_positive_numbers():
    assert add(2, 3) == 5

def test_add_negative_numbers():
    assert add(-1, -2) == -3

def test_add_mixed_numbers():
    assert add(5, -3) == 2

if __name__ == "__main__":
    pytest.main([__file__, "-v"])

Output

stdout
============================= test session starts ==============================
platform linux -- Python 3.11.0, pytest-7.4.0, pluggy-1.0.0
rootdir: /home/user
collected 3 items

test_example.py ...                                                       [100%]

============================== 3 passed in 0.01s ===============================

How it works

Each test function starts with test_ so pytest auto-discovers it. The assert statement checks that add(a, b) equals the expected result; if false, pytest raises AssertionError and marks the test failed. Using functions keeps tests isolated and readable. Running pytest.main([__file__, "-v"]) when the script executes directly runs the tests with verbose output.

Common mistakes

  • Forgetting to import pytest even though it's only used for main invocation
  • Not naming test functions with the `test_` prefix, so pytest skips them
  • Comparing floats with `==` without tolerance, causing flaky tests

Variations

  1. Use `@pytest.mark.parametrize` to generate multiple test cases from one function
  2. Use the `unittest` module with `self.assertEqual()` instead of pytest style

Real-world use cases

  • Verifying pure functions (add, string transformations) in a library's test suite.
  • Running regression checks in CI pipelines after every commit to catch broken logic.
  • Validating math-heavy code like price calculations in a web application.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.