Mocking and testing utilities.

class mode.utils.mocks.IN(*alternatives: Any)

Class used to check for multiple alternatives.

assert foo.value IN(a, b)
class mode.utils.mocks.Mock(spec=None, side_effect=None, return_value=sentinel.DEFAULT, wraps=None, name=None, spec_set=None, parent=None, _spec_state=None, _new_name='', _new_parent=None, **kwargs)

Mock object.

global_call_count: Optional[int] = None
call_counts: List[int] = None
reset_mock(*args: Any, **kwargs: Any) → None

Restore the mock object to its initial state.

mode.utils.mocks.ContextMock(*args: Any, **kwargs: Any) → mode.utils.mocks._ContextMock

Mock that mocks with statement contexts.

class mode.utils.mocks.AsyncMock(*args: Any, name: str = None, **kwargs: Any)

Mock for async def function/method or anything awaitable.

class mode.utils.mocks.AsyncMagicMock(*args: Any, name: str = None, **kwargs: Any)

A magic mock type for async def functions/methods.

class mode.utils.mocks.AsyncContextMock(*args: Any, aenter_return: Any = None, aexit_return: Any = None, side_effect: Union[Callable, BaseException] = None, **kwargs: Any)

Mock for typing.AsyncContextManager.

You can use this to mock asynchronous context managers, when an object with a fully defined __aenter__ and __aexit__ is required.

Here’s an example mocking an aiohttp client:

import http
from aiohttp.client import ClientSession
from aiohttp.web import Response
from mode.utils.mocks import AsyncContextManagerMock, AsyncMock, Mock

def session(monkeypatch):
    session = Mock(
                        return_value={'hello': 'json'},
    monkeypatch.setattr('', session)
    return session

async def test_session(session):
    from import ClientSession
    session = ClientSession()
    async with session.get('') as response:
        assert response.status == http.HTTPStatus.OK
        assert await response.json() == {'hello': 'json'}
class mode.utils.mocks.FutureMock(*args: Any, **kwargs: Any)

Mock a asyncio.Future.

awaited = False
assert_awaited() → None
assert_not_awaited() → None
mode.utils.mocks.patch_module(*names: str, new_callable: Any = <class 'mode.utils.mocks.Mock'>) → Iterator

Mock one or modules such that every attribute is a Mock.

mode.utils.mocks.mask_module(*modnames: str) → Iterator

Ban some modules from being importable inside the context.

For example:

>>> with mask_module('sys'):
...     try:
...         import sys
...     except ImportError:
...         print('sys not found')
sys not found

>>> import sys  # noqa
>>> sys.version
(2, 5, 2, 'final', 0)

Taken from

class mode.utils.mocks.MagicMock(*args, **kw)

MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself.

If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.

Attributes and the return value of a MagicMock will also be MagicMocks.

mock_add_spec(spec, spec_set=False)

Add a spec to a mock. spec can either be an object or a list of strings. Only attributes on the spec can be fetched as attributes from the mock.

If spec_set is True then only attributes on the spec can be set.
mode.utils.mocks.patch(target, new=sentinel.DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

patch acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the target is patched with a new object. When the function/with statement exits the patch is undone.

If new is omitted, then the target is replaced with a MagicMock. If patch is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function. If patch is used as a context manager the created mock is returned by the context manager.

target should be a string in the form ‘package.module.ClassName’. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling patch from. The target is imported when the decorated function is executed, not at decoration time.

The spec and spec_set keyword arguments are passed to the MagicMock if patch is creating one for you.

In addition you can pass spec=True or spec_set=True, which causes patch to pass in the object being mocked as the spec/spec_set object.

new_callable allows you to specify a different class, or callable object, that will be called to create the new object. By default MagicMock is used.

A more powerful form of spec is autospec. If you set autospec=True then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a TypeError if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class.

Instead of autospec=True you can pass autospec=some_object to use an arbitrary object as the spec instead of the one being replaced.

By default patch will fail to replace attributes that don’t exist. If you pass in create=True, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don’t actually exist!

Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. patch finds tests by looking for method names that start with patch.TEST_PREFIX. By default this is test, which matches the way unittest finds tests. You can specify an alternative prefix by setting patch.TEST_PREFIX.

Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use “as” then the patched object will be bound to the name after the “as”; very useful if patch is creating a mock object for you.

patch takes arbitrary keyword arguments. These will be passed to the Mock (or new_callable) on construction.

patch.dict(…), patch.multiple(…) and patch.object(…) are available for alternate use-cases.