0
0
PyTesttesting~8 mins

monkeypatch.setattr in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - monkeypatch.setattr
Folder Structure
my_pytest_project/
├── tests/
│   ├── test_example.py
│   ├── test_utils.py
│   └── __init__.py
├── src/
│   ├── my_module.py
│   └── __init__.py
├── conftest.py
├── pytest.ini
└── requirements.txt
Test Framework Layers
  • Source Code Layer (src/): Contains the application code to be tested.
  • Test Layer (tests/): Holds test files using pytest functions and classes.
  • Fixtures and Helpers (conftest.py): Defines reusable fixtures and setup/teardown logic.
  • Monkeypatch Usage: Used inside test functions to temporarily replace attributes or functions for isolated testing.
  • Configuration (pytest.ini): Stores pytest settings like markers and test paths.
Configuration Patterns

Use pytest.ini to configure test runs, for example:

[pytest]
addopts = -v --tb=short
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')

Manage environments and credentials via environment variables or separate config files loaded in conftest.py.

Monkeypatch allows dynamic replacement of attributes or functions during tests without permanent changes, supporting isolated and environment-independent tests.

Test Reporting and CI/CD Integration
  • Use pytest built-in reporting with verbose output (-v) and short tracebacks (--tb=short).
  • Integrate with CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins) to run tests on each commit.
  • Generate reports with plugins like pytest-html for readable test summaries.
  • Monkeypatch usage ensures tests are isolated and reliable, improving CI stability.
Best Practices
  • Use monkeypatch only inside test functions or fixtures to avoid side effects outside tests.
  • Patch only what is necessary to keep tests clear and maintainable.
  • Prefer patching imports at the location where they are used to ensure correct behavior.
  • Combine monkeypatch with fixtures for reusable and clean test setups.
  • Always restore original behavior automatically by relying on monkeypatch's built-in cleanup.
Self Check

Where in this folder structure would you add a new monkeypatch fixture that replaces a function in my_module.py for multiple tests?

Key Result
Use monkeypatch.setattr inside pytest test functions or fixtures to safely replace attributes for isolated testing.