Bird
0
0

You want a pytest fixture to initialize a database connection once before all tests in multiple modules run, and close it after all tests finish. Which scope should you use and why?

hard📝 framework Q15 of 15
PyTest - Fixtures
You want a pytest fixture to initialize a database connection once before all tests in multiple modules run, and close it after all tests finish. Which scope should you use and why?
AUse <code>session</code> scope to share across all tests in the run.
BUse <code>function</code> scope to isolate each test.
CUse <code>module</code> scope to share per file.
DUse <code>class</code> scope to share per test class.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    The database connection should be initialized once before all tests in multiple modules and closed after all tests.
  2. Step 2: Match scope to requirement

    Session scope runs once per entire test session, perfect for setup/teardown across all modules.
  3. Final Answer:

    Use session scope to share across all tests in the run. -> Option A
  4. Quick Check:

    Session scope = once per test run [OK]
Quick Trick: Session scope runs once for all tests in the run [OK]
Common Mistakes:
MISTAKES
  • Choosing function or class scope which run too often
  • Using module scope which limits to one file
  • Not matching scope to resource lifetime

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes