0
0
PyTesttesting~8 mins

unittest.mock.patch in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - unittest.mock.patch
Folder Structure
my_pytest_project/
├── tests/
│   ├── test_example.py       # Test files using pytest and unittest.mock.patch
│   └── __init__.py
├── src/
│   ├── module.py             # Application code to be tested
│   └── __init__.py
├── conftest.py               # pytest fixtures and setup
├── requirements.txt          # Dependencies including pytest
└── pytest.ini                # pytest configuration file
Test Framework Layers
  • Application Layer (src/): Contains the real code to be tested.
  • Test Layer (tests/): Contains pytest test functions or classes using unittest.mock.patch to replace parts of the application during tests.
  • Fixtures & Setup (conftest.py): Shared test setup and reusable fixtures for mocking or test data.
  • Utilities: Helper functions or mock helpers can be added here if needed.
  • Configuration: pytest.ini or other config files to control test runs.
Configuration Patterns
  • Environment Variables: Use environment variables or pytest command line options to select test environment or toggle mocking behavior.
  • pytest.ini: Configure test markers, logging, and test paths.
  • Fixtures: Use conftest.py to define fixtures that apply patch globally or per test scope.
  • Mock Targeting: Always patch the object where it is used, not where it is defined, to ensure correct mocking.
Test Reporting and CI/CD Integration
  • pytest Output: Clear pass/fail results with detailed tracebacks for failed mocks or assertions.
  • Coverage: Use pytest-cov plugin to measure code coverage, including patched code paths.
  • CI/CD: Integrate pytest runs in CI pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests automatically on commits.
  • Test Logs: Capture logs during tests to help debug mock failures.
Best Practices
  1. Patch Where Used: Always patch the object in the module where it is used, not where it is defined, to avoid ineffective mocks.
  2. Use Context Managers or Decorators: Use @patch decorators or with patch(...): context managers to keep mocks limited in scope and easy to read.
  3. Keep Tests Independent: Each test should patch only what it needs and clean up after itself automatically.
  4. Mock External Calls: Use patch to replace slow or unreliable external services with fast, predictable mocks.
  5. Combine with Fixtures: Use pytest fixtures to reuse common patch setups and keep tests DRY (Don't Repeat Yourself).
Self Check

Where in this folder structure would you add a new patch for mocking a database call used in module.py?

Key Result
Use unittest.mock.patch in pytest tests to replace parts of the code during test execution, organized in a clear src/tests folder structure with fixtures and config.