0
0
PyTesttesting~8 mins

Project structure for tests in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Project structure for tests
Folder Structure
project-root/
├── tests/
│   ├── unit/
│   │   ├── test_example_unit.py
│   ├── integration/
│   │   ├── test_example_integration.py
│   ├── e2e/
│   │   ├── test_example_e2e.py
│   ├── utils/
│   ├── __init__.py
│   └── conftest.py
├── src/
│   ├── __init__.py
│   └── application_code.py
├── pytest.ini
├── requirements.txt
└── README.md
Test Framework Layers
  • Tests Layer: Contains all test files organized by type (unit, integration, end-to-end).
  • Fixtures & Config Layer: conftest.py holds shared setup and fixtures for tests.
  • Source Code Layer: src/ folder contains the application code under test.
  • Configuration Layer: pytest.ini manages pytest settings and markers.
  • Utilities Layer: Helper functions or test utilities can be added inside tests/utils/ if needed.
Configuration Patterns
  • pytest.ini: Configure test markers, addopts, and test paths.
  • conftest.py: Define fixtures for setup like database connections, test data, or environment variables.
  • Environment Handling: Use environment variables or pytest command line options to switch between test environments (dev, staging, prod).
  • Credentials: Store sensitive data securely outside the repo, load via environment variables or secret managers.
  • Browser or External Service Config: Use fixtures with parameters to select browsers or services dynamically.
Test Reporting and CI/CD Integration
  • Use pytest plugins like pytest-html or pytest-cov for HTML reports and coverage reports.
  • Integrate tests into CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests automatically on code push.
  • Configure test reports to be saved as artifacts or sent via email/slack notifications.
  • Use pytest-xdist for parallel test execution to speed up test runs.
Best Practices
  • Organize tests by type and feature for clarity and easy navigation.
  • Keep conftest.py clean and modular by splitting fixtures into multiple files if needed.
  • Use descriptive test names and docstrings to explain test purpose.
  • Isolate tests to avoid dependencies and side effects between tests.
  • Keep test data and credentials out of source control; use environment variables or secure vaults.
Self Check

Where would you add a new fixture for database connection setup in this pytest project structure?

Key Result
Organize pytest tests in a clear folder structure with conftest.py for fixtures and pytest.ini for configuration.