0
0
PyTesttesting~8 mins

Docker-based test execution in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Docker-based test execution
Folder Structure
my-pytest-project/
├── tests/
│   ├── test_example.py
│   └── __init__.py
├── src/
│   └── app_code.py
├── docker/
│   ├── Dockerfile
│   └── entrypoint.sh
├── pytest.ini
├── requirements.txt
└── README.md

This structure keeps tests in tests/, source code in src/, and Docker files in docker/.

Test Framework Layers
  • Test Layer: tests/ folder with pytest test files.
  • Application Layer: src/ folder with application code.
  • Docker Layer: docker/Dockerfile and entrypoint.sh to build and run tests inside a container.
  • Configuration Layer: pytest.ini for pytest settings and requirements.txt for dependencies.
  • Utilities Layer: Helper scripts or fixtures can be added inside tests/ or a separate utils/ folder if needed.
Configuration Patterns
  • Environment Variables: Use environment variables in Docker to pass settings like API URLs or credentials.
  • pytest.ini: Configure pytest options such as markers, test paths, and logging.
  • requirements.txt: List all Python dependencies to install inside the Docker container.
  • Dockerfile: Defines the Python environment, installs dependencies, copies source and tests, and runs pytest.
  • Entrypoint Script: entrypoint.sh can set environment variables and execute pytest with arguments.
Test Reporting and CI/CD Integration
  • Test Reports: Use pytest plugins like pytest-html or pytest-junitxml to generate reports inside the container.
  • Volume Mounts: Mount host folders to container to save reports outside the container.
  • CI/CD: Integrate Docker test runs in pipelines (GitHub Actions, Jenkins, GitLab CI) by running docker build and docker run commands.
  • Exit Codes: Docker container exits with pytest exit code to indicate pass/fail status to CI.
Best Practices
  1. Isolate Tests: Run tests inside Docker to ensure consistent environment across machines.
  2. Keep Dockerfile Simple: Use lightweight base images (e.g., python:3.12-slim) and layer caching.
  3. Use Entrypoint Script: Manage environment setup and test execution cleanly.
  4. Separate Config: Use environment variables and config files instead of hardcoding values.
  5. Save Artifacts: Mount volumes to keep logs and reports after container finishes.
Self Check

Where in this folder structure would you add a new pytest fixture to share setup code for multiple tests?

Key Result
Use Docker to run pytest tests in a consistent, isolated environment with clear folder structure and config.