Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 74 lines (57 sloc) 2.213 kB
74c474a @dcramer Improve handling of DoesNotExist and MultipleObjectsReturned cases. M…
authored
1 import mock
2
3
4 class SharedMock(mock.MagicMock):
3edb99a @slinkp Added some explanatory docstrings and comments.
slinkp authored
5
6 """
7 A MagicMock whose children are all itself.
8
9 >>> m = SharedMock()
10 >>> m is m.foo is m.bar is m.foo.bar.baz.qux
11 True
12 >>> m.foo.side_effect = ['hello from foo']
13 >>> m.bar()
14 'hello from foo'
15
16 'Magic' methods are not shared.
17 >>> m.__getitem__ is m.__len__
18 False
19
20 Neither are attributes you assign.
21 >>> m.explicitly_assigned_attribute = 1
22 >>> m.explicitly_assigned_attribute is m.foo
23 False
24
25 """
26
74c474a @dcramer Improve handling of DoesNotExist and MultipleObjectsReturned cases. M…
authored
27 def __init__(self, *args, **kwargs):
28 super(SharedMock, self).__init__(*args, **kwargs)
29 parent = mock.MagicMock()
30 parent.child = self
31 self.__parent = parent
32
33 def _get_child_mock(self, **kwargs):
34 name = kwargs.get('name', '')
35 if name[:2] == name[-2:] == '__':
36 return super(SharedMock, self)._get_child_mock(**kwargs)
37 return self
38
39 def __getattr__(self, name):
40 result = super(SharedMock, self).__getattr__(name)
41 if result is self:
42 result._mock_name = result._mock_new_name = name
43 return result
44
45 def assert_chain_calls(self, *calls):
46 """
47 Asserts that a chained method was called (parents in the chain do not
3edb99a @slinkp Added some explanatory docstrings and comments.
slinkp authored
48 matter, nor are they tracked). Use with `mock.call`.
49
50 >>> obj.filter(foo='bar').select_related('baz')
51 >>> obj.assert_chain_calls(mock.call.filter(foo='bar'))
52 >>> obj.assert_chain_calls(mock.call.select_related('baz'))
53 >>> obj.assert_chain_calls(mock.call.reverse())
54 *** AssertionError: [call.reverse()] not all found in call list, ...
74c474a @dcramer Improve handling of DoesNotExist and MultipleObjectsReturned cases. M…
authored
55
56 """
3edb99a @slinkp Added some explanatory docstrings and comments.
slinkp authored
57
74c474a @dcramer Improve handling of DoesNotExist and MultipleObjectsReturned cases. M…
authored
58 all_calls = self.__parent.mock_calls[:]
59
60 not_found = []
61 for kall in calls:
62 try:
63 all_calls.remove(kall)
64 except ValueError:
65 not_found.append(kall)
66 if not_found:
67 if self.__parent.mock_calls:
68 message = '%r not all found in call list, %d other(s) were:\n%r' % (not_found, len(self.__parent.mock_calls),
69 self.__parent.mock_calls)
70 else:
71 message = 'no calls were found'
72
73 raise AssertionError(message)
Something went wrong with that request. Please try again.