CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-types-mock

Type stubs for the mock library providing comprehensive type annotations for Mock, MagicMock, patch decorators, and other testing utilities

Overview
Eval results
Files

patching.mddocs/

Patching System

Comprehensive patching decorators and context managers for temporarily replacing objects during testing. The patching system provides flexible strategies for dependency injection, object replacement, and test isolation with automatic cleanup.

Capabilities

Basic Patching

The main patch decorator and context manager for replacing objects during tests.

def patch(
    target: str,
    new=...,                    # DEFAULT creates MagicMock/AsyncMock
    spec=None,
    create: bool = False,
    spec_set=None,
    autospec=None,
    new_callable=None,
    unsafe: bool = False,
    **kwargs
):
    """
    Temporarily replace an object during testing.
    
    Parameters:
    - target: String path to object to patch (e.g., 'module.function')
    - new: Replacement object (DEFAULT creates appropriate mock)
    - spec: Specification for created mock
    - create: Create attribute if it doesn't exist
    - spec_set: Like spec but restricts mock to only spec attributes
    - autospec: Automatically create spec from target object
    - new_callable: Factory for creating replacement object
    - unsafe: Allow patching built-in or restricted objects
    - **kwargs: Additional arguments for mock creation
    
    Returns:
    Context manager/decorator that yields the replacement object
    """

Usage examples:

from mock import patch, Mock

# As decorator
@patch('module.function')
def test_function(mock_func):
    mock_func.return_value = "mocked_result"
    # Test code here
    mock_func.assert_called_once()

# As context manager
def test_with_context():
    with patch('module.function') as mock_func:
        mock_func.return_value = "mocked_result"
        # Test code here
        mock_func.assert_called_once()

# Provide specific replacement
@patch('module.function', return_value="specific_result")
def test_with_specific_mock(mock_func):
    # mock_func is configured with return_value
    pass

# Create mock with specification
@patch('module.MyClass', autospec=True)
def test_with_autospec(mock_class):
    # mock_class has same interface as MyClass
    instance = mock_class()
    instance.method.return_value = "test"

Object Patching

Patch attributes of existing objects.

def patch.object(
    target,
    attribute: str,
    new=...,
    spec=None,
    create: bool = False,
    spec_set=None,
    autospec=None,
    new_callable=None,
    unsafe: bool = False,
    **kwargs
):
    """
    Patch an attribute of an existing object.
    
    Parameters:
    - target: Object containing the attribute to patch
    - attribute: Name of attribute to patch
    - Other parameters same as patch()
    """

Usage example:

import os
from mock import patch

# Patch method of existing object
@patch.object(os, 'getcwd', return_value='/fake/path')
def test_getcwd(mock_getcwd):
    assert os.getcwd() == '/fake/path'
    mock_getcwd.assert_called_once()

# Patch with context manager
def test_patch_object():
    with patch.object(os.path, 'exists', return_value=True) as mock_exists:
        assert os.path.exists('/any/path') == True
        mock_exists.assert_called_once_with('/any/path')

Multiple Patching

Patch multiple attributes of the same object simultaneously.

def patch.multiple(
    target,
    spec=None,
    create: bool = False,
    spec_set=None,
    autospec=None,
    new_callable=None,
    unsafe: bool = False,
    **kwargs
):
    """
    Patch multiple attributes of a target object.
    
    Parameters:
    - target: Object to patch
    - **kwargs: attribute_name=replacement pairs
    - Other parameters same as patch()
    
    Returns:
    Dictionary mapping attribute names to mock objects
    """

Usage example:

from mock import patch

# Patch multiple methods
@patch.multiple('os', getcwd=Mock(return_value='/fake'), getpid=Mock(return_value=123))
def test_multiple_patches(getcwd_mock, getpid_mock):
    # getcwd_mock and getpid_mock are available
    assert os.getcwd() == '/fake'
    assert os.getpid() == 123

# With context manager - returns dict
def test_multiple_context():
    with patch.multiple('os', getcwd=Mock(return_value='/fake'), getpid=Mock(return_value=123)) as mocks:
        assert os.getcwd() == '/fake'
        assert os.getpid() == 123
        mocks['getcwd'].assert_called_once()
        mocks['getpid'].assert_called_once()

Patch Management

def patch.stopall() -> None:
    """Stop all active patches created with start() method."""

Usage with manual patch management:

from mock import patch

# Manual patch lifecycle
def test_manual_patches():
    # Start patches manually
    patch1 = patch('module.func1')
    patch2 = patch('module.func2')
    
    mock1 = patch1.start()
    mock2 = patch2.start()
    
    try:
        # Test code here
        mock1.return_value = "result1"
        mock2.return_value = "result2"
        
        # Your test assertions
        pass
    finally:
        # Stop all patches
        patch.stopall()

Dictionary Patching

Temporarily modify dictionaries during testing.

class patch.dict:
    def __init__(
        self,
        in_dict,
        values=(),
        clear: bool = False,
        **kwargs
    ) -> None:
        """
        Temporarily modify a dictionary.
        
        Parameters:
        - in_dict: Dictionary to modify
        - values: Values to set (dict or iterable of key-value pairs)
        - clear: Clear dictionary before setting values
        - **kwargs: Additional key-value pairs to set
        """
        
    def __call__(self, func):
        """Use as decorator."""
        
    def __enter__(self):
        """Use as context manager."""
        
    def __exit__(self, *args):
        """Context manager cleanup."""
        
    def start(self) -> None:
        """Start dictionary patching."""
        
    def stop(self) -> None:
        """Stop dictionary patching."""

Usage examples:

import os
from mock import patch

# Patch environment variables
@patch.dict(os.environ, {'TEST_VAR': 'test_value'})
def test_env_var():
    assert os.environ['TEST_VAR'] == 'test_value'

# Context manager with clear
def test_env_clear():
    with patch.dict(os.environ, {'ONLY_VAR': 'only_value'}, clear=True):
        # os.environ only contains ONLY_VAR
        assert os.environ == {'ONLY_VAR': 'only_value'}
    # Original environment restored

# Patch custom dictionary
my_dict = {'existing': 'value'}

@patch.dict(my_dict, new_key='new_value')
def test_custom_dict():
    assert my_dict['new_key'] == 'new_value'
    assert my_dict['existing'] == 'value'  # Original key preserved

Advanced Patching Patterns

# Patch with side effect
@patch('requests.get')
def test_with_side_effect(mock_get):
    def side_effect(url):
        if 'success' in url:
            return Mock(status_code=200, json=lambda: {'data': 'success'})
        else:
            return Mock(status_code=404)
    
    mock_get.side_effect = side_effect
    
    # Test different responses based on input
    response = requests.get('http://example.com/success')
    assert response.status_code == 200

# Patch class and instance methods
@patch('module.MyClass')
def test_class_and_instance(mock_class):
    # Configure class mock
    mock_instance = Mock()
    mock_class.return_value = mock_instance
    mock_instance.method.return_value = "instance_result"
    
    # Test code
    obj = module.MyClass()
    result = obj.method()
    assert result == "instance_result"
    
    mock_class.assert_called_once()
    mock_instance.method.assert_called_once()

# Nested patching
@patch('outer.inner.function')
@patch('other.module.function')
def test_nested_patches(mock_other, mock_inner):
    # Order matters - innermost decorator is first parameter
    mock_inner.return_value = "inner_result"
    mock_other.return_value = "other_result"

Type Definitions

# Patch object types (internal implementation details)
class _patch:
    """Internal patch implementation class."""
    def __init__(self, getter, attribute: str, new, spec, create: bool, spec_set, autospec, new_callable, kwargs, *, unsafe: bool = False) -> None: ...
    def __enter__(self): ...
    def __exit__(self, exc_type, exc_value, traceback) -> None: ...
    def start(self): ...
    def stop(self) -> None: ...

class _patch_dict:
    """Internal dictionary patch implementation class."""
    def __init__(self, in_dict, values=(), clear: bool = False, **kwargs) -> None: ...
    def __enter__(self): ...
    def __exit__(self, *args) -> None: ...
    def start(self) -> None: ...
    def stop(self) -> None: ...

Install with Tessl CLI

npx tessl i tessl/pypi-types-mock

docs

async-mocking.md

core-mocking.md

index.md

patching.md

utilities.md

tile.json