Bird
0
0

You want to create a fixture that sets up a temporary database for Flask tests and ensures it is cleaned up after all tests in the module run. Which fixture scope and structure is best?

hard📝 state output Q15 of 15
Flask - Testing Flask Applications
You want to create a fixture that sets up a temporary database for Flask tests and ensures it is cleaned up after all tests in the module run. Which fixture scope and structure is best?
A@pytest.fixture(scope='function') def temp_db(): db = setup_temp_db() yield db teardown_temp_db(db)
B@pytest.fixture(scope='module') def temp_db(): db = setup_temp_db() yield db teardown_temp_db(db)
C@pytest.fixture(scope='session') def temp_db(): db = setup_temp_db() return db
D@pytest.fixture(scope='module') def temp_db(): db = setup_temp_db() return db teardown_temp_db(db)
Step-by-Step Solution
Solution:
  1. Step 1: Choose fixture scope for module-wide setup

    Scope 'module' runs once per module, ideal for shared DB setup across tests.
  2. Step 2: Use yield to allow teardown after all tests

    Yield pauses fixture to run tests, then runs teardown after all tests complete.
  3. Final Answer:

    @pytest.fixture(scope='module')\ndef temp_db():\n db = setup_temp_db()\n yield db\n teardown_temp_db(db) -> Option B
  4. Quick Check:

    Module scope + yield for setup and cleanup [OK]
Quick Trick: Use scope='module' and yield for setup/cleanup [OK]
Common Mistakes:
MISTAKES
  • Using function scope causes repeated setup
  • Returning without yield skips cleanup
  • Placing cleanup code after return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes