← Back to libraryQuestion 203 of 468
🐍PythonIntermediate

pytest Fixtures

📌 Definition:

Fixtures are pytest's dependency-injection mechanism for setup/teardown. A function decorated with @pytest.fixture provides a resource (driver, DB connection, test data) that tests request by naming it as a parameter.

📖 Detailed Explanation:

@pytest.fixture def driver(): d = webdriver.Chrome(); yield d; d.quit() sets up a browser, yields it to the test, and tears it down after. A test just adds driver as a parameter: def test_x(driver): .... Fixtures have SCOPES — function (default), class, module, session — controlling how often they run/reuse (a session-scoped DB connection is created once). Fixtures can depend on other fixtures, and conftest.py shares them across files without imports. yield-style fixtures put teardown after the yield. This replaces setUp/tearDown with composable, reusable, scoped resources.

🔑 Key Points:
  • @pytest.fixture provides setup/teardown via dependency injection
  • Tests request fixtures by naming them as parameters
  • Scopes: function/class/module/session control reuse
  • conftest.py shares fixtures across files; yield separates setup/teardown
🌍 Real-World Example:

A session-scoped fixture opens one browser for the whole run: @pytest.fixture(scope='session') — reused across tests to save the cost of launching Chrome repeatedly.

🎯 Scenario-Based Interview Question:

Each test creates and quits its own browser, making the suite slow. How do fixtures and scope help?