Bird
0
0

You want to share a database connection setup across multiple test files using conftest.py. Which approach best follows pytest best practices?

hard📝 framework Q15 of 15
PyTest - Test Organization
You want to share a database connection setup across multiple test files using conftest.py. Which approach best follows pytest best practices?
ADefine a fixture in <code>conftest.py</code> that creates and yields the connection, then closes it after tests
BWrite the connection setup code inside each test function separately
CCreate a global variable in <code>conftest.py</code> holding the connection without a fixture
DUse a class with static methods in <code>conftest.py</code> to manage the connection
Step-by-Step Solution
Solution:
  1. Step 1: Understand fixture scope and cleanup

    Using a fixture with yield allows setup before tests and cleanup after, ideal for resources like DB connections.
  2. Step 2: Evaluate other options

    Write the connection setup code inside each test function separately repeats code, violating DRY. Create a global variable in conftest.py holding the connection without a fixture lacks cleanup and is not recommended. Use a class with static methods in conftest.py to manage the connection is more complex and less idiomatic.
  3. Final Answer:

    Define a fixture in conftest.py that creates and yields the connection, then closes it after tests -> Option A
  4. Quick Check:

    Fixture with yield for setup/teardown = A [OK]
Quick Trick: Use yield fixture for setup and cleanup in conftest.py [OK]
Common Mistakes:
MISTAKES
  • Duplicating setup in tests
  • Not cleaning up resources
  • Using global variables instead of fixtures

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes