Framework Mode - Fixture scope (function, class, module, session)
Folder Structure
project-root/ ├── tests/ │ ├── test_example.py │ ├── test_another.py │ ├── conftest.py │ └── submodule/ │ └── test_submodule.py └── pytest.ini
project-root/ ├── tests/ │ ├── test_example.py │ ├── test_another.py │ ├── conftest.py │ └── submodule/ │ └── test_submodule.py └── pytest.ini
conftest.py or test modules, fixtures provide setup and teardown code with different scopes: function, class, module, and session.tests/ folder use fixtures to run tests. Each test function or method can request fixtures.pytest.ini or pyproject.toml files configure pytest options and plugins.Use conftest.py files to define fixtures with appropriate scopes:
function: Runs before each test function. Use for isolated setup.class: Runs once per test class. Use when tests share setup in a class.module: Runs once per test module (file). Use for expensive setup shared by all tests in a file.session: Runs once per test session. Use for global setup like database connections.Example fixture with scope:
import pytest
@pytest.fixture(scope="module")
def setup_database():
print("Setup DB")
yield
print("Teardown DB")
Use pytest.ini to configure test runs, e.g., markers or test paths.
pytest-html or pytest-cov to generate reports.pytest commands and collect reports.function scope for tests that must not share state.session scope for expensive global setup to speed up test runs.conftest.py to share fixtures across multiple test files.Where in this framework structure would you add a new fixture that sets up a web browser once per test class?