Bird
Raised Fist0
PyTesttesting~20 mins

Handling shared resources 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 shared resource
Consider the following pytest code using a fixture that manages a shared resource. What will be the output when running the test?
PyTest
import pytest

shared_list = []

@pytest.fixture(scope="module")
def resource():
    shared_list.append(1)
    yield shared_list
    shared_list.clear()

def test_one(resource):
    resource.append(2)
    assert resource == [1, 2]

def test_two(resource):
    resource.append(3)
    assert resource == [1, 3]
ABoth test_one and test_two fail with AssertionError
BBoth test_one and test_two pass
Ctest_one fails with AssertionError, test_two passes
Dtest_one passes, test_two fails with AssertionError
Attempts:
2 left
💡 Hint
Think about how the shared_list is modified and when it is cleared.
assertion
intermediate
1:30remaining
Correct assertion for shared file content
You have a shared file resource used in multiple tests. Which assertion correctly verifies that the file content includes the string 'success' after writing?
PyTest
def test_write_file(shared_file):
    shared_file.write('operation success')
    shared_file.seek(0)
    content = shared_file.read()
Aassert 'success' in content
Bassert content == 'success'
Cassert content.startswith('success')
Dassert content.endswith('success')
Attempts:
2 left
💡 Hint
The file content may have other text besides 'success'.
🔧 Debug
advanced
2:30remaining
Identify the cause of test interference with shared database connection
Two tests share a database connection fixture with function scope. Test A inserts a row but does not rollback. Test B expects an empty table but fails. What is the most likely cause?
PyTest
import pytest

@pytest.fixture(scope='function')
def db_connection():
    conn = create_connection()
    yield conn
    conn.close()

def test_a(db_connection):
    db_connection.execute('INSERT INTO users VALUES (1, "Alice")')
    # missing rollback

def test_b(db_connection):
    result = db_connection.execute('SELECT * FROM users')
    assert len(result.fetchall()) == 0
ATest A did not rollback, so data persists and affects Test B
BThe fixture scope should be module, not function
CTest B has a wrong assertion expecting empty table
DThe connection is closed too early in Test A
Attempts:
2 left
💡 Hint
Think about transaction handling and test isolation.
framework
advanced
1:30remaining
Best pytest fixture scope for expensive shared resource
You have a resource that takes 10 minutes to set up and can be safely shared across all tests in a module. Which pytest fixture scope is best to use?
Ascope='function' to isolate each test
Bscope='module' to share resource across all tests in the module
Cscope='session' to share resource across all test sessions
Dscope='class' to share resource across tests in a class
Attempts:
2 left
💡 Hint
Choose a scope that balances setup time and test isolation.
🧠 Conceptual
expert
3:00remaining
Handling flaky tests caused by shared resource contention
You notice intermittent test failures caused by multiple tests accessing a shared resource concurrently. What is the best approach to handle this in pytest?
AUse pytest-xdist to run tests in parallel to reduce test time
BMark flaky tests as expected failures to ignore them
CAdd locks or synchronization in fixtures to serialize access to the shared resource
DIncrease the fixture scope to session to share the resource more broadly
Attempts:
2 left
💡 Hint
Think about how to prevent concurrent access issues.

Practice

(1/5)
1. What is the main purpose of using shared resources in pytest tests?
easy
A. To make tests run slower by adding extra steps
B. To reuse setup work and avoid conflicts between tests
C. To write tests without any setup or teardown
D. To skip tests that use external files

Solution

  1. Step 1: Understand shared resources in testing

    Shared resources allow multiple tests to use the same setup, saving time and avoiding repeated work.
  2. Step 2: Recognize the benefit of avoiding conflicts

    Using shared resources carefully prevents tests from interfering with each other, keeping results reliable.
  3. Final Answer:

    To reuse setup work and avoid conflicts between tests -> Option B
  4. Quick Check:

    Shared resources = reuse setup + avoid conflicts [OK]
Hint: Shared resources save setup time and prevent test clashes [OK]
Common Mistakes:
  • Thinking shared resources slow tests down
  • Believing shared resources remove the need for setup
  • Confusing shared resources with skipping tests
2. Which pytest fixture scope is best to share a resource across all tests in a module?
easy
A. "function" scope
B. "class" scope
C. "session" scope
D. "module" scope

Solution

  1. Step 1: Recall pytest fixture scopes

    "function" runs for each test, "class" for each test class, "module" for all tests in a file, "session" for all tests in a run.
  2. Step 2: Identify scope for sharing in a module

    To share a resource across all tests in one module (file), use "module" scope.
  3. Final Answer:

    "module" scope -> Option D
  4. Quick Check:

    Module scope = share resource in one file [OK]
Hint: "module" scope shares resource across one test file [OK]
Common Mistakes:
  • Using "function" scope which creates resource per test
  • Choosing "class" scope which limits sharing to test classes
  • Confusing "session" scope which shares across all tests
3. What will be the output of this pytest fixture usage?
import pytest

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

def test_one(resource):
    assert resource == "data"

def test_two(resource):
    assert resource == "data"
medium
A. Setup resource printed once, then tests pass, then Teardown resource printed once
B. Setup resource and Teardown resource printed before each test
C. Setup resource printed twice, no teardown printed
D. No output printed because print statements are ignored

Solution

  1. Step 1: Understand fixture scope and yield behavior

    With "module" scope, setup runs once before all tests in the module, yield provides the resource, and teardown runs once after all tests.
  2. Step 2: Analyze print outputs during test run

    "Setup resource" prints once before tests, both tests use the resource and pass, then "Teardown resource" prints once after all tests.
  3. Final Answer:

    Setup resource printed once, then tests pass, then Teardown resource printed once -> Option A
  4. Quick Check:

    Module scope fixture setup/teardown run once [OK]
Hint: Module scope fixture setup/teardown run once per module [OK]
Common Mistakes:
  • Expecting setup/teardown to run before and after each test
  • Thinking print statements are suppressed
  • Confusing fixture scope with function scope
4. Identify the error in this pytest fixture that shares a database connection:
@pytest.fixture(scope="module")
def db_connection():
    conn = open_db()
    yield conn
    conn.close()

def test_query(db_connection):
    assert db_connection.execute("SELECT 1") == 1

def test_insert(db_connection):
    db_connection.execute("INSERT INTO table VALUES (1)")
medium
A. The connection might be shared but not reset between tests causing side effects
B. The fixture does not close the connection after tests
C. The fixture scope should be "function" to avoid conflicts
D. The yield statement is missing in the fixture

Solution

  1. Step 1: Review fixture setup and teardown

    The fixture opens a connection, yields it, then closes it after all tests in the module.
  2. Step 2: Consider side effects of shared connection

    Because the connection is shared and not reset between tests, changes in one test (like insert) may affect others, causing flaky tests.
  3. Final Answer:

    The connection might be shared but not reset between tests causing side effects -> Option A
  4. Quick Check:

    Shared resource without reset risks test interference [OK]
Hint: Shared resources need reset or isolation to avoid side effects [OK]
Common Mistakes:
  • Thinking connection is never closed
  • Assuming function scope is always required
  • Missing yield statement in fixture
5. You want to share a temporary folder between tests but ensure it is empty before each test. Which pytest fixture setup is best?
hard
A. Use a "module" scoped fixture that creates the folder once and clears it before each test
B. Use a "session" scoped fixture that creates the folder once and never cleans it
C. Use a "function" scoped fixture that creates and deletes the folder for each test
D. Use a "class" scoped fixture that creates the folder once per test class without cleanup

Solution

  1. Step 1: Understand the need to share and clean resource

    You want to share the folder to save setup time but also ensure it is empty before each test to avoid leftover files.
  2. Step 2: Choose fixture scope and cleanup strategy

    A "function" scoped fixture creates and deletes the folder for each test, ensuring it is empty before each test and avoiding leftover files.
  3. Final Answer:

    Use a "function" scoped fixture that creates and deletes the folder for each test -> Option C
  4. Quick Check:

    Function scope fixture creates clean folder per test [OK]
Hint: Create and delete resource per test for clean state [OK]
Common Mistakes:
  • Using function scope causing slow tests
  • Using session scope without cleanup causing test pollution
  • Using class scope which limits sharing incorrectly