test_fixtures_request_different_scope.py

Overview

This file contains pytest fixtures and test cases designed to demonstrate and verify the behavior of pytest fixtures with different scopes, particularly focusing on how fixtures defined at different levels (module-level and class-level) interact and get executed. Specifically, it illustrates how pytest resolves fixture dependencies and the order in which fixtures are invoked when multiple fixtures with the same name but different scopes exist.

The tests in this file emphasize the interaction between module-level and class-level fixtures named `inner` and how they affect the shared `order` list. The `order` list is used to track the sequence of fixture invocations, which is then asserted in the tests to confirm the expected order and scope resolution behavior.


Detailed Explanation of Contents

Fixtures

order (module-level fixture)

@pytest.fixture
def order():
    return []

outer (module-level fixture)

@pytest.fixture
def outer(order, inner):
    order.append("outer")

Classes and Their Fixtures

TestOne

@pytest.fixture
def inner(self, order):
    order.append("one")
def test_order(self, order, outer):
    assert order == ["one", "outer"]

TestTwo

@pytest.fixture
def inner(self, order):
    order.append("two")
def test_order(self, order, outer):
    assert order == ["two", "outer"]

Important Implementation Details and Behavior


Interaction with Other Parts of the System


Usage Example

To run the tests and verify fixture order behavior, execute:

pytest test_fixtures_request_different_scope.py

Expected output is that both tests pass, confirming that:


Mermaid Class Diagram

classDiagram
    class TestOne {
        +inner(self, order)
        +test_order(self, order, outer)
    }
    class TestTwo {
        +inner(self, order)
        +test_order(self, order, outer)
    }
    class Fixtures {
        +order()
        +outer(order, inner)
    }
    TestOne ..|> Fixtures : uses
    TestTwo ..|> Fixtures : uses

Summary

This file is a focused pytest test module demonstrating how pytest fixtures can be scoped and overridden at different levels (module and class) and how fixture dependencies are resolved. It uses an `order` list to track and assert the sequence of fixture calls, providing clarity on fixture invocation order and scope precedence. This is useful for developers needing to understand complex fixture interactions in pytest testing suites.