mode.utils.mocks — mode-ng 0.4.0 documentation

# `mode.utils.mocks`

Mocking and testing utilities.

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

  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 :pypi:`aiohttp` client:

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

      @pytest.fixture()
      def session(monkeypatch):
          session = Mock(
              name='http_client',
              autospec=ClientSession,
              request=Mock(
                  return_value=AsyncContextManagerMock(
                      return_value=Mock(
                          autospec=Response,
                          status=http.HTTPStatus.OK,
                          json=AsyncMock(
                              return_value={'hello': 'json'},
                          ),
                      ),
                  ),
              ),
          )
          monkeypatch.setattr('where.is.ClientSession', session)
          return session

      @pytest.mark.asyncio
      async def test_session(session):
          from where.is import ClientSession
          session = ClientSession()
          async with session.get('http://example.com') as response:
              assert response.status == http.HTTPStatus.OK
              assert await response.json() == {'hello': 'json'}

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

  A magic mock type for `async def` functions/methods.

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

  Mock for `async def` function/method or anything awaitable.

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

  Mock that mocks `with` statement contexts.

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

  Mock a `asyncio.Future`.

  assert_awaited() → None
  assert_not_awaited() → None
  awaited = False

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

  Class used to check for multiple alternatives.

      assert foo.value IN(a, b)

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.

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

  Mock object.

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

    Restore the mock object to its initial state.

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 http://bitbucket.org/runeh/snippets/src/tip/missing_modules.py

mode.utils.mocks.patch(target, new=sentinel.DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **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 an AsyncMock if the patched object is an async function or a `MagicMock otherwise. 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 AsyncMock is used for async functions and MagicMock for the rest.

  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 will raise a RuntimeError if passed some common misspellings of the arguments autospec and spec_set. Pass the argument unsafe with the value True to disable that check.

  patch takes arbitrary keyword arguments. These will be passed to AsyncMock if the patched object is asynchronous, to MagicMock otherwise or to new_callable if specified.

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

mode.utils.mocks.patch_module(*names: str, new_callable: ~typing.Any = <class 'mode.utils.mocks.Mock'>) → Iterator

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