0
0
PyTesttesting~10 mins

Context manager fixtures in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses a pytest fixture implemented as a context manager to set up and tear down a resource. It verifies that the resource is correctly initialized and cleaned up after the test.

Test Code - pytest
PyTest
import pytest

class Resource:
    def __init__(self):
        self.active = False
    def start(self):
        self.active = True
    def stop(self):
        self.active = False

@pytest.fixture
def resource():
    res = Resource()
    res.start()
    yield res
    res.stop()

def test_resource_active(resource):
    assert resource.active is True
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1pytest starts test executionpytest test runner initialized-PASS
2pytest calls the 'resource' fixture before the testResource instance created with active = False-PASS
3Resource.start() is called inside fixture, setting active = TrueResource active state is True-PASS
4Fixture yields the resource instance to the testTest receives resource with active = True-PASS
5Test asserts resource.active is Trueresource.active is Trueassert resource.active is TruePASS
6Test completes, pytest resumes fixture teardownResource active state still True-PASS
7Resource.stop() is called in fixture teardown, setting active = FalseResource active state is False-PASS
8pytest finishes test executionAll resources cleaned up-PASS
Failure Scenario
Failing Condition: Resource.start() is not called, so resource.active remains False
Execution Trace Quiz - 3 Questions
Test your understanding
What does the fixture do before yielding the resource to the test?
ACalls res.stop() to deactivate the resource
BDoes nothing before yielding
CCalls res.start() to activate the resource
DRaises an exception
Key Result
Using context manager style fixtures with yield in pytest helps ensure setup and cleanup happen reliably around tests.