Bird
0
0

You want to share a fixture that provides a database connection across multiple test files. You place this fixture in conftest.py:

hard🚀 Application Q15 of 15
PyTest - Fixtures
You want to share a fixture that provides a database connection across multiple test files. You place this fixture in conftest.py:
import pytest

@pytest.fixture(scope="session")
def db_connection():
    conn = create_connection()
    yield conn
    conn.close()
What is the best reason to use scope="session" here?
ATo run tests in parallel using the same connection
BTo create a new connection for every test function
CTo close the connection before each test
DTo create the connection once per test session and reuse it in all tests
Step-by-Step Solution
Solution:
  1. Step 1: Understand fixture scopes in pytest

    Scope "session" means the fixture is created once for the entire test run and shared across all tests.
  2. Step 2: Apply to database connection use case

    Creating the connection once saves time and resources, and closing it after all tests is efficient.
  3. Final Answer:

    To create the connection once per test session and reuse it in all tests -> Option D
  4. Quick Check:

    Session scope = one setup per test run [OK]
Quick Trick: Use session scope for expensive setup reused by all tests [OK]
Common Mistakes:
MISTAKES
  • Thinking session scope creates new instance per test
  • Assuming connection closes before each test
  • Confusing scope with parallel test execution

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes