or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-mocking.mdfixtures.mdindex.mdmock-creation.md
tile.json

tessl/pypi-pytest-mock

Thin-wrapper around the mock package for easier use with pytest

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pytest-mock@3.14.x

To install, run

npx @tessl/cli install tessl/pypi-pytest-mock@3.14.0

index.mddocs/

pytest-mock

A pytest plugin that provides comprehensive mocking capabilities through the mocker fixture. It serves as a thin wrapper around Python's unittest.mock module, offering automatic cleanup and enhanced pytest integration with better error reporting.

Package Information

  • Package Name: pytest-mock
  • Package Type: pypi
  • Language: Python
  • Installation: pip install pytest-mock

Core Imports

import pytest_mock
from pytest_mock import MockerFixture, PytestMockWarning

For type annotations:

from pytest_mock import MockType, AsyncMockType

Basic Usage

def test_unix_fs(mocker):
    # Patch a function/method
    mocker.patch('os.remove')
    
    # Call your code that uses os.remove
    UnixFS.rm('file')
    
    # Assert the mock was called correctly
    os.remove.assert_called_once_with('file')

def test_with_spy(mocker):
    # Create a spy that calls the original method
    spy = mocker.spy(UnixFS, 'rm')
    
    # Call the method - it runs normally
    UnixFS.rm('file')  # Actually removes the file
    
    # But you can still assert on the call
    spy.assert_called_once_with('file')

def test_with_stub(mocker):
    # Create a stub for testing callbacks
    callback = mocker.stub()
    
    # Use the stub in your code
    process_data(data, callback=callback)
    
    # Assert it was called
    callback.assert_called()

Architecture

pytest-mock integrates seamlessly with pytest's fixture system and provides:

  • MockerFixture: Main interface providing all mocking functionality
  • Automatic Cleanup: All mocks are automatically stopped after each test
  • Enhanced Assertions: Better error messages using pytest's introspection
  • Multiple Scopes: Support for function, class, module, package, and session scopes
  • Type Safety: Full type annotations for better IDE support

The plugin registers with pytest and provides fixtures at different scopes, ensuring mocks are properly managed throughout the test lifecycle.

Capabilities

Core Mocking Operations

Essential mocking functionality including patching functions/methods, creating mocks, and managing mock lifecycle. This covers the primary use cases for test mocking.

def patch(self, target: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def patch.object(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def patch.context_manager(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def patch.multiple(self, target: object, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> Dict[str, MockType]: ...
def patch.dict(self, in_dict: Union[Mapping, str], values=(), clear=False, **kwargs) -> Any: ...

Core Mocking Operations

Mock Creation and Management

Creating different types of mock objects and managing their lifecycle, including specialized utilities like spies and stubs for advanced testing scenarios.

def create_autospec(self, spec, spec_set=False, instance=False, **kwargs) -> MockType: ...
def spy(self, obj: object, name: str) -> MockType: ...
def stub(self, name=None) -> unittest.mock.MagicMock: ...
def async_stub(self, name=None) -> AsyncMockType: ...
def resetall(self, *, return_value=False, side_effect=False) -> None: ...
def stopall(self) -> None: ...
def stop(self, mock: unittest.mock.MagicMock) -> None: ...

Mock Creation and Management

Pytest Fixtures

Multiple pytest fixtures providing MockerFixture instances at different scopes, allowing flexible mock management across various test organization patterns.

@pytest.fixture
def mocker(pytestconfig) -> MockerFixture: ...

@pytest.fixture(scope="class")  
def class_mocker(pytestconfig) -> MockerFixture: ...

@pytest.fixture(scope="module")
def module_mocker(pytestconfig) -> MockerFixture: ...

@pytest.fixture(scope="package")
def package_mocker(pytestconfig) -> MockerFixture: ...

@pytest.fixture(scope="session")
def session_mocker(pytestconfig) -> MockerFixture: ...

Pytest Fixtures

Types

# Type aliases for mock objects
MockType = Union[
    unittest.mock.MagicMock,
    unittest.mock.AsyncMock, 
    unittest.mock.NonCallableMagicMock
]

AsyncMockType = unittest.mock.AsyncMock

# Main fixture class
class MockerFixture:
    """
    Fixture providing mock functionality with automatic cleanup.
    """
    
    # Patching interface
    patch: '_Patcher'  # Provides patch(), patch.object(), patch.multiple(), patch.dict()
    
    # Mock creation aliases  
    Mock: Type[unittest.mock.Mock]
    MagicMock: Type[unittest.mock.MagicMock]
    NonCallableMock: Type[unittest.mock.NonCallableMock]
    NonCallableMagicMock: Type[unittest.mock.NonCallableMagicMock]
    PropertyMock: Type[unittest.mock.PropertyMock]
    AsyncMock: Type[unittest.mock.AsyncMock]  # Python 3.8+
    
    # Mock utilities
    call: unittest.mock._Call
    ANY: unittest.mock._AnyComparer
    DEFAULT: unittest.mock._SentinelObject
    sentinel: unittest.mock._SentinelObject
    mock_open: Callable
    seal: Callable  # If available
    
    # Methods
    def create_autospec(self, spec, spec_set=False, instance=False, **kwargs) -> MockType: ...
    def spy(self, obj: object, name: str) -> MockType: ...
    def stub(self, name=None) -> unittest.mock.MagicMock: ...
    def async_stub(self, name=None) -> AsyncMockType: ...
    def resetall(self, *, return_value=False, side_effect=False) -> None: ...
    def stopall(self) -> None: ...
    def stop(self, mock: unittest.mock.MagicMock) -> None: ...

class _Patcher:
    """Internal patching interface - use via mocker.patch"""
    def __call__(self, target: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
    def object(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
    def context_manager(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
    def multiple(self, target: object, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> Dict[str, MockType]: ...
    def dict(self, in_dict: Union[Mapping, str], values=(), clear=False, **kwargs) -> Any: ...

# Warning class
class PytestMockWarning(UserWarning):
    """
    Base class for all warnings emitted by pytest-mock.
    
    This warning is emitted when:
    - Using mocks returned by pytest-mock as context managers (usually unnecessary)
    - Potential misuse of mocking patterns that could lead to issues
    
    The most common warning is when using mock objects as context managers:
    'Mocks returned by pytest-mock do not need to be used as context managers.
    The mocker fixture automatically undoes mocking at the end of a test.'
    
    This can be safely ignored if you're intentionally mocking a context manager.
    """

# Backward compatibility alias
MockFixture = MockerFixture  # Deprecated alias for MockerFixture

# Configuration

pytest-mock provides configuration options that can be set in pytest.ini, pyproject.toml, tox.ini, or setup.cfg files.

## Configuration Options

```python { .api }
# pytest.ini configuration options
[tool.pytest.ini_options]
mock_traceback_monkeypatch = true  # Enable enhanced assertion reporting
mock_use_standalone_module = false  # Use standalone mock module instead of unittest.mock

mock_traceback_monkeypatch (default: True):

  • Enhances mock assertion error messages with detailed parameter introspection
  • Shows differences between expected and actual call arguments
  • Disable with --tb=native or set to false to use standard mock error messages

mock_use_standalone_module (default: False):

  • Forces use of the standalone mock module from PyPI instead of unittest.mock
  • Useful for compatibility with older Python versions or specific mock features
  • Requires installing the mock package separately: pip install mock

Usage in pytest.ini:

[tool:pytest]
mock_traceback_monkeypatch = true
mock_use_standalone_module = false

Usage in pyproject.toml:

[tool.pytest.ini_options]
mock_traceback_monkeypatch = true
mock_use_standalone_module = false

Plugin hooks

def pytest_addoption(parser) -> None: """ Pytest hook that adds configuration options for pytest-mock.

Adds ini options:
- mock_traceback_monkeypatch: Enable enhanced assertion reporting (default: True)
- mock_use_standalone_module: Use standalone mock module instead of unittest.mock (default: False)
"""

def pytest_configure(config) -> None: """ Pytest hook that configures pytest-mock based on settings.

Wraps mock assertion methods for better error reporting when
mock_traceback_monkeypatch is enabled.
"""