case.mock

case.mock.ContextMock(*args, **kwargs)[source]

Mock that mocks with statement contexts.

class case.mock.MagicMock(*args, **kw)[source]
class case.mock.Mock(*args, **kw)[source]
class case.mock.MockCallbacks(*args, **kwargs)[source]
case.mock.create_patcher(*partial_path)[source]
case.mock.environ(env_name, env_value)[source]

Mock environment variable value.

Example:

@mock.environ('DJANGO_SETTINGS_MODULE', 'proj.settings')
def test_other_settings(self):
    ...
case.mock.mask_modules(*modnames)[source]

Ban some modules from being importable inside the context

For example:

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

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

Or as a decorator:

@mask_modules('sys')
def test_foo(self):
    ...
case.mock.module(*names)[source]

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

case.mock.module_exists(*modules)[source]

Patch one or more modules to ensure they exist.

A module name with multiple paths (e.g. gevent.monkey) will ensure all parent modules are also patched (gevent + gevent.monkey).

Decorator example:

@mock.module_exists('gevent.monkey')
def test_foo(self):
    pass

Context example:

with mock.module_exists('gevent.monkey'):
    gevent.monkey.patch_all = Mock(name='patch_all')
    ...
case.mock.mute()[source]

Redirect sys.stdout and sys.stderr to /dev/null, silencent them. Decorator example:

@mock.mute
def test_foo(self):
    something()
Context example::
with mock.mute():

something()

case.mock.open(typ=<class 'case.utils.WhateverIO'>, side_effect=None)[source]

Patch builtins.open so that it returns StringIO object.

Parameters:
  • typ – File object for open to return. Defaults to WhateverIO which is the bastard child of io.StringIO and io.BytesIO accepting both bytes and unicode input.

  • side_effect – Additional side effect for when the open context is entered.

Decorator example:

@mock.open()
def test_foo(self, open_fh):
    something_opening_and_writing_a_file()
    self.assertIn('foo', open_fh.getvalue())

Context example:

with mock.open(io.BytesIO) as open_fh:
    something_opening_and_writing_bytes_to_a_file()
    self.assertIn(b'foo', open_fh.getvalue())
case.mock.patch(target, new=sentinel.DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs)[source]

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.

case.mock.platform_pyimp(value=None)[source]

Mock platform.python_implementation

Decorator example:

@mock.platform_pyimp('PyPy')
def test_foo(self):
    ...

Context example:

with mock.platform_pyimp('PyPy'):
    ...
case.mock.pypy_version(value=None)[source]

Mock sys.pypy_version_info

Decorator example:

@mock.pypy_version((3, 6, 1))
def test_foo(self):
    ...

Context example:

with mock.pypy_version((3, 6, 1)):
    ...
case.mock.replace_module_value(module, name, value=None)[source]

Mock module value, given a module, attribute name and value.

Decorator example:

@mock.replace_module_value(module, 'CONSTANT', 3.03)
def test_foo(self):
    ...

Context example:

with mock.replace_module_value(module, 'CONSTANT', 3.03):
    ...
case.mock.reset_modules(*modules)[source]

Remove modules from sys.modules by name, and reset back again when the test/context returns.

Decorator example:

@mock.reset_modules('celery.result', 'celery.app.base')
def test_foo(self):
    pass

Context example:

with mock.reset_modules('celery.result', 'celery.app.base'):
    pass
case.mock.restore_logging()[source]

Restore root logger handlers after test returns.

Decorator example:

@mock.restore_logging()
def test_foo(self):
    setup_logging()

Context example:

with mock.restore_logging():
    setup_logging()
case.mock.sleepdeprived(module=<module 'time' (built-in)>)[source]

Mock time.sleep to do nothing.

Example:

@mock.sleepdeprived()  # < patches time.sleep
@mock.sleepdeprived(celery.result)  # < patches celery.result.sleep
case.mock.stdouts()[source]

Override sys.stdout and sys.stderr with StringIO instances.

Decorator example:

@mock.stdouts
def test_foo(self, stdout, stderr):
    something()
    self.assertIn('foo', stdout.getvalue())

Context example:

with mock.stdouts() as (stdout, stderr):
    something()
    self.assertIn('foo', stdout.getvalue())
case.mock.sys_platform(value=None)[source]

Mock sys.platform

Decorator example:

@mock.sys_platform('darwin')
def test_foo(self):
    ...

Context example:

with mock.sys_platform('darwin'):
    ...
case.mock.sys_version(value=None)[source]

Mock sys.version_info

Decorator example:

@mock.sys_version((3, 6, 1))
def test_foo(self):
    ...

Context example:

with mock.sys_version((3, 6, 1)):
    ...
case.mock.wrap_logger(logger, loglevel=40)[source]

Wrap logging.Logger with a StringIO() handler.

yields a StringIO handle.

Example:

with mock.wrap_logger(logger, loglevel=logging.DEBUG) as sio:
    ...
    sio.getvalue()