0
0
PyTesttesting~8 mins

Parametrized fixtures in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Parametrized fixtures
Folder Structure
project_root/
├── tests/
│   ├── test_example.py       # Test files using fixtures
│   └── conftest.py           # Fixtures including parametrized fixtures
├── utils/
│   └── helpers.py            # Helper functions
├── config/
│   └── config.yaml           # Environment and test data configs
└── pytest.ini                # Pytest configuration file
  
Test Framework Layers
  • Fixtures Layer:
    Located in conftest.py. Contains parametrized fixtures that provide test data or setup for tests. These fixtures run tests multiple times with different inputs.
  • Tests Layer:
    Test files in tests/ use the parametrized fixtures by declaring them as function arguments. Each test runs once per fixture parameter.
  • Utilities Layer:
    Helper functions and reusable code to support fixtures and tests.
  • Configuration Layer:
    Files like pytest.ini and config.yaml hold environment settings and test parameters.
Configuration Patterns

Use pytest.ini to set global pytest options like markers and test paths.

Use config.yaml or similar files to store environment-specific data (URLs, credentials).

Parametrized fixtures can read from config files or be hardcoded in conftest.py to supply multiple test inputs.

Example snippet in conftest.py:

import pytest

@pytest.fixture(params=["data1", "data2", "data3"])
def sample_data(request):
    return request.param
  
Test Reporting and CI/CD Integration
  • Use pytest built-in reporting with --junitxml=report.xml to generate XML reports for CI tools.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Parametrized fixtures help by running multiple test cases in one test function, improving coverage and reporting clarity.
  • Use plugins like pytest-html for readable HTML reports.
Best Practices for Parametrized Fixtures
  • Keep fixtures simple and focused: Each fixture should provide one type of data or setup.
  • Use params argument: To easily supply multiple values for tests without repeating code.
  • Combine fixtures carefully: Avoid complex dependencies that make tests hard to understand.
  • Use descriptive parameter names: So test reports clearly show which input caused a failure.
  • Read test data from external files: For large or changing datasets, keep test data outside code.
Self Check

Where in this folder structure would you add a new parametrized fixture that provides user login data for tests?

Key Result
Parametrized fixtures in pytest provide multiple test inputs from a single fixture, improving test coverage and reusability.