0
0
PyTesttesting~8 mins

Conditional parametrize in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Conditional parametrize
Folder Structure
tests/
├── test_example.py          # Test files with parametrize decorators
├── conftest.py              # Fixtures and hooks
utilities/
├── helpers.py               # Helper functions for conditions
config/
├── config.yaml              # Environment and test data config
reports/
├── latest_report.html       # Generated test reports
Test Framework Layers
  • Test Layer: Contains test files using @pytest.mark.parametrize with conditional logic to select parameters dynamically.
  • Fixture Layer: conftest.py holds fixtures that provide test data or environment info to decide which parameters to run.
  • Utility Layer: Helper functions to determine conditions, e.g., checking environment variables or feature flags.
  • Configuration Layer: Central config files (YAML/JSON) to define environments, browsers, or flags that influence parameter selection.
Configuration Patterns

Use a config file (e.g., config/config.yaml) to define environment variables or flags.

# config/config.yaml
run_extended_tests: true
browser: chrome

Load config in conftest.py and expose as fixture.

import yaml
import pytest

def pytest_addoption(parser):
    parser.addoption("--env", action="store", default="dev")

@pytest.fixture(scope="session")
def config(request):
    with open("config/config.yaml") as f:
        cfg = yaml.safe_load(f)
    cfg['env'] = request.config.getoption("--env")
    return cfg

Use this fixture in tests to conditionally parametrize.

Test Reporting and CI/CD Integration
  • Use pytest-html or Allure plugins to generate readable reports showing which parameter sets ran.
  • CI pipelines (GitHub Actions, Jenkins) run tests with different config flags to cover conditional parameters.
  • Reports help verify that conditional branches in parametrize are executed as expected.
Best Practices
  1. Keep conditions simple: Use clear boolean flags or environment variables to decide parameters.
  2. Centralize config: Manage all conditional flags in one config file or fixture for easy updates.
  3. Use fixtures for data: Pass config or environment info via fixtures to keep tests clean.
  4. Document parameter choices: Comment why certain parameters run only under specific conditions.
  5. Validate coverage: Ensure CI runs all conditional branches to avoid missing test cases.
Self Check

Where in this folder structure would you add a new helper function that decides which parameters to use based on the current environment?

Key Result
Use fixtures and config files to conditionally parametrize tests in pytest for flexible, environment-aware testing.