Skip to content
This repository has been archived by the owner on Mar 27, 2022. It is now read-only.

Commit

Permalink
added ability to specify name in mock()
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim Cuthbertson committed Apr 29, 2009
1 parent a623c76 commit 352c395
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
35 changes: 28 additions & 7 deletions mocktest/mockwrapper.py
Expand Up @@ -15,19 +15,38 @@
from mockmatcher import MockMatcher
from mockerror import MockError

def mock(raw = None, proxied = None):
def mock(*args):
"""
return a mock wrapper for the given silent mock, delegating to `proxied`
when a given call is not set to be intercepted by the mock. You can use
the mock wrapper to set expectations or get invocation details for a silent mock
usage:
mock("name of mock"), or
mock(raw_mock_to_wrap), or
mock(proxied_object), or
mock(raw, proxied)
"""
raw, name, proxied = None, None, None
if len(args) == 1:
arg = args[0]
if isinstance(arg, str):
name = arg
elif isinstance(arg, SilentMock):
raw = arg
else:
proxied = arg
elif len(args) == 2:
raw, proxied = args
elif len(args) == 0:
# this is ok too
pass
else:
raise TypeError("mock takes zero, one, or two arguments - got %s" % (len(args),))

if raw is None:
raw = raw_mock()
if (not isinstance(raw, SilentMock)) and proxied is None:
# make mock(real_obj) act like mock(None, proxied=real_obj)
proxied = raw
raw = raw_mock()
return MockWrapper(raw, proxied)
return MockWrapper(raw, proxied, name)

class MockWrapper(RealSetter):
"""
Expand All @@ -37,7 +56,7 @@ class MockWrapper(RealSetter):
all setattr and getattr calls go via the attached silent mock's _mock_get and _mock_set
"""
_all_expectations = None
def __init__(self, wrapped_mock = None, proxied = None):
def __init__(self, wrapped_mock = None, proxied = None, name = None):
if self.__class__._all_expectations is None:
raise RuntimeError(("%s._setup has not been called. " +
"Make sure you are inheriting from mocktest.TestCase, " +
Expand All @@ -48,6 +67,8 @@ def __init__(self, wrapped_mock = None, proxied = None):
raise TypeError("expected SilentMock, got %s" % (wrapped_mock.__class__.__name__,))
self._real_set(_mock = wrapped_mock)
self._proxied = proxied
if name:
self.name = name

# delegate getting and setting to SilentMock
def _set(self, **kwargs):
Expand Down
4 changes: 4 additions & 0 deletions test/mock_test.py
Expand Up @@ -96,6 +96,10 @@ def test_spec_class_in_constructor(self):

self.assertRaises(AttributeError, lambda: wrapper.raw.__something__)

def test_should_set_name_if_single_string_constructor_arg(self):
wrapper = mock('foo')
self.assertEqual(wrapper.name, 'foo')

def test_spec_instance_in_constructor(self):
wrapper = mock().with_spec(self.SpecClass())
self.assertEqual(wrapper._children.keys(), ['a','b'])
Expand Down

0 comments on commit 352c395

Please sign in to comment.