Bird
Raised Fist0
PyTesttesting~20 mins

Shared expensive resource patterns 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
🎖️
Shared Resource Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of pytest fixture with module scope
What will be the output when running this pytest code with two test functions using a module-scoped fixture?
PyTest
import pytest

@pytest.fixture(scope="module")
def resource():
    print("Setup resource")
    yield "data"
    print("Teardown resource")

def test_one(resource):
    print(f"Test one got {resource}")
    assert resource == "data"

def test_two(resource):
    print(f"Test two got {resource}")
    assert resource == "data"
ASetup resource\nTeardown resource\nTest one got data\nTest two got data
BTest one got data\nTest two got data
CSetup resource\nTest one got data\nTest two got data\nTeardown resource
DSetup resource\nTest one got data\nTeardown resource\nSetup resource\nTest two got data\nTeardown resource
Attempts:
2 left
💡 Hint
Module scope means the fixture runs once per module, not per test.
assertion
intermediate
2:00remaining
Correct assertion for shared resource usage count
Given a shared resource fixture that counts how many times it was used, which assertion correctly verifies it was used exactly twice after two tests?
PyTest
import pytest

usage_count = 0

@pytest.fixture(scope="module")
def shared_resource():
    global usage_count
    usage_count += 1
    yield


def test_a(shared_resource):
    pass

def test_b(shared_resource):
    pass

# After tests run, which assertion is correct?
Aassert usage_count == 1
Bassert usage_count == 2
Cassert usage_count >= 2
Dassert usage_count == 0
Attempts:
2 left
💡 Hint
Remember the fixture scope affects how many times setup code runs.
🔧 Debug
advanced
2:00remaining
Identify the problem with fixture teardown order
This pytest code uses two fixtures: one expensive resource and one dependent on it. The teardown prints are not in expected order. What causes this?
PyTest
import pytest

@pytest.fixture(scope="module")
def expensive_resource():
    print("Setup expensive")
    yield
    print("Teardown expensive")

@pytest.fixture(scope="module")
def dependent_resource(expensive_resource):
    print("Setup dependent")
    yield
    print("Teardown dependent")

def test_example(dependent_resource):
    assert True
ATeardown order depends on test function order
BTeardown order is correct: expensive_resource teardown runs before dependent_resource teardown
CFixtures with same scope teardown in random order
DTeardown order is reversed: dependent_resource teardown runs before expensive_resource teardown
Attempts:
2 left
💡 Hint
Think about fixture dependency and teardown sequence.
framework
advanced
2:00remaining
Best way to share a database connection across tests
You want to share a single expensive database connection across multiple test files in pytest. Which fixture scope and method is best?
AUse a fixture with scope='function' that opens and closes connection per test
BUse a fixture with scope='session' that opens connection once and yields it
CUse a fixture with scope='module' but open connection in each test manually
DUse a fixture with scope='class' that opens connection once per test class
Attempts:
2 left
💡 Hint
Think about how often you want the expensive setup to run.
🧠 Conceptual
expert
2:00remaining
Why use autouse fixtures for shared expensive resources?
What is the main advantage of using an autouse fixture with an expensive resource in pytest?
AIt automatically provides the resource to all tests without needing explicit parameters
BIt runs the fixture setup multiple times per test to ensure freshness
CIt disables teardown to keep the resource alive after tests
DIt forces tests to fail if they do not use the resource
Attempts:
2 left
💡 Hint
Think about convenience and test code simplicity.

Practice

(1/5)
1. What is the main benefit of using a pytest fixture with a scope='module' when dealing with expensive resources?
easy
A. The fixture runs only once per test session, regardless of module.
B. The fixture setup runs once per module, reducing repeated expensive setup.
C. The fixture runs before every test function, ensuring fresh resources.
D. The fixture runs after each test to clean up resources immediately.

Solution

  1. Step 1: Understand fixture scopes in pytest

    Fixtures with scope='module' run once per module, not per test function.
  2. Step 2: Relate scope to expensive resource usage

    Running setup once per module saves time by avoiding repeated expensive setups for each test.
  3. Final Answer:

    The fixture setup runs once per module, reducing repeated expensive setup. -> Option B
  4. Quick Check:

    Module scope = setup once per module [OK]
Hint: Module scope runs setup once per module, saving time [OK]
Common Mistakes:
  • Confusing module scope with function scope
  • Thinking setup runs before every test
  • Assuming cleanup runs immediately after each test
2. Which of the following is the correct syntax to define a pytest fixture that sets up a database connection once per test session?
easy
A. @pytest.fixture(scope='session')\ndef db_conn():\n pass
B. @pytest.fixture(scope='class')\ndef db_conn():\n pass
C. @pytest.fixture(scope='module')\ndef db_conn():\n pass
D. @pytest.fixture(scope='function')\ndef db_conn():\n pass

Solution

  1. Step 1: Identify scope for once per test session

    The session scope runs the fixture setup once for the entire test session.
  2. Step 2: Match syntax with correct scope

    @pytest.fixture(scope='session')\ndef db_conn():\n pass uses @pytest.fixture(scope='session'), which is correct for this purpose.
  3. Final Answer:

    @pytest.fixture(scope='session')\ndef db_conn():\n pass -> Option A
  4. Quick Check:

    Session scope = setup once per session [OK]
Hint: Session scope means setup runs once per entire test run [OK]
Common Mistakes:
  • Using function scope for expensive shared resources
  • Confusing module and session scopes
  • Forgetting to specify scope in fixture decorator
3. Given the following pytest fixture and test code, what will be the output when running the tests?
@pytest.fixture(scope='module')
def resource():
    print('Setup resource')
    yield
    print('Cleanup resource')

def test_one(resource):
    print('Test one running')

def test_two(resource):
    print('Test two running')
medium
A. Setup resource\nTest one running\nTest two running\nCleanup resource
B. Setup resource\nTest one running\nCleanup resource\nSetup resource\nTest two running\nCleanup resource
C. Test one running\nTest two running
D. Setup resource\nCleanup resource\nTest one running\nTest two running

Solution

  1. Step 1: Understand module scope fixture behavior

    With scope='module', setup runs once before any tests in the module, and cleanup runs after all tests finish.
  2. Step 2: Trace the print statements during test execution

    First, 'Setup resource' prints. Then 'Test one running' and 'Test two running' print during tests. Finally, 'Cleanup resource' prints after all tests.
  3. Final Answer:

    Setup resource\nTest one running\nTest two running\nCleanup resource -> Option A
  4. Quick Check:

    Module scope = setup once before all tests, cleanup after all [OK]
Hint: Module scope runs setup once before all tests, cleanup after all [OK]
Common Mistakes:
  • Expecting cleanup after each test
  • Thinking setup runs before each test
  • Ignoring yield behavior in fixture
4. Identify the error in this pytest fixture code that aims to share a resource across tests in a class:
@pytest.fixture(scope='class')
def setup_resource():
    resource = open('file.txt')
    yield resource
    resource.close()

def test_example(setup_resource):
    assert setup_resource.readable()
medium
A. The fixture should use scope='module' instead of 'class'.
B. The fixture function name does not match the test parameter name.
C. The fixture does not handle exceptions during resource setup.
D. The fixture is missing the @pytest.mark.usefixtures decorator.

Solution

  1. Step 1: Review fixture resource setup and cleanup

    The fixture opens a file and yields it, then closes it after tests.
  2. Step 2: Check for error handling in setup

    If opening the file fails, no exception handling is present, which can cause test failures or resource leaks.
  3. Final Answer:

    The fixture does not handle exceptions during resource setup. -> Option C
  4. Quick Check:

    Missing exception handling in fixture setup = problem [OK]
Hint: Always handle exceptions in fixture setup to avoid leaks [OK]
Common Mistakes:
  • Confusing fixture scope requirements
  • Thinking @pytest.mark.usefixtures is mandatory
  • Assuming fixture name mismatch causes error
5. You want to share a database connection across multiple test classes but ensure it resets after all tests finish. Which pytest fixture pattern correctly achieves this?
hard
A. @pytest.fixture(scope='function')\ndef db_conn():\n conn = connect_db()\n yield conn\n conn.reset()\n conn.close()
B. @pytest.fixture(scope='class')\ndef db_conn():\n conn = connect_db()\n yield conn\n conn.close()
C. @pytest.fixture(scope='module')\ndef db_conn():\n conn = connect_db()\n yield conn\n conn.reset()
D. @pytest.fixture(scope='session')\ndef db_conn():\n conn = connect_db()\n yield conn\n conn.reset()\n conn.close()

Solution

  1. Step 1: Determine scope for sharing across multiple test classes

    Sharing across classes requires at least session scope to cover all tests.
  2. Step 2: Ensure resource resets after all tests finish

    Using yield allows cleanup code after tests; calling conn.reset() before conn.close() resets the connection properly.
  3. Final Answer:

    @pytest.fixture(scope='session')\ndef db_conn():\n conn = connect_db()\n yield conn\n conn.reset()\n conn.close() -> Option D
  4. Quick Check:

    Session scope + yield cleanup with reset = correct pattern [OK]
Hint: Use session scope and yield cleanup to reset shared resource [OK]
Common Mistakes:
  • Using too narrow scope like function or class
  • Forgetting to reset resource before closing
  • Not using yield to separate setup and cleanup