0
0
PyTesttesting~8 mins

monkeypatch fixture in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - monkeypatch fixture
Folder Structure for Pytest Project Using monkeypatch
project-root/
├── tests/
│   ├── test_example.py
│   ├── test_service.py
│   └── __init__.py
├── src/
│   ├── service.py
│   └── __init__.py
├── conftest.py
├── pytest.ini
└── requirements.txt
    
Test Framework Layers
  • Source Code Layer (src/): Contains application code to be tested.
  • Test Layer (tests/): Contains test files using pytest, including tests that use the monkeypatch fixture to replace parts of the code during tests.
  • Fixtures and Config (conftest.py): Defines shared fixtures and setup code, including reusable monkeypatch setups if needed.
  • Configuration (pytest.ini): Holds pytest configuration options like markers and test paths.
  • Utilities (optional): Helper functions or mocks used in tests.
Configuration Patterns

Use pytest.ini to configure pytest behavior, such as test discovery and markers.

Use conftest.py to define fixtures that can be shared across tests, including custom monkeypatch setups.

For environment-specific settings or credentials, use environment variables accessed via os.environ and patch them with monkeypatch.setenv() during tests.

Example: monkeypatch.setattr() to replace functions or methods temporarily during a test run.

Test Reporting and CI/CD Integration
  • Use pytest's built-in reporting with --junitxml=report.xml to generate XML reports for CI tools.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests automatically on code changes.
  • Use pytest plugins like pytest-html for readable HTML reports.
  • Ensure monkeypatch usage does not affect other tests by proper scoping and cleanup (pytest handles this automatically).
Best Practices for Using monkeypatch Fixture
  • Use monkeypatch to replace external dependencies or environment variables to isolate tests.
  • Keep monkeypatching limited to the scope of a single test to avoid side effects.
  • Prefer patching at the lowest possible level (e.g., patch functions or methods rather than entire modules).
  • Use monkeypatch.setenv() to safely modify environment variables during tests.
  • Write clear test names and comments explaining what is being patched and why.
Self Check

Where in this folder structure would you add a new monkeypatch fixture that mocks a database connection for multiple tests?

Key Result
Use pytest's monkeypatch fixture in tests/ with scoped patches to isolate and control dependencies during test runs.