Bird
0
0

You want to create a pytest fixture that connects to a database before a test and disconnects after. Which fixture correctly uses yield for this?

hard🚀 Application Q8 of 15
PyTest - Fixtures
You want to create a pytest fixture that connects to a database before a test and disconnects after. Which fixture correctly uses yield for this?
A@pytest.fixture def db_conn(): conn = connect_db() yield conn conn.close()
B@pytest.fixture def db_conn(): yield connect_db() disconnect_db()
C@pytest.fixture def db_conn(): conn = connect_db() conn.close() yield conn
D@pytest.fixture def db_conn(): yield connect_db() disconnect_db()
Step-by-Step Solution
Solution:
  1. Step 1: Setup connection

    Connect to DB before yield.
  2. Step 2: Yield connection

    Yield connection object for test use.
  3. Step 3: Teardown connection

    Close connection after test completes.
  4. Step 4: Analyze options

    @pytest.fixture def db_conn(): conn = connect_db() yield conn conn.close() correctly implements this pattern.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Setup -> yield resource -> teardown [OK]
Quick Trick: Setup -> yield resource -> teardown [OK]
Common Mistakes:
MISTAKES
  • Closing connection before yield
  • Calling disconnect without connection object
  • Yielding before setup

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes