Skip to content

Instantly share code, notes, and snippets.

@Xion Xion/
Created May 8, 2016

What would you like to do?
Fix for Mock.configure_mock
Extensions to the standard Python mock library.
Use it instead of the library itself.
from __future__ import absolute_import
from unittest.mock import *
except ImportErorr:
from mock import *
class _ConfigureMockMixin(object):
"""Mixin for mock classes that makes :meth:`configure_mock`
return the mock object.
This allows to unambiguously separate attributes to be set on mock
from the regular ``*Mock`` constructor parameters, like ``name``
or ``return_value``, while still keeping the mock definition as
a single expression (and thus making it usable e.g. as ``new=`` argument
for :func:`mock.patch`).
mock_foo = Mock(name="Foo mock name") \
.configure_mock(name="Foo object name")
def configure_mock(self, **attrs):
super(_ConfigureMockMixin, self).configure_mock(**attrs)
return self
# Mock classes
class MagicMock(_ConfigureMockMixin, MagicMock):
class Mock(_ConfigureMockMixin, Mock):
class NonCallableMagicMock(_ConfigureMockMixin, NonCallableMagicMock):
class NonCallableMock(_ConfigureMockMixin, NonCallableMock):
del _ConfigureMockMixin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.