Testing with pytest
pytest is the most popular Python testing framework. It's simpler than unittest, uses plain assert statements, and has powerful fixtures and plugins.
20 min•By Priygop Team•Updated 2026
pytest
pytest
# pip install pytest
# Run: pytest test_file.py -v
# pytest uses simple assert statements!
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# Test functions (start with test_)
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_multiply():
assert multiply(3, 4) == 12
assert multiply(-2, 3) == -6
# Test exceptions
def test_divide_by_zero():
try:
result = 10 / 0
assert False, "Should have raised"
except ZeroDivisionError:
pass # Expected!
# Parametrized tests
import functools
test_cases = [
(2, 3, 5),
(0, 0, 0),
(-1, 1, 0),
(100, 200, 300),
]
def test_add_parametrized():
for a, b, expected in test_cases:
assert add(a, b) == expected, f"add({a}, {b}) should be {expected}"
# Fixtures (setup/teardown)
# @pytest.fixture
# def sample_data():
# return [1, 2, 3, 4, 5]
#
# def test_sum(sample_data):
# assert sum(sample_data) == 15
# Run all tests
print("=== pytest Demo ===")
tests = [test_add, test_multiply, test_divide_by_zero, test_add_parametrized]
for test in tests:
try:
test()
print(f" ✅ {test.__name__} PASSED")
except AssertionError as e:
print(f" ❌ {test.__name__} FAILED: {e}")
print(f"\n{len(tests)} tests passed!")
# pytest commands:
print("\n=== pytest Commands ===")
print("pytest # run all tests")
print("pytest -v # verbose output")
print("pytest -k 'test_add' # run matching tests")
print("pytest --cov=mymodule # code coverage")Tip
Tip
pytest auto-discovers tests in test_*.py files. Use pytest -v for verbose output and pytest -x to stop on first failure.
Diagram
Loading diagram…
pytest > unittest. Use fixtures for DRY. Mock external services. Run in CI with tox for multi-version.
Common Mistake
Warning
Writing tests that depend on each other or on execution order. Each test should be independent and repeatable.
Quick Quiz
Practice Task
Note
(1) Write pytest tests with assert. (2) Use @pytest.fixture for setup. (3) Parametrize tests with @pytest.mark.parametrize.