0
0
PyTesttesting~8 mins

Parametrize with IDs in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Parametrize with IDs
Folder Structure
tests/
├── test_math_operations.py
├── test_user_login.py
└── conftest.py

utils/
├── calculator.py
└── helpers.py

pytest.ini
requirements.txt

This is a simple pytest project structure. All test files are inside the tests/ folder. Utility code is in utils/. The conftest.py file holds shared fixtures and setup.

Test Framework Layers
  • Tests: Test functions using @pytest.mark.parametrize with ids to name test cases clearly.
  • Fixtures: Shared setup or data in conftest.py for reuse.
  • Utilities: Helper functions or classes in utils/ to keep tests clean.
  • Configuration: pytest.ini for test options and markers.
Configuration Patterns
  • pytest.ini to define markers and default options.
  • Use conftest.py to define fixtures that can provide test data or environment setup.
  • Parametrize tests with ids to give readable names to each test case, improving test reports.
  • Example of parametrization with IDs in test function:
    import pytest
    
    @pytest.mark.parametrize(
        "input,expected",
        [
            (1, 2),
            (3, 4),
            (5, 6),
        ],
        ids=["one_to_two", "three_to_four", "five_to_six"]
    )
    def test_increment(input, expected):
        assert input + 1 == expected
    
Test Reporting and CI/CD Integration
  • pytest automatically shows test IDs in the test report when using ids in parametrization.
  • Use plugins like pytest-html to generate readable HTML reports showing test case names.
  • Integrate pytest runs in CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests automatically on code changes.
  • Readable test IDs help quickly identify which test case failed in reports and logs.
Best Practices
  • Use descriptive IDs: Give each parameter set a clear, human-readable name to understand test cases easily.
  • Keep parameter sets small: Avoid too many parameters in one test to keep tests simple and focused.
  • Reuse fixtures: Use conftest.py fixtures to provide common data or setup for parametrized tests.
  • Combine with markers: Use pytest markers to group or skip parametrized tests as needed.
  • Maintain readability: Use ids to improve test output clarity, especially when parameters are complex objects.
Self Check

Where in this folder structure would you add a new parametrized test for a login feature that uses IDs to name test cases?

Key Result
Use pytest's @pytest.mark.parametrize with descriptive IDs to organize and clearly name test cases for better readability and reporting.