Bird
0
0

Consider this pytest fixture setup:

hard🚀 Application Q9 of 15
PyTest - Fixtures
Consider this pytest fixture setup:
import pytest

@pytest.fixture(scope='module')
def db_connection():
    print('Connect DB')
    yield
    print('Disconnect DB')

@pytest.fixture(scope='function')
def user_data():
    print('Setup user data')

How many times will Connect DB and Setup user data print if there are 3 test functions in the module using both fixtures?
A'Connect DB' prints 3 times; 'Setup user data' prints 3 times.
B'Connect DB' prints 1 time; 'Setup user data' prints 3 times.
C'Connect DB' prints 3 times; 'Setup user data' prints 1 time.
D'Connect DB' prints 1 time; 'Setup user data' prints 1 time.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze db_connection fixture with module scope

    Module scope means 'Connect DB' prints once before all tests in the module.
  2. Step 2: Analyze user_data fixture with function scope

    Function scope means 'Setup user data' prints once per test function, so 3 times for 3 tests.
  3. Final Answer:

    'Connect DB' prints 1 time; 'Setup user data' prints 3 times. -> Option B
  4. Quick Check:

    Module scope runs once; function scope runs per test [OK]
Quick Trick: Module scope runs once; function scope runs per test [OK]
Common Mistakes:
MISTAKES
  • Assuming module scope runs per test
  • Confusing yield behavior with scope
  • Counting prints incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes