In this lesson, you will learn how to reduce code duplication by injecting shared objects directly into your test functions using Pytest fixtures.
The Power of Dependency Injection
When writing tests, you often find yourself repeating the same setup code—such as initializing a database connection, creating a temporary file, or configuring a complex object—at the start of every test function. This leads to brittle, cluttered code.
Instead of manually creating these dependencies inside your tests, Dependency Injection allows you to define a fixture once and request it as an argument. Pytest automatically "injects" the result of that fixture function into your test whenever it is needed.
Practical Implementation
Imagine you have a function that processes data and requires a custom configuration object. Rather than instantiating that object inside every test, you define a fixture:
import pytest
class AppConfig:
def __init__(self):
self.env = "testing"
@pytest.fixture
def app_config():
"""Fixture to provide a standard config object."""
return AppConfig()
def test_process_data(app_config):
# The app_config object is injected automatically!
assert app_config.env == "testing"
In the example above, the test_process_data function receives the app_config instance simply by naming it as an argument. Pytest matches the argument name to the function decorated with @pytest.fixture.
Why Use This Pattern?
- Decoupling: Your test doesn't need to know how to build the
AppConfigobject; it only needs to know that it requires one to run. - Reusability: If you decide to change how your configuration is initialized (e.g., adding a new parameter), you only need to update the fixture in one location, rather than hunting through dozens of test functions.
- Readability: Your test logic remains focused on the "what" (the assertion) rather than the "how" (the setup boilerplate).
By treating your test dependencies as modular inputs, you keep your test suite lean, maintainable, and highly expressive.
Key Takeaway: By using Pytest fixtures, you can inject dependencies as function arguments, eliminating repetitive setup code and keeping your tests focused on verifying behavior.