Pytest Tutorial: Fixtures, Parametrize, Mocking
Writing robust, maintainable software requires comprehensive automated testing. While Python's built-in unittest library provides a solid foundation, it often requires heavy boilerplate code and verbose assertions. Pytest has emerged as the definitive standard testing framework in the Python ecosystem, offering concise syntax, powerful fixture injection, seamless parametrization, and detailed failure reporting.
This comprehensive tutorial walks through the core features of Pytest that every Python developer must master: Test Discovery, Fixtures, Parametrization, and Mocking External Dependencies.
1. Installation and Pytest Conventions
Pytest can be installed via pip. Pytest automatically discovers test files matching the naming convention test_*.py or *_test.py and functions prefixed with test_.
# Terminal installation command
pip install pytest
# test_sample.py
def add(a: int, b: int) -> int:
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
2. Pytest Fixtures: Managing Setup and Teardown
Fixtures allow developers to define reusable setup and teardown logic (such as database connections, mock API clients, or test file instances) that can be cleanly injected into test functions as arguments.
import pytest
@pytest.fixture
def sample_user_database():
# Setup phase: Initialize mock database state
db = {"admin": "supersecret", "developer": "codecrown"}
yield db
# Teardown phase: Clean up resources after test completes
db.clear()
def test_user_authentication(sample_user_database):
assert sample_user_database["developer"] == "codecrown"
assert "guest" not in sample_user_database
3. Parametrizing Tests for Multiple Scenarios
Instead of writing repetitive test functions for different input combinations, @pytest.mark.parametrize allows you to run a single test function across multiple sets of arguments.
import pytest
def is_even(number: int) -> bool:
return number % 2 == 0
@pytest.mark.parametrize("input_num, expected", [
(2, True),
(3, False),
(0, True),
(-4, True),
(7, False)
])
def test_is_even(input_num, expected):
assert is_even(input_num) == expected
4. Mocking External APIs and Dependencies
Unit tests should run in isolation without making real network requests or interacting with live third-party services. Python's built-in unittest.mock library integrates seamlessly with Pytest to mock out external dependencies.
from unittest.mock import patch
import pytest
# A service function that makes an external API call
def fetch_user_status(user_id: int) -> str:
# Imagine this makes an expensive external HTTP request
response = requests.get(f"https://api.example.com/users/{user_id}")
return response.json().get("status")
@patch("requests.get")
def test_fetch_user_status(mock_get):
# Configure the mock return value
mock_get.return_value.json.return_value = {"status": "active"}
status = fetch_user_status(42)
assert status == "active"
mock_get.assert_called_once_with("https://api.example.com/users/42")
Conclusion
Mastering Pytest—from organizing test suites and leveraging reusable fixtures to parametrizing test cases and mocking external HTTP requests—enables developers to write reliable, high-coverage automated testing pipelines for Python applications.