0
0
PyTesttesting~8 mins

Grouping related tests in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Grouping related tests
Folder Structure
tests/
├── unit/
│   ├── test_math_operations.py
│   └── test_string_utils.py
├── integration/
│   ├── test_api_endpoints.py
│   └── test_database.py
├── functional/
│   ├── test_user_login.py
│   └── test_shopping_cart.py
├── conftest.py
└── pytest.ini
Test Framework Layers
  • Tests: Organized by type (unit, integration, functional) inside tests/ folder.
  • Fixtures: Defined in conftest.py for shared setup and teardown.
  • Configuration: pytest.ini for test markers and options.
  • Utilities: Helper functions or modules imported by tests if needed.
Configuration Patterns
  • pytest.ini: Define markers to group tests, e.g., [pytest] with markers = unit: Unit tests, integration: Integration tests, functional: Functional tests.
  • conftest.py: Place fixtures here to share setup across grouped tests.
  • Command line: Run grouped tests by marker, e.g., pytest -m unit to run all unit tests.
  • Environment variables: Use if needed to switch configurations for different test groups.
Test Reporting and CI/CD Integration
  • Use pytest built-in reports with clear grouping by markers.
  • Generate JUnit XML reports for CI tools to parse and display grouped test results.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins) to run specific groups on different triggers.
  • Use plugins like pytest-html for readable HTML reports showing grouped test outcomes.
Best Practices for Grouping Related Tests
  1. Use markers: Mark tests clearly with @pytest.mark.unit, @pytest.mark.integration, etc., for easy selection.
  2. Organize folders: Group tests by type or feature in separate folders for clarity.
  3. Shared fixtures: Use conftest.py to avoid duplication and share setup among grouped tests.
  4. Keep tests independent: Ensure grouped tests do not depend on each other to avoid flaky results.
  5. Run groups selectively: Use command line options to run only needed groups during development or CI.
Self Check

Where in this framework structure would you add a new test file for API integration tests?

Key Result
Organize tests by folders and markers, use shared fixtures, and run groups selectively with pytest.