Bird
Raised Fist0
PyTesttesting~20 mins

Context manager fixtures in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Context Manager Fixture Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a pytest fixture using context manager
What will be the output when running this pytest test with the given fixture?
PyTest
import pytest

class Resource:
    def __init__(self):
        self.active = False
    def __enter__(self):
        self.active = True
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.active = False

@pytest.fixture
def resource():
    with Resource() as r:
        yield r

def test_resource_active(resource):
    assert resource.active
ATest passes because resource.active is True inside the test
BTest fails because resource.active is False inside the test
CTest fails due to fixture not yielding any value
DTest raises an exception because Resource does not support context manager
Attempts:
2 left
💡 Hint
Remember that the fixture yields the resource while it is active inside the context manager.
assertion
intermediate
2:00remaining
Correct assertion to check resource active state in context manager fixture
Given this fixture and test, which assertion correctly verifies the state of the resource during the test?
PyTest
import pytest

class Resource:
    def __init__(self):
        self.active = False
    def __enter__(self):
        self.active = True
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.active = False

@pytest.fixture
def resource():
    with Resource() as r:
        yield r

def test_resource_cleanup(resource):
    pass  # Which assertion goes here?
Aassert hasattr(resource, 'active')
Bassert resource.active is False
Cassert resource.active is True
Dassert resource is None
Attempts:
2 left
💡 Hint
The test runs while the resource is active inside the fixture yield.
🔧 Debug
advanced
2:00remaining
Common misconception: Why does this context manager fixture seem to cause a test to hang?
Consider this fixture and test. Some developers think the test never finishes. What is the most likely reason for this misconception?
PyTest
import pytest

class Resource:
    def __enter__(self):
        print('Entering')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exiting')

@pytest.fixture
def resource():
    with Resource() as r:
        yield r
        print('After yield')

def test_hang(resource):
    assert True
AThe fixture never exits the with block because __exit__ is missing a return statement
BThe fixture hangs because the yield is inside the with block and the with block never ends
CThe fixture hangs because __exit__ does not return True to suppress exceptions
DThe fixture hangs because the test does not consume the fixture properly
Attempts:
2 left
💡 Hint
Think about when the with block ends relative to the yield.
locator
advanced
2:00remaining
Best locator strategy for a pytest fixture using context manager
You want to locate the line in this fixture where the resource is yielded to the test. Which line number is the best locator?
PyTest
1| import pytest
2| 
3| class Resource:
4|     def __enter__(self):
5|         print('Enter')
6|         return self
7|     def __exit__(self, exc_type, exc_val, exc_tb):
8|         print('Exit')
9| 
10| @pytest.fixture
11| def resource():
12|     with Resource() as r:
13|         yield r
14|         print('Cleanup')
ALine 13: yield r
BLine 14: print('Cleanup')
CLine 11: def resource():
DLine 12: with Resource() as r:
Attempts:
2 left
💡 Hint
The yield statement is where the fixture hands control to the test.
framework
expert
2:00remaining
How does pytest handle teardown in context manager fixtures?
In pytest, when a fixture uses a context manager with yield, when exactly does pytest execute the code after the yield?
APytest runs the code after yield only if the test fails
BBefore the test function starts, pytest runs the code after yield to prepare the environment
CPytest never runs the code after yield in context manager fixtures
DImmediately after the test function finishes, pytest resumes the fixture and runs the code after yield for teardown
Attempts:
2 left
💡 Hint
Think about how yield pauses and resumes execution.

Practice

(1/5)
1. What is the main purpose of using a context manager fixture in pytest?
easy
A. To speed up test execution by skipping setup
B. To automatically handle setup and cleanup around a test
C. To replace assertions with print statements
D. To run tests in parallel automatically

Solution

  1. Step 1: Understand context manager role

    Context managers in pytest use yield to run setup code before the test and cleanup code after the test finishes.
  2. Step 2: Identify purpose in testing

    This automatic setup and cleanup makes tests safer and cleaner by managing resources like files or connections.
  3. Final Answer:

    To automatically handle setup and cleanup around a test -> Option B
  4. Quick Check:

    Context manager fixture = automatic setup and cleanup [OK]
Hint: Context managers wrap setup and cleanup automatically [OK]
Common Mistakes:
  • Thinking context managers speed up tests by skipping setup
  • Confusing context managers with parallel test execution
  • Using print statements instead of assertions
2. Which of the following is the correct way to define a context manager fixture in pytest?
easy
A. @pytest.fixture def resource(): setup() yield cleanup()
B. @pytest.fixture def resource(): yield setup() cleanup()
C. @pytest.fixture def resource(): setup() cleanup() yield
D. @pytest.fixture def resource(): cleanup() yield setup()

Solution

  1. Step 1: Recall context manager fixture syntax

    In pytest, the code before yield runs as setup, and the code after yield runs as cleanup.
  2. Step 2: Check each option

    @pytest.fixture def resource(): setup() yield cleanup() correctly places setup() before yield and cleanup() after. Others have wrong order.
  3. Final Answer:

    @pytest.fixture def resource(): setup() yield cleanup() -> Option A
  4. Quick Check:

    Setup before yield, cleanup after yield [OK]
Hint: Setup code goes before yield, cleanup after yield [OK]
Common Mistakes:
  • Placing cleanup before yield
  • Calling setup after yield
  • Putting yield at the end after cleanup
3. Given this fixture and test, what will be printed when running pytest?
@pytest.fixture
def file_resource():
    print('Setup file')
    yield
    print('Cleanup file')

def test_example(file_resource):
    print('Running test')
medium
A. Running test\nSetup file\nCleanup file
B. Cleanup file\nSetup file\nRunning test
C. Setup file\nCleanup file\nRunning test
D. Setup file\nRunning test\nCleanup file

Solution

  1. Step 1: Understand fixture execution order

    Before the test runs, the fixture prints 'Setup file'. Then the test prints 'Running test'. After the test finishes, the fixture prints 'Cleanup file'.
  2. Step 2: Match output sequence

    The output order is: 'Setup file', 'Running test', 'Cleanup file'.
  3. Final Answer:

    Setup file\nRunning test\nCleanup file -> Option D
  4. Quick Check:

    Setup -> Test -> Cleanup order [OK]
Hint: Fixture setup prints before test, cleanup prints after [OK]
Common Mistakes:
  • Assuming cleanup runs before test
  • Thinking test runs before setup
  • Mixing order of prints
4. What is wrong with this context manager fixture?
@pytest.fixture
def db_connection():
    conn = connect_db()
    yield conn
    conn.close()
medium
A. Nothing is wrong; it is correct
B. The fixture should not yield a value
C. The cleanup code after yield will never run
D. The connection should be closed before yield

Solution

  1. Step 1: Analyze fixture structure

    The fixture creates a connection, yields it for the test, then closes it after the test finishes.
  2. Step 2: Confirm cleanup runs after yield

    Code after yield runs as cleanup, so conn.close() will run properly after the test.
  3. Final Answer:

    Nothing is wrong; it is correct -> Option A
  4. Quick Check:

    Yield passes resource, cleanup runs after yield [OK]
Hint: Cleanup code after yield always runs after test [OK]
Common Mistakes:
  • Thinking cleanup code never runs
  • Closing connection before yield
  • Not yielding the resource
5. You want to write a context manager fixture that creates a temporary file, yields its path, and deletes the file after the test. Which code correctly implements this?
hard
A. @pytest.fixture def temp_file(): path = '/tmp/testfile.txt' os.remove(path) yield path
B. @pytest.fixture def temp_file(): path = '/tmp/testfile.txt' yield path open(path, 'w').close() os.remove(path)
C. @pytest.fixture def temp_file(): path = '/tmp/testfile.txt' open(path, 'w').close() yield path os.remove(path)
D. @pytest.fixture def temp_file(): path = '/tmp/testfile.txt' os.remove(path) yield open(path, 'w').close()

Solution

  1. Step 1: Setup temporary file before yield

    The file must be created before yielding its path so the test can use it.
  2. Step 2: Cleanup file after yield

    After the test, the file should be deleted to clean up resources.
  3. Final Answer:

    @pytest.fixture def temp_file(): path = '/tmp/testfile.txt' open(path, 'w').close() yield path os.remove(path) -> Option C
  4. Quick Check:

    Create file before yield, delete after yield [OK]
Hint: Create resource before yield, clean up after yield [OK]
Common Mistakes:
  • Deleting file before test runs
  • Creating file after yield
  • Not yielding the file path