How to Write a pytest Test Function with assert Equal in Python

Define simple pytest test functions that use assert to verify result equality and run them with pytest.main.

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

Requires third-party packages — install first
pip install pytest

Python code

19 lines
Python 3.9+
import pytest

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

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

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

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

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

Output

stdout
============================= test session starts ==============================
platform darwin -- Python 3.11.0, pytest-7.4.0, pluggy-1.3.0
rootdir: /path/to/your/test
collected 3 items

test_file.py ...                                                          [100%]

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

How it works

Each test function is named with a test_ prefix so pytest discovers it automatically. Inside the test, you call the function under test and use the assert statement to compare the actual result to the expected value. If the assertion fails, pytest reports a detailed diff showing both the expected and actual values. Running pytest.main([__file__, "-v"]) lets you execute the tests directly from the script with verbose output.

Common mistakes

  • Forgetting the test_ prefix on function names, causing pytest to skip them
  • Using `assert result == expected` without any message; adding a helpful message improves debugging
  • Naming the test file without a `test_` prefix, so pytest doesn't collect it by default

Variations

  1. Use `pytest.approx` for floating-point comparisons to avoid precision issues
  2. Parameterize the test with `@pytest.mark.parametrize` to test multiple input sets without duplicating code

Real-world use cases

  • Verifying that a data transformation function returns the correct result for known inputs.
  • Ensuring that an API client correctly parses a response payload into expected fields.
  • Checking that a validation helper returns the expected error dictionary for invalid data.

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.