test_extend_fixture_module_class.py

Overview

This file contains a minimal pytest test module demonstrating how fixtures can be defined and extended within the same test file, particularly showcasing the interaction between module-level and class-level fixtures sharing the same name. The primary focus is to illustrate pytest's fixture resolution and overriding behavior when a class-level fixture shadows a module-level fixture.

The module defines:

This setup is useful for understanding fixture scoping, overriding, and dependency injection in pytest.


Detailed Explanation

Module-level Fixture

@pytest.fixture
def spam():
    return "spam"

Class: TestSpam

This test class contains a class-level fixture and a test method.

Class-level Fixture: spam

@pytest.fixture
def spam(self, spam):
    return spam * 2

Test Method: test_spam

def test_spam(self, spam):
    assert spam == "spamspam"

Implementation Details and Algorithms


Interaction with Other Parts of the System


Usage Example

Running the tests in this file using:

pytest test_extend_fixture_module_class.py

Would yield:

collected 1 item

test_extend_fixture_module_class.py .                                  [100%]

============================== 1 passed in 0.01s ==============================

This confirms that the fixture overriding works as intended.


Mermaid Class Diagram

classDiagram
    class TestSpam {
        +spam(self, spam): str
        +test_spam(self, spam): None
    }
    class spam_fixture_module {
        +spam(): str
    }
    TestSpam ..> spam_fixture_module : depends on

Summary

This file serves as a concise example illustrating pytest's fixture overriding and scope resolution. It shows how a class-level fixture can reuse and extend a module-level fixture by injecting it as a parameter and modifying its return value. This pattern is useful for organizing tests with hierarchical fixture dependencies, enabling flexible and maintainable test code.