Bird
0
0

You want a pytest fixture to open a database connection before a test and ensure it closes after, regardless of test outcome. Which feature should you use?

hard🚀 Application Q8 of 15
PyTest - Fixtures
You want a pytest fixture to open a database connection before a test and ensure it closes after, regardless of test outcome. Which feature should you use?
ACall the close method inside the fixture before returning
BUse a generator fixture with <code>yield</code> to separate setup and teardown
CUse <code>scope='session'</code> to manage connection lifetime
DManually close the connection inside each test function
Step-by-Step Solution
Solution:
  1. Step 1: Understand fixture teardown

    To ensure cleanup runs after tests, even on failure, use yield in fixtures.
  2. Step 2: How yield works

    Code before yield runs before the test (setup), code after runs after (teardown).
  3. Step 3: Evaluate options

    Use a generator fixture with yield to separate setup and teardown correctly uses a generator fixture with yield for setup and teardown.
  4. Final Answer:

    Use a generator fixture with yield to separate setup and teardown -> Option B
  5. Quick Check:

    Yield separates setup and teardown in fixtures [OK]
Quick Trick: Use yield in fixture for guaranteed teardown [OK]
Common Mistakes:
MISTAKES
  • Closing resources before yielding
  • Not using yield for teardown
  • Relying on test code to cleanup

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes