0
0
PyTesttesting~8 mins

pytest-mock for enhanced mocking - Framework Patterns

Choose your learning style9 modes available
Framework Mode - pytest-mock for enhanced mocking
Folder Structure
test_project/
├── tests/
│   ├── test_example.py
│   ├── test_service.py
│   └── __init__.py
├── src/
│   ├── service.py
│   └── __init__.py
├── conftest.py
├── requirements.txt
└── pytest.ini

This structure separates source code in src/ and tests in tests/. The conftest.py file holds shared fixtures and mocks setup.

Test Framework Layers
  • Source Code Layer (src/): Contains application logic to be tested.
  • Test Layer (tests/): Contains test cases using pytest and pytest-mock for mocking dependencies.
  • Fixtures and Mocks (conftest.py): Central place for reusable pytest fixtures and mock setups using pytest-mock plugin.
  • Configuration Layer (pytest.ini): Holds pytest configuration like markers and test options.
  • Dependency Management (requirements.txt): Lists pytest and pytest-mock packages.
Configuration Patterns
  • pytest.ini: Configure test markers, addopts for verbosity, and test paths.
    [pytest]
    addopts = -v --tb=short
    markers =
        integration: mark test as integration test
        unit: mark test as unit test
    
  • conftest.py: Define fixtures for environment setup, mock objects, and shared test data.
    import pytest
    
    @pytest.fixture
    def mock_api_call(mocker):
        return mocker.patch('src.service.api_call')
    
  • Environment Variables: Use os.environ or pytest plugins like pytest-env to manage credentials and environment-specific settings.
Test Reporting and CI/CD Integration
  • Use pytest built-in reporting with verbose output for clear pass/fail results.
  • Integrate with CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins) to run tests automatically on code push.
  • Generate JUnit XML reports for CI tools to parse:
    pytest --junitxml=reports/results.xml
  • Use pytest plugins like pytest-html for human-readable HTML reports.
  • Fail fast option --maxfail=1 can be used to stop on first failure during CI runs.
Best Practices
  1. Use pytest-mock fixture: Use the mocker fixture from pytest-mock to patch dependencies cleanly and restore them automatically after tests.
  2. Isolate tests: Mock external calls and side effects to keep tests fast and reliable.
  3. Centralize mocks: Define common mocks in conftest.py to avoid duplication and improve maintainability.
  4. Use descriptive test names and markers: Helps organize and selectively run tests.
  5. Keep tests independent: Avoid shared state between tests to prevent flaky results.
Self Check

Where in this framework structure would you add a new mock for an external API call used in multiple tests?

Key Result
Use pytest-mock's mocker fixture in conftest.py to create reusable, clean mocks for isolated and maintainable tests.