CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mock

Rolling backport of unittest.mock for all Pythons

Pending
Overview
Eval results
Files

mock-objects.mddocs/

Mock Objects

Mock objects provide configurable replacements for Python objects, enabling comprehensive test isolation and behavior verification. The mock library offers several mock classes optimized for different use cases.

Capabilities

Mock

The primary mock class that creates callable mock objects with automatic attribute and method creation.

class Mock:
    def __init__(
        self,
        spec=None,
        side_effect=None,
        return_value=None,
        wraps=None,
        name=None,
        spec_set=None,
        unsafe=False,
        **kwargs
    ):
        """
        Create a mock object.
        
        Parameters:
        - spec: Specification object to validate mock usage against
        - side_effect: Function to call when mock is called, or exception to raise, or iterable of values
        - return_value: Value to return when mock is called
        - wraps: Object to wrap, calls pass through to wrapped object
        - name: Name of the mock for debugging
        - spec_set: Like spec but more restrictive
        - unsafe: Allow access to dangerous attributes
        - **kwargs: Attributes to set on the mock
        """
    
    def assert_called_with(self, *args, **kwargs):
        """Assert the mock was last called with specified arguments."""
    
    def assert_called_once_with(self, *args, **kwargs):
        """Assert the mock was called exactly once with specified arguments."""
    
    def assert_any_call(self, *args, **kwargs):
        """Assert the mock was called with specified arguments at some point."""
    
    def assert_has_calls(self, calls, any_order=False):
        """Assert the mock has been called with the specified calls."""
    
    def assert_called(self):
        """Assert the mock has been called at least once."""
    
    def assert_called_once(self):
        """Assert the mock has been called exactly once."""
    
    def assert_not_called(self):
        """Assert the mock has never been called."""
    
    def reset_mock(self, visited=None, return_value=False, side_effect=False):
        """Reset the mock to initial state."""
    
    def configure_mock(self, **kwargs):
        """Configure the mock with keyword arguments."""
    
    def attach_mock(self, mock, attribute):
        """Attach a mock as an attribute."""
    
    def mock_add_spec(self, spec, spec_set=False):
        """Add a spec to the mock."""
    
    # Properties
    called: bool  # Whether the mock has been called
    call_count: int  # Number of times the mock has been called
    call_args: call  # Arguments from the last call
    call_args_list: list  # List of all call arguments
    mock_calls: list  # List of all calls including method calls
    method_calls: list  # List of method calls only
    return_value: object  # Value to return when called
    side_effect: object  # Side effect when called

NonCallableMock

A mock that cannot be called, used for mocking non-callable objects like modules, classes (not instances), or other objects that shouldn't be called.

class NonCallableMock:
    def __init__(
        self,
        spec=None,
        wraps=None,
        name=None,
        spec_set=None,
        **kwargs
    ):
        """
        Create a non-callable mock object.
        
        Similar to Mock but raises TypeError when called.
        """
    
    def assert_called_with(self, *args, **kwargs):
        """Raises AssertionError - non-callable mocks cannot be called."""
    
    def configure_mock(self, **kwargs):
        """Configure the mock with keyword arguments."""
    
    def attach_mock(self, mock, attribute):
        """Attach a mock as an attribute."""
    
    def mock_add_spec(self, spec, spec_set=False):
        """Add a spec to the mock."""
    
    def reset_mock(self, visited=None):
        """Reset the mock to initial state."""

MagicMock

A mock with magic method support, automatically creating mock implementations for Python's special methods like __str__, __iter__, etc.

class MagicMock(Mock):
    def __init__(self, *args, **kwargs):
        """
        Create a mock with magic method support.
        
        Inherits all Mock functionality and adds automatic magic method creation.
        Magic methods like __str__, __iter__, __len__ are automatically mocked.
        """

NonCallableMagicMock

A non-callable version of MagicMock, combining the restrictions of NonCallableMock with magic method support.

class NonCallableMagicMock(NonCallableMock):
    def __init__(self, *args, **kwargs):
        """
        Create a non-callable mock with magic method support.
        
        Cannot be called but has automatic magic method creation.
        """

AsyncMock

A mock designed specifically for async/await code, providing proper coroutine support and async method mocking.

class AsyncMock(Mock):
    def __init__(self, *args, **kwargs):
        """
        Create a mock for async/await code.
        
        Returns coroutines when called and properly handles async context managers.
        Automatically detects when specs are async and creates appropriate mocks.
        """
    
    async def __call__(self, *args, **kwargs):
        """Call the async mock, returning a coroutine."""
    
    def assert_awaited(self):
        """Assert the mock has been awaited at least once."""
    
    def assert_awaited_once(self):
        """Assert the mock has been awaited exactly once."""
    
    def assert_awaited_with(self, *args, **kwargs):
        """Assert the mock was last awaited with specified arguments."""
    
    def assert_awaited_once_with(self, *args, **kwargs):
        """Assert the mock was awaited exactly once with specified arguments."""
    
    def assert_any_await(self, *args, **kwargs):
        """Assert the mock was awaited with specified arguments at some point."""
    
    def assert_has_awaits(self, calls, any_order=False):
        """Assert the mock has been awaited with the specified calls."""
    
    def assert_not_awaited(self):
        """Assert the mock has never been awaited."""
    
    def reset_mock(self, *args, **kwargs):
        """Reset the mock including await-specific state."""
    
    # Properties
    await_count: int  # Number of times the mock has been awaited
    await_args: call  # Arguments from the last await
    await_args_list: list  # List of all await arguments

ThreadingMock

A thread-safe version of Mock that uses locks to prevent race conditions in multithreaded testing scenarios. Provides additional synchronization methods for waiting on mock calls.

class ThreadingMock(Mock):
    DEFAULT_TIMEOUT: float = 10.0  # Default timeout for wait methods
    
    def __init__(self, *args, **kwargs):
        """
        Create a thread-safe mock object.
        
        All mock operations are protected by locks to prevent race conditions.
        Inherits all Mock functionality with thread safety guarantees.
        """
    
    def wait_until_called(self, *, timeout=None):
        """
        Wait until the mock is called at least once.
        
        Parameters:
        - timeout: Maximum time to wait in seconds (defaults to DEFAULT_TIMEOUT)
        
        Returns:
        True if mock was called within timeout, False otherwise
        """
    
    def wait_until_any_call_with(self, *args, **kwargs):
        """
        Wait until the mock is called with specific arguments.
        
        Parameters:
        - *args: Positional arguments to wait for
        - **kwargs: Keyword arguments to wait for
        
        Returns:
        True if mock was called with arguments within timeout, False otherwise
        """

PropertyMock

A mock designed specifically for properties and descriptors, implementing the descriptor protocol.

class PropertyMock(Mock):
    def __init__(self, return_value=None, **kwargs):
        """
        Create a mock for property objects.
        
        Implements descriptor protocol (__get__, __set__, __delete__).
        Used to mock properties, class methods, and static methods.
        """
    
    def __get__(self, obj, obj_type):
        """Descriptor get method."""
    
    def __set__(self, obj, value):
        """Descriptor set method."""
    
    def __delete__(self, obj):
        """Descriptor delete method."""

Common Patterns

Basic Mock Usage

from mock import Mock

# Create and use a simple mock
mock_obj = Mock()
mock_obj.method.return_value = 'result'
result = mock_obj.method('arg')
mock_obj.method.assert_called_with('arg')

Mock with Spec

from mock import Mock

class RealClass:
    def method(self, arg): pass

# Mock with spec prevents typos and invalid attribute access
mock_obj = Mock(spec=RealClass)
mock_obj.method('arg')  # Valid
# mock_obj.typo()  # Would raise AttributeError

Async Mock Usage

from mock import AsyncMock
import asyncio

async def test_async_function():
    mock_async = AsyncMock()
    mock_async.return_value = 'async result'
    
    result = await mock_async('arg')
    assert result == 'async result'
    mock_async.assert_awaited_once_with('arg')

ThreadingMock Usage

from mock import ThreadingMock
import threading
import time

def test_threaded_function():
    mock_service = ThreadingMock()
    
    def worker():
        time.sleep(0.1)  # Simulate work
        mock_service('worker_call')
    
    # Start worker thread
    thread = threading.Thread(target=worker)
    thread.start()
    
    # Wait for mock to be called (with timeout)
    called = mock_service.wait_until_called(timeout=1.0)
    assert called == True
    
    # Wait for specific call arguments
    specific_call = mock_service.wait_until_any_call_with('worker_call')
    assert specific_call == True
    
    thread.join()
    mock_service.assert_called_with('worker_call')

Install with Tessl CLI

npx tessl i tessl/pypi-mock

docs

index.md

mock-objects.md

patching.md

special-objects.md

utilities.md

tile.json