0
0
PyTesttesting~8 mins

Test packages in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Test packages
Folder Structure for Pytest Test Packages
project-root/
├── src/
│   └── app_code.py
├── tests/
│   ├── __init__.py
│   ├── unit/
│   │   ├── __init__.py
│   │   ├── test_module1.py
│   │   └── test_module2.py
│   ├── integration/
│   │   ├── __init__.py
│   │   └── test_integration_feature.py
│   ├── e2e/
│   │   ├── __init__.py
│   │   └── test_end_to_end.py
│   └── conftest.py
├── pytest.ini
└── requirements.txt
  
Test Framework Layers in Pytest Packages
  • Test Packages: Organized folders like unit, integration, and e2e inside tests/ to group related tests.
  • Test Modules: Python files starting with test_ containing test functions or classes.
  • Fixtures: Defined in conftest.py or test modules to set up test data or environment.
  • Application Code: Source code under src/ imported by tests.
  • Configuration: pytest.ini for pytest settings and markers.
Configuration Patterns for Pytest Test Packages
  • pytest.ini: Central place to define test markers, addopts, and test paths.
  • conftest.py: Share fixtures and hooks across test packages.
  • Environment Variables: Use os.environ or pytest-env plugin to manage credentials and environment-specific settings.
  • Command Line Options: Add custom options in conftest.py to select environments or browsers.
Test Reporting and CI/CD Integration
  • pytest-html Plugin: Generate HTML reports for test runs.
  • JUnit XML Reports: Use --junitxml=report.xml to create XML reports for CI tools.
  • CI/CD Pipelines: Integrate pytest commands in pipelines (GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Test Logs: Capture logs with pytest logging plugin for debugging failures.
Best Practices for Pytest Test Packages
  • Use __init__.py: Include __init__.py files in test folders to make them packages and enable relative imports.
  • Group Tests Logically: Separate unit, integration, and end-to-end tests into different packages for clarity and selective runs.
  • Reuse Fixtures: Define common fixtures in conftest.py to avoid duplication.
  • Keep Tests Independent: Each test should run alone without relying on others.
  • Clear Naming: Name test files and functions clearly starting with test_ for pytest discovery.
Self Check Question

Where would you add a new test module for API integration tests in this pytest test package structure?

Key Result
Organize tests into packages with __init__.py, use conftest.py for shared fixtures, and configure pytest.ini for smooth test management.