0
0
PyTesttesting~8 mins

Mock return values and side effects in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Mock return values and side effects
Folder Structure
tests/
├── test_service.py          # Test cases using mocks
├── conftest.py              # Shared fixtures and mock setups
src/
├── service.py               # Code under test
utils/
├── helpers.py               # Utility functions

Test Framework Layers
  • Test Cases: Located in tests/, use pytest and unittest.mock to mock dependencies.
  • Mocks and Fixtures: Defined in conftest.py or inside tests to provide controlled return values and side effects.
  • Code Under Test: In src/, contains functions or classes whose behavior is tested.
  • Utilities: Helper functions or classes to support tests or application logic.
Configuration Patterns
  • Use pytest.ini or tox.ini for pytest configuration.
  • Manage environment variables or test data in conftest.py fixtures.
  • Mock external dependencies with unittest.mock.patch to control return values and side effects.
  • Use parametrization in pytest to test multiple scenarios with different mock return values.
Test Reporting and CI/CD Integration
  • Use pytest built-in reporting with pytest -v for detailed output.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests automatically on commits.
  • Generate HTML reports using plugins like pytest-html for easy review.
  • Fail tests if mocks are not called as expected to catch regressions.
Best Practices
  1. Mock only external dependencies, not the code under test itself.
  2. Use side_effect to simulate exceptions or multiple return values in mocks.
  3. Keep mocks simple and focused to avoid over-mocking.
  4. Use fixtures to share mock setups across multiple tests for consistency.
  5. Assert mock calls and parameters to verify correct interaction.
Self Check

Where in this folder structure would you add a new mock for an external API call used by service.py?

Key Result
Use pytest with unittest.mock to control return values and side effects for reliable unit tests.