0
0
PyTesttesting~8 mins

Fixture scope (function, class, module, session) in PyTest - Framework Patterns

Choose your learning style9 modes available
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
  
Test Framework Layers
  • Fixtures Layer: Defined in conftest.py or test modules, fixtures provide setup and teardown code with different scopes: function, class, module, and session.
  • Test Layer: Test files inside tests/ folder use fixtures to run tests. Each test function or method can request fixtures.
  • Configuration Layer: pytest.ini or pyproject.toml files configure pytest options and plugins.
  • Utilities Layer: Helper functions or classes can be placed in separate modules imported by fixtures or tests.
Configuration Patterns

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.

Test Reporting and CI/CD Integration
  • Use pytest plugins like pytest-html or pytest-cov to generate reports.
  • Configure CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run pytest commands and collect reports.
  • Fixture scopes help optimize test run time by reducing repeated setup, improving CI efficiency.
Best Practices
  • Use the narrowest fixture scope needed to keep tests isolated and fast.
  • Use function scope for tests that must not share state.
  • Use session scope for expensive global setup to speed up test runs.
  • Keep fixtures simple and focused on setup/teardown only.
  • Use conftest.py to share fixtures across multiple test files.
Self Check

Where in this framework structure would you add a new fixture that sets up a web browser once per test class?

Key Result
Use pytest fixtures with appropriate scopes (function, class, module, session) to organize setup and teardown efficiently.