0
0
PyTesttesting~8 mins

Combining multiple parametrize decorators in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Combining multiple parametrize decorators
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   ├── test_login.py
│   └── test_calculations.py
├── conftest.py
├── pytest.ini
└── utils/
    └── helpers.py
  
Test Framework Layers
  • Tests Layer: Contains test files using @pytest.mark.parametrize decorators to run tests with multiple data sets. Multiple parametrize decorators can be stacked to combine parameters.
  • Fixtures Layer: conftest.py holds fixtures for setup and teardown, shared resources, and test data preparation.
  • Utilities Layer: Helper functions and reusable code in utils/helpers.py to keep tests clean and DRY.
  • Configuration Layer: pytest.ini or tox.ini for pytest settings like markers, test paths, and command-line options.
Configuration Patterns

Use pytest.ini to define markers and default options. Use conftest.py to manage fixtures that provide test data or environment setup.

# pytest.ini
[pytest]
markers =
    slow: marks tests as slow
    parametrize: marks parameterized tests

# conftest.py
import pytest

@pytest.fixture
def sample_data():
    return {"key": "value"}
  

For combining multiple parametrize decorators, simply stack them above the test function. Pytest runs the test for every combination of parameters.

Test Reporting and CI/CD Integration
  • Use pytest built-in options like --junitxml=report.xml to generate XML reports for CI tools.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests automatically on code changes.
  • Use plugins like pytest-html for readable HTML reports.
  • Reports show each parameter combination as a separate test case, making it easy to identify failing inputs.
Best Practices
  • Stack multiple @pytest.mark.parametrize decorators to test all combinations of parameters clearly and efficiently.
  • Keep parameter names descriptive to understand test inputs easily.
  • Use fixtures to provide complex or reusable test data instead of hardcoding in parametrize.
  • Limit the number of combined parameters to avoid explosion of test cases and long test runs.
  • Use meaningful test IDs with ids argument in parametrize for better report readability.
Self Check

Where in this framework structure would you add a new test file that uses multiple @pytest.mark.parametrize decorators to test a calculator's add and multiply functions?

Key Result
Stack multiple @pytest.mark.parametrize decorators in test files under tests/ to run all parameter combinations efficiently.