Skip to content

Instantly share code, notes, and snippets.

@Xion
Created May 8, 2016 00:12
Show Gist options
  • Save Xion/8b98733d4b6be354be0ebae815ebd22d to your computer and use it in GitHub Desktop.
Save Xion/8b98733d4b6be354be0ebae815ebd22d to your computer and use it in GitHub Desktop.
Fix for Mock.configure_mock
"""
Extensions to the standard Python mock library.
Use it instead of the library itself.
"""
from __future__ import absolute_import
try:
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`).
Example::
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):
pass
class Mock(_ConfigureMockMixin, Mock):
pass
class NonCallableMagicMock(_ConfigureMockMixin, NonCallableMagicMock):
pass
class NonCallableMock(_ConfigureMockMixin, NonCallableMock):
pass
del _ConfigureMockMixin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment