Separate unittest.mock wrapper methods from unittest.mock behavior/implementation

From the python/cpython [GitHub - python/cpython: The Python programming language] source code - issues/feature-request:

New features to Python should first be discussed elsewhere before creating issues on GitHub,

According to this SO question this feature is very popular (41k views, first page by tags [mocking] and [python]).

The idea is very easy:
Sometimes we need only check that object was called but not interfere at the object logic/behavior itself.
The current most popular solution is to mock/patch the required object and apply mock method assert_called.... This interferes with the object’s behavior without any point.

Usecase and usage example:

from unittest.mock import future_wrapper  # Such object still not exists


def method_to_test()
    ...


def entry_point()
    method_to_test()
    ...

def test_method_to_test():
    wrapped_method_to_test = future_wrapper(spec=method_to_test)  # No need to specify side_effect, method behavior was not touched.
    entry_point()
    wrapped_method_to_test.assert_called_once()

# Another possible implementation:

def test_method_to_test():
    # No need to specify side_effect, method behavior was not touched.
    with future_wrapper(spec=method_to_test) as wrapped_method_to_test:
        wrapped_method_to_test()
        wrapped_method_to_test.assert_called_once()

Current implementation:

from unittest.mock import create_autospec


def method_to_test()
    ...


def entry_point()
    method_to_test()
    ...


def test_method_to_test():
    mocked_error_handler = create_autospec(
        spec=method_to_test,
        spec_set=True,
        side_effect=lambda *args, **kwargs: method_to_test(*args, **kwargs))
    entry_point()
    wrapped_method_to_test.assert_called_once()

See other possible current implementations in the SO question link in top of the post (new users can put only 2 links).

1 Like