1 | n/a | # mock.py |
---|
2 | n/a | # Test tools for mocking and patching. |
---|
3 | n/a | # Maintained by Michael Foord |
---|
4 | n/a | # Backport for other versions of Python available from |
---|
5 | n/a | # http://pypi.python.org/pypi/mock |
---|
6 | n/a | |
---|
7 | n/a | __all__ = ( |
---|
8 | n/a | 'Mock', |
---|
9 | n/a | 'MagicMock', |
---|
10 | n/a | 'patch', |
---|
11 | n/a | 'sentinel', |
---|
12 | n/a | 'DEFAULT', |
---|
13 | n/a | 'ANY', |
---|
14 | n/a | 'call', |
---|
15 | n/a | 'create_autospec', |
---|
16 | n/a | 'FILTER_DIR', |
---|
17 | n/a | 'NonCallableMock', |
---|
18 | n/a | 'NonCallableMagicMock', |
---|
19 | n/a | 'mock_open', |
---|
20 | n/a | 'PropertyMock', |
---|
21 | n/a | ) |
---|
22 | n/a | |
---|
23 | n/a | |
---|
24 | n/a | __version__ = '1.0' |
---|
25 | n/a | |
---|
26 | n/a | |
---|
27 | n/a | import inspect |
---|
28 | n/a | import pprint |
---|
29 | n/a | import sys |
---|
30 | n/a | import builtins |
---|
31 | n/a | from types import ModuleType |
---|
32 | n/a | from functools import wraps, partial |
---|
33 | n/a | |
---|
34 | n/a | |
---|
35 | n/a | _builtins = {name for name in dir(builtins) if not name.startswith('_')} |
---|
36 | n/a | |
---|
37 | n/a | BaseExceptions = (BaseException,) |
---|
38 | n/a | if 'java' in sys.platform: |
---|
39 | n/a | # jython |
---|
40 | n/a | import java |
---|
41 | n/a | BaseExceptions = (BaseException, java.lang.Throwable) |
---|
42 | n/a | |
---|
43 | n/a | |
---|
44 | n/a | FILTER_DIR = True |
---|
45 | n/a | |
---|
46 | n/a | # Workaround for issue #12370 |
---|
47 | n/a | # Without this, the __class__ properties wouldn't be set correctly |
---|
48 | n/a | _safe_super = super |
---|
49 | n/a | |
---|
50 | n/a | def _is_instance_mock(obj): |
---|
51 | n/a | # can't use isinstance on Mock objects because they override __class__ |
---|
52 | n/a | # The base class for all mocks is NonCallableMock |
---|
53 | n/a | return issubclass(type(obj), NonCallableMock) |
---|
54 | n/a | |
---|
55 | n/a | |
---|
56 | n/a | def _is_exception(obj): |
---|
57 | n/a | return ( |
---|
58 | n/a | isinstance(obj, BaseExceptions) or |
---|
59 | n/a | isinstance(obj, type) and issubclass(obj, BaseExceptions) |
---|
60 | n/a | ) |
---|
61 | n/a | |
---|
62 | n/a | |
---|
63 | n/a | def _get_signature_object(func, as_instance, eat_self): |
---|
64 | n/a | """ |
---|
65 | n/a | Given an arbitrary, possibly callable object, try to create a suitable |
---|
66 | n/a | signature object. |
---|
67 | n/a | Return a (reduced func, signature) tuple, or None. |
---|
68 | n/a | """ |
---|
69 | n/a | if isinstance(func, type) and not as_instance: |
---|
70 | n/a | # If it's a type and should be modelled as a type, use __init__. |
---|
71 | n/a | try: |
---|
72 | n/a | func = func.__init__ |
---|
73 | n/a | except AttributeError: |
---|
74 | n/a | return None |
---|
75 | n/a | # Skip the `self` argument in __init__ |
---|
76 | n/a | eat_self = True |
---|
77 | n/a | elif not isinstance(func, FunctionTypes): |
---|
78 | n/a | # If we really want to model an instance of the passed type, |
---|
79 | n/a | # __call__ should be looked up, not __init__. |
---|
80 | n/a | try: |
---|
81 | n/a | func = func.__call__ |
---|
82 | n/a | except AttributeError: |
---|
83 | n/a | return None |
---|
84 | n/a | if eat_self: |
---|
85 | n/a | sig_func = partial(func, None) |
---|
86 | n/a | else: |
---|
87 | n/a | sig_func = func |
---|
88 | n/a | try: |
---|
89 | n/a | return func, inspect.signature(sig_func) |
---|
90 | n/a | except ValueError: |
---|
91 | n/a | # Certain callable types are not supported by inspect.signature() |
---|
92 | n/a | return None |
---|
93 | n/a | |
---|
94 | n/a | |
---|
95 | n/a | def _check_signature(func, mock, skipfirst, instance=False): |
---|
96 | n/a | sig = _get_signature_object(func, instance, skipfirst) |
---|
97 | n/a | if sig is None: |
---|
98 | n/a | return |
---|
99 | n/a | func, sig = sig |
---|
100 | n/a | def checksig(_mock_self, *args, **kwargs): |
---|
101 | n/a | sig.bind(*args, **kwargs) |
---|
102 | n/a | _copy_func_details(func, checksig) |
---|
103 | n/a | type(mock)._mock_check_sig = checksig |
---|
104 | n/a | |
---|
105 | n/a | |
---|
106 | n/a | def _copy_func_details(func, funcopy): |
---|
107 | n/a | # we explicitly don't copy func.__dict__ into this copy as it would |
---|
108 | n/a | # expose original attributes that should be mocked |
---|
109 | n/a | for attribute in ( |
---|
110 | n/a | '__name__', '__doc__', '__text_signature__', |
---|
111 | n/a | '__module__', '__defaults__', '__kwdefaults__', |
---|
112 | n/a | ): |
---|
113 | n/a | try: |
---|
114 | n/a | setattr(funcopy, attribute, getattr(func, attribute)) |
---|
115 | n/a | except AttributeError: |
---|
116 | n/a | pass |
---|
117 | n/a | |
---|
118 | n/a | |
---|
119 | n/a | def _callable(obj): |
---|
120 | n/a | if isinstance(obj, type): |
---|
121 | n/a | return True |
---|
122 | n/a | if getattr(obj, '__call__', None) is not None: |
---|
123 | n/a | return True |
---|
124 | n/a | return False |
---|
125 | n/a | |
---|
126 | n/a | |
---|
127 | n/a | def _is_list(obj): |
---|
128 | n/a | # checks for list or tuples |
---|
129 | n/a | # XXXX badly named! |
---|
130 | n/a | return type(obj) in (list, tuple) |
---|
131 | n/a | |
---|
132 | n/a | |
---|
133 | n/a | def _instance_callable(obj): |
---|
134 | n/a | """Given an object, return True if the object is callable. |
---|
135 | n/a | For classes, return True if instances would be callable.""" |
---|
136 | n/a | if not isinstance(obj, type): |
---|
137 | n/a | # already an instance |
---|
138 | n/a | return getattr(obj, '__call__', None) is not None |
---|
139 | n/a | |
---|
140 | n/a | # *could* be broken by a class overriding __mro__ or __dict__ via |
---|
141 | n/a | # a metaclass |
---|
142 | n/a | for base in (obj,) + obj.__mro__: |
---|
143 | n/a | if base.__dict__.get('__call__') is not None: |
---|
144 | n/a | return True |
---|
145 | n/a | return False |
---|
146 | n/a | |
---|
147 | n/a | |
---|
148 | n/a | def _set_signature(mock, original, instance=False): |
---|
149 | n/a | # creates a function with signature (*args, **kwargs) that delegates to a |
---|
150 | n/a | # mock. It still does signature checking by calling a lambda with the same |
---|
151 | n/a | # signature as the original. |
---|
152 | n/a | if not _callable(original): |
---|
153 | n/a | return |
---|
154 | n/a | |
---|
155 | n/a | skipfirst = isinstance(original, type) |
---|
156 | n/a | result = _get_signature_object(original, instance, skipfirst) |
---|
157 | n/a | if result is None: |
---|
158 | n/a | return |
---|
159 | n/a | func, sig = result |
---|
160 | n/a | def checksig(*args, **kwargs): |
---|
161 | n/a | sig.bind(*args, **kwargs) |
---|
162 | n/a | _copy_func_details(func, checksig) |
---|
163 | n/a | |
---|
164 | n/a | name = original.__name__ |
---|
165 | n/a | if not name.isidentifier(): |
---|
166 | n/a | name = 'funcopy' |
---|
167 | n/a | context = {'_checksig_': checksig, 'mock': mock} |
---|
168 | n/a | src = """def %s(*args, **kwargs): |
---|
169 | n/a | _checksig_(*args, **kwargs) |
---|
170 | n/a | return mock(*args, **kwargs)""" % name |
---|
171 | n/a | exec (src, context) |
---|
172 | n/a | funcopy = context[name] |
---|
173 | n/a | _setup_func(funcopy, mock) |
---|
174 | n/a | return funcopy |
---|
175 | n/a | |
---|
176 | n/a | |
---|
177 | n/a | def _setup_func(funcopy, mock): |
---|
178 | n/a | funcopy.mock = mock |
---|
179 | n/a | |
---|
180 | n/a | # can't use isinstance with mocks |
---|
181 | n/a | if not _is_instance_mock(mock): |
---|
182 | n/a | return |
---|
183 | n/a | |
---|
184 | n/a | def assert_called_with(*args, **kwargs): |
---|
185 | n/a | return mock.assert_called_with(*args, **kwargs) |
---|
186 | n/a | def assert_called(*args, **kwargs): |
---|
187 | n/a | return mock.assert_called(*args, **kwargs) |
---|
188 | n/a | def assert_not_called(*args, **kwargs): |
---|
189 | n/a | return mock.assert_not_called(*args, **kwargs) |
---|
190 | n/a | def assert_called_once(*args, **kwargs): |
---|
191 | n/a | return mock.assert_called_once(*args, **kwargs) |
---|
192 | n/a | def assert_called_once_with(*args, **kwargs): |
---|
193 | n/a | return mock.assert_called_once_with(*args, **kwargs) |
---|
194 | n/a | def assert_has_calls(*args, **kwargs): |
---|
195 | n/a | return mock.assert_has_calls(*args, **kwargs) |
---|
196 | n/a | def assert_any_call(*args, **kwargs): |
---|
197 | n/a | return mock.assert_any_call(*args, **kwargs) |
---|
198 | n/a | def reset_mock(): |
---|
199 | n/a | funcopy.method_calls = _CallList() |
---|
200 | n/a | funcopy.mock_calls = _CallList() |
---|
201 | n/a | mock.reset_mock() |
---|
202 | n/a | ret = funcopy.return_value |
---|
203 | n/a | if _is_instance_mock(ret) and not ret is mock: |
---|
204 | n/a | ret.reset_mock() |
---|
205 | n/a | |
---|
206 | n/a | funcopy.called = False |
---|
207 | n/a | funcopy.call_count = 0 |
---|
208 | n/a | funcopy.call_args = None |
---|
209 | n/a | funcopy.call_args_list = _CallList() |
---|
210 | n/a | funcopy.method_calls = _CallList() |
---|
211 | n/a | funcopy.mock_calls = _CallList() |
---|
212 | n/a | |
---|
213 | n/a | funcopy.return_value = mock.return_value |
---|
214 | n/a | funcopy.side_effect = mock.side_effect |
---|
215 | n/a | funcopy._mock_children = mock._mock_children |
---|
216 | n/a | |
---|
217 | n/a | funcopy.assert_called_with = assert_called_with |
---|
218 | n/a | funcopy.assert_called_once_with = assert_called_once_with |
---|
219 | n/a | funcopy.assert_has_calls = assert_has_calls |
---|
220 | n/a | funcopy.assert_any_call = assert_any_call |
---|
221 | n/a | funcopy.reset_mock = reset_mock |
---|
222 | n/a | funcopy.assert_called = assert_called |
---|
223 | n/a | funcopy.assert_not_called = assert_not_called |
---|
224 | n/a | funcopy.assert_called_once = assert_called_once |
---|
225 | n/a | |
---|
226 | n/a | mock._mock_delegate = funcopy |
---|
227 | n/a | |
---|
228 | n/a | |
---|
229 | n/a | def _is_magic(name): |
---|
230 | n/a | return '__%s__' % name[2:-2] == name |
---|
231 | n/a | |
---|
232 | n/a | |
---|
233 | n/a | class _SentinelObject(object): |
---|
234 | n/a | "A unique, named, sentinel object." |
---|
235 | n/a | def __init__(self, name): |
---|
236 | n/a | self.name = name |
---|
237 | n/a | |
---|
238 | n/a | def __repr__(self): |
---|
239 | n/a | return 'sentinel.%s' % self.name |
---|
240 | n/a | |
---|
241 | n/a | def __reduce__(self): |
---|
242 | n/a | return 'sentinel.%s' % self.name |
---|
243 | n/a | |
---|
244 | n/a | |
---|
245 | n/a | class _Sentinel(object): |
---|
246 | n/a | """Access attributes to return a named object, usable as a sentinel.""" |
---|
247 | n/a | def __init__(self): |
---|
248 | n/a | self._sentinels = {} |
---|
249 | n/a | |
---|
250 | n/a | def __getattr__(self, name): |
---|
251 | n/a | if name == '__bases__': |
---|
252 | n/a | # Without this help(unittest.mock) raises an exception |
---|
253 | n/a | raise AttributeError |
---|
254 | n/a | return self._sentinels.setdefault(name, _SentinelObject(name)) |
---|
255 | n/a | |
---|
256 | n/a | def __reduce__(self): |
---|
257 | n/a | return 'sentinel' |
---|
258 | n/a | |
---|
259 | n/a | |
---|
260 | n/a | sentinel = _Sentinel() |
---|
261 | n/a | |
---|
262 | n/a | DEFAULT = sentinel.DEFAULT |
---|
263 | n/a | _missing = sentinel.MISSING |
---|
264 | n/a | _deleted = sentinel.DELETED |
---|
265 | n/a | |
---|
266 | n/a | |
---|
267 | n/a | def _copy(value): |
---|
268 | n/a | if type(value) in (dict, list, tuple, set): |
---|
269 | n/a | return type(value)(value) |
---|
270 | n/a | return value |
---|
271 | n/a | |
---|
272 | n/a | |
---|
273 | n/a | _allowed_names = { |
---|
274 | n/a | 'return_value', '_mock_return_value', 'side_effect', |
---|
275 | n/a | '_mock_side_effect', '_mock_parent', '_mock_new_parent', |
---|
276 | n/a | '_mock_name', '_mock_new_name' |
---|
277 | n/a | } |
---|
278 | n/a | |
---|
279 | n/a | |
---|
280 | n/a | def _delegating_property(name): |
---|
281 | n/a | _allowed_names.add(name) |
---|
282 | n/a | _the_name = '_mock_' + name |
---|
283 | n/a | def _get(self, name=name, _the_name=_the_name): |
---|
284 | n/a | sig = self._mock_delegate |
---|
285 | n/a | if sig is None: |
---|
286 | n/a | return getattr(self, _the_name) |
---|
287 | n/a | return getattr(sig, name) |
---|
288 | n/a | def _set(self, value, name=name, _the_name=_the_name): |
---|
289 | n/a | sig = self._mock_delegate |
---|
290 | n/a | if sig is None: |
---|
291 | n/a | self.__dict__[_the_name] = value |
---|
292 | n/a | else: |
---|
293 | n/a | setattr(sig, name, value) |
---|
294 | n/a | |
---|
295 | n/a | return property(_get, _set) |
---|
296 | n/a | |
---|
297 | n/a | |
---|
298 | n/a | |
---|
299 | n/a | class _CallList(list): |
---|
300 | n/a | |
---|
301 | n/a | def __contains__(self, value): |
---|
302 | n/a | if not isinstance(value, list): |
---|
303 | n/a | return list.__contains__(self, value) |
---|
304 | n/a | len_value = len(value) |
---|
305 | n/a | len_self = len(self) |
---|
306 | n/a | if len_value > len_self: |
---|
307 | n/a | return False |
---|
308 | n/a | |
---|
309 | n/a | for i in range(0, len_self - len_value + 1): |
---|
310 | n/a | sub_list = self[i:i+len_value] |
---|
311 | n/a | if sub_list == value: |
---|
312 | n/a | return True |
---|
313 | n/a | return False |
---|
314 | n/a | |
---|
315 | n/a | def __repr__(self): |
---|
316 | n/a | return pprint.pformat(list(self)) |
---|
317 | n/a | |
---|
318 | n/a | |
---|
319 | n/a | def _check_and_set_parent(parent, value, name, new_name): |
---|
320 | n/a | if not _is_instance_mock(value): |
---|
321 | n/a | return False |
---|
322 | n/a | if ((value._mock_name or value._mock_new_name) or |
---|
323 | n/a | (value._mock_parent is not None) or |
---|
324 | n/a | (value._mock_new_parent is not None)): |
---|
325 | n/a | return False |
---|
326 | n/a | |
---|
327 | n/a | _parent = parent |
---|
328 | n/a | while _parent is not None: |
---|
329 | n/a | # setting a mock (value) as a child or return value of itself |
---|
330 | n/a | # should not modify the mock |
---|
331 | n/a | if _parent is value: |
---|
332 | n/a | return False |
---|
333 | n/a | _parent = _parent._mock_new_parent |
---|
334 | n/a | |
---|
335 | n/a | if new_name: |
---|
336 | n/a | value._mock_new_parent = parent |
---|
337 | n/a | value._mock_new_name = new_name |
---|
338 | n/a | if name: |
---|
339 | n/a | value._mock_parent = parent |
---|
340 | n/a | value._mock_name = name |
---|
341 | n/a | return True |
---|
342 | n/a | |
---|
343 | n/a | # Internal class to identify if we wrapped an iterator object or not. |
---|
344 | n/a | class _MockIter(object): |
---|
345 | n/a | def __init__(self, obj): |
---|
346 | n/a | self.obj = iter(obj) |
---|
347 | n/a | def __iter__(self): |
---|
348 | n/a | return self |
---|
349 | n/a | def __next__(self): |
---|
350 | n/a | return next(self.obj) |
---|
351 | n/a | |
---|
352 | n/a | class Base(object): |
---|
353 | n/a | _mock_return_value = DEFAULT |
---|
354 | n/a | _mock_side_effect = None |
---|
355 | n/a | def __init__(self, *args, **kwargs): |
---|
356 | n/a | pass |
---|
357 | n/a | |
---|
358 | n/a | |
---|
359 | n/a | |
---|
360 | n/a | class NonCallableMock(Base): |
---|
361 | n/a | """A non-callable version of `Mock`""" |
---|
362 | n/a | |
---|
363 | n/a | def __new__(cls, *args, **kw): |
---|
364 | n/a | # every instance has its own class |
---|
365 | n/a | # so we can create magic methods on the |
---|
366 | n/a | # class without stomping on other mocks |
---|
367 | n/a | new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__}) |
---|
368 | n/a | instance = object.__new__(new) |
---|
369 | n/a | return instance |
---|
370 | n/a | |
---|
371 | n/a | |
---|
372 | n/a | def __init__( |
---|
373 | n/a | self, spec=None, wraps=None, name=None, spec_set=None, |
---|
374 | n/a | parent=None, _spec_state=None, _new_name='', _new_parent=None, |
---|
375 | n/a | _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs |
---|
376 | n/a | ): |
---|
377 | n/a | if _new_parent is None: |
---|
378 | n/a | _new_parent = parent |
---|
379 | n/a | |
---|
380 | n/a | __dict__ = self.__dict__ |
---|
381 | n/a | __dict__['_mock_parent'] = parent |
---|
382 | n/a | __dict__['_mock_name'] = name |
---|
383 | n/a | __dict__['_mock_new_name'] = _new_name |
---|
384 | n/a | __dict__['_mock_new_parent'] = _new_parent |
---|
385 | n/a | |
---|
386 | n/a | if spec_set is not None: |
---|
387 | n/a | spec = spec_set |
---|
388 | n/a | spec_set = True |
---|
389 | n/a | if _eat_self is None: |
---|
390 | n/a | _eat_self = parent is not None |
---|
391 | n/a | |
---|
392 | n/a | self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self) |
---|
393 | n/a | |
---|
394 | n/a | __dict__['_mock_children'] = {} |
---|
395 | n/a | __dict__['_mock_wraps'] = wraps |
---|
396 | n/a | __dict__['_mock_delegate'] = None |
---|
397 | n/a | |
---|
398 | n/a | __dict__['_mock_called'] = False |
---|
399 | n/a | __dict__['_mock_call_args'] = None |
---|
400 | n/a | __dict__['_mock_call_count'] = 0 |
---|
401 | n/a | __dict__['_mock_call_args_list'] = _CallList() |
---|
402 | n/a | __dict__['_mock_mock_calls'] = _CallList() |
---|
403 | n/a | |
---|
404 | n/a | __dict__['method_calls'] = _CallList() |
---|
405 | n/a | __dict__['_mock_unsafe'] = unsafe |
---|
406 | n/a | |
---|
407 | n/a | if kwargs: |
---|
408 | n/a | self.configure_mock(**kwargs) |
---|
409 | n/a | |
---|
410 | n/a | _safe_super(NonCallableMock, self).__init__( |
---|
411 | n/a | spec, wraps, name, spec_set, parent, |
---|
412 | n/a | _spec_state |
---|
413 | n/a | ) |
---|
414 | n/a | |
---|
415 | n/a | |
---|
416 | n/a | def attach_mock(self, mock, attribute): |
---|
417 | n/a | """ |
---|
418 | n/a | Attach a mock as an attribute of this one, replacing its name and |
---|
419 | n/a | parent. Calls to the attached mock will be recorded in the |
---|
420 | n/a | `method_calls` and `mock_calls` attributes of this one.""" |
---|
421 | n/a | mock._mock_parent = None |
---|
422 | n/a | mock._mock_new_parent = None |
---|
423 | n/a | mock._mock_name = '' |
---|
424 | n/a | mock._mock_new_name = None |
---|
425 | n/a | |
---|
426 | n/a | setattr(self, attribute, mock) |
---|
427 | n/a | |
---|
428 | n/a | |
---|
429 | n/a | def mock_add_spec(self, spec, spec_set=False): |
---|
430 | n/a | """Add a spec to a mock. `spec` can either be an object or a |
---|
431 | n/a | list of strings. Only attributes on the `spec` can be fetched as |
---|
432 | n/a | attributes from the mock. |
---|
433 | n/a | |
---|
434 | n/a | If `spec_set` is True then only attributes on the spec can be set.""" |
---|
435 | n/a | self._mock_add_spec(spec, spec_set) |
---|
436 | n/a | |
---|
437 | n/a | |
---|
438 | n/a | def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False, |
---|
439 | n/a | _eat_self=False): |
---|
440 | n/a | _spec_class = None |
---|
441 | n/a | _spec_signature = None |
---|
442 | n/a | |
---|
443 | n/a | if spec is not None and not _is_list(spec): |
---|
444 | n/a | if isinstance(spec, type): |
---|
445 | n/a | _spec_class = spec |
---|
446 | n/a | else: |
---|
447 | n/a | _spec_class = _get_class(spec) |
---|
448 | n/a | res = _get_signature_object(spec, |
---|
449 | n/a | _spec_as_instance, _eat_self) |
---|
450 | n/a | _spec_signature = res and res[1] |
---|
451 | n/a | |
---|
452 | n/a | spec = dir(spec) |
---|
453 | n/a | |
---|
454 | n/a | __dict__ = self.__dict__ |
---|
455 | n/a | __dict__['_spec_class'] = _spec_class |
---|
456 | n/a | __dict__['_spec_set'] = spec_set |
---|
457 | n/a | __dict__['_spec_signature'] = _spec_signature |
---|
458 | n/a | __dict__['_mock_methods'] = spec |
---|
459 | n/a | |
---|
460 | n/a | |
---|
461 | n/a | def __get_return_value(self): |
---|
462 | n/a | ret = self._mock_return_value |
---|
463 | n/a | if self._mock_delegate is not None: |
---|
464 | n/a | ret = self._mock_delegate.return_value |
---|
465 | n/a | |
---|
466 | n/a | if ret is DEFAULT: |
---|
467 | n/a | ret = self._get_child_mock( |
---|
468 | n/a | _new_parent=self, _new_name='()' |
---|
469 | n/a | ) |
---|
470 | n/a | self.return_value = ret |
---|
471 | n/a | return ret |
---|
472 | n/a | |
---|
473 | n/a | |
---|
474 | n/a | def __set_return_value(self, value): |
---|
475 | n/a | if self._mock_delegate is not None: |
---|
476 | n/a | self._mock_delegate.return_value = value |
---|
477 | n/a | else: |
---|
478 | n/a | self._mock_return_value = value |
---|
479 | n/a | _check_and_set_parent(self, value, None, '()') |
---|
480 | n/a | |
---|
481 | n/a | __return_value_doc = "The value to be returned when the mock is called." |
---|
482 | n/a | return_value = property(__get_return_value, __set_return_value, |
---|
483 | n/a | __return_value_doc) |
---|
484 | n/a | |
---|
485 | n/a | |
---|
486 | n/a | @property |
---|
487 | n/a | def __class__(self): |
---|
488 | n/a | if self._spec_class is None: |
---|
489 | n/a | return type(self) |
---|
490 | n/a | return self._spec_class |
---|
491 | n/a | |
---|
492 | n/a | called = _delegating_property('called') |
---|
493 | n/a | call_count = _delegating_property('call_count') |
---|
494 | n/a | call_args = _delegating_property('call_args') |
---|
495 | n/a | call_args_list = _delegating_property('call_args_list') |
---|
496 | n/a | mock_calls = _delegating_property('mock_calls') |
---|
497 | n/a | |
---|
498 | n/a | |
---|
499 | n/a | def __get_side_effect(self): |
---|
500 | n/a | delegated = self._mock_delegate |
---|
501 | n/a | if delegated is None: |
---|
502 | n/a | return self._mock_side_effect |
---|
503 | n/a | sf = delegated.side_effect |
---|
504 | n/a | if (sf is not None and not callable(sf) |
---|
505 | n/a | and not isinstance(sf, _MockIter) and not _is_exception(sf)): |
---|
506 | n/a | sf = _MockIter(sf) |
---|
507 | n/a | delegated.side_effect = sf |
---|
508 | n/a | return sf |
---|
509 | n/a | |
---|
510 | n/a | def __set_side_effect(self, value): |
---|
511 | n/a | value = _try_iter(value) |
---|
512 | n/a | delegated = self._mock_delegate |
---|
513 | n/a | if delegated is None: |
---|
514 | n/a | self._mock_side_effect = value |
---|
515 | n/a | else: |
---|
516 | n/a | delegated.side_effect = value |
---|
517 | n/a | |
---|
518 | n/a | side_effect = property(__get_side_effect, __set_side_effect) |
---|
519 | n/a | |
---|
520 | n/a | |
---|
521 | n/a | def reset_mock(self, visited=None,*, return_value=False, side_effect=False): |
---|
522 | n/a | "Restore the mock object to its initial state." |
---|
523 | n/a | if visited is None: |
---|
524 | n/a | visited = [] |
---|
525 | n/a | if id(self) in visited: |
---|
526 | n/a | return |
---|
527 | n/a | visited.append(id(self)) |
---|
528 | n/a | |
---|
529 | n/a | self.called = False |
---|
530 | n/a | self.call_args = None |
---|
531 | n/a | self.call_count = 0 |
---|
532 | n/a | self.mock_calls = _CallList() |
---|
533 | n/a | self.call_args_list = _CallList() |
---|
534 | n/a | self.method_calls = _CallList() |
---|
535 | n/a | |
---|
536 | n/a | if return_value: |
---|
537 | n/a | self._mock_return_value = DEFAULT |
---|
538 | n/a | if side_effect: |
---|
539 | n/a | self._mock_side_effect = None |
---|
540 | n/a | |
---|
541 | n/a | for child in self._mock_children.values(): |
---|
542 | n/a | if isinstance(child, _SpecState): |
---|
543 | n/a | continue |
---|
544 | n/a | child.reset_mock(visited) |
---|
545 | n/a | |
---|
546 | n/a | ret = self._mock_return_value |
---|
547 | n/a | if _is_instance_mock(ret) and ret is not self: |
---|
548 | n/a | ret.reset_mock(visited) |
---|
549 | n/a | |
---|
550 | n/a | |
---|
551 | n/a | def configure_mock(self, **kwargs): |
---|
552 | n/a | """Set attributes on the mock through keyword arguments. |
---|
553 | n/a | |
---|
554 | n/a | Attributes plus return values and side effects can be set on child |
---|
555 | n/a | mocks using standard dot notation and unpacking a dictionary in the |
---|
556 | n/a | method call: |
---|
557 | n/a | |
---|
558 | n/a | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
---|
559 | n/a | >>> mock.configure_mock(**attrs)""" |
---|
560 | n/a | for arg, val in sorted(kwargs.items(), |
---|
561 | n/a | # we sort on the number of dots so that |
---|
562 | n/a | # attributes are set before we set attributes on |
---|
563 | n/a | # attributes |
---|
564 | n/a | key=lambda entry: entry[0].count('.')): |
---|
565 | n/a | args = arg.split('.') |
---|
566 | n/a | final = args.pop() |
---|
567 | n/a | obj = self |
---|
568 | n/a | for entry in args: |
---|
569 | n/a | obj = getattr(obj, entry) |
---|
570 | n/a | setattr(obj, final, val) |
---|
571 | n/a | |
---|
572 | n/a | |
---|
573 | n/a | def __getattr__(self, name): |
---|
574 | n/a | if name in {'_mock_methods', '_mock_unsafe'}: |
---|
575 | n/a | raise AttributeError(name) |
---|
576 | n/a | elif self._mock_methods is not None: |
---|
577 | n/a | if name not in self._mock_methods or name in _all_magics: |
---|
578 | n/a | raise AttributeError("Mock object has no attribute %r" % name) |
---|
579 | n/a | elif _is_magic(name): |
---|
580 | n/a | raise AttributeError(name) |
---|
581 | n/a | if not self._mock_unsafe: |
---|
582 | n/a | if name.startswith(('assert', 'assret')): |
---|
583 | n/a | raise AttributeError(name) |
---|
584 | n/a | |
---|
585 | n/a | result = self._mock_children.get(name) |
---|
586 | n/a | if result is _deleted: |
---|
587 | n/a | raise AttributeError(name) |
---|
588 | n/a | elif result is None: |
---|
589 | n/a | wraps = None |
---|
590 | n/a | if self._mock_wraps is not None: |
---|
591 | n/a | # XXXX should we get the attribute without triggering code |
---|
592 | n/a | # execution? |
---|
593 | n/a | wraps = getattr(self._mock_wraps, name) |
---|
594 | n/a | |
---|
595 | n/a | result = self._get_child_mock( |
---|
596 | n/a | parent=self, name=name, wraps=wraps, _new_name=name, |
---|
597 | n/a | _new_parent=self |
---|
598 | n/a | ) |
---|
599 | n/a | self._mock_children[name] = result |
---|
600 | n/a | |
---|
601 | n/a | elif isinstance(result, _SpecState): |
---|
602 | n/a | result = create_autospec( |
---|
603 | n/a | result.spec, result.spec_set, result.instance, |
---|
604 | n/a | result.parent, result.name |
---|
605 | n/a | ) |
---|
606 | n/a | self._mock_children[name] = result |
---|
607 | n/a | |
---|
608 | n/a | return result |
---|
609 | n/a | |
---|
610 | n/a | |
---|
611 | n/a | def __repr__(self): |
---|
612 | n/a | _name_list = [self._mock_new_name] |
---|
613 | n/a | _parent = self._mock_new_parent |
---|
614 | n/a | last = self |
---|
615 | n/a | |
---|
616 | n/a | dot = '.' |
---|
617 | n/a | if _name_list == ['()']: |
---|
618 | n/a | dot = '' |
---|
619 | n/a | seen = set() |
---|
620 | n/a | while _parent is not None: |
---|
621 | n/a | last = _parent |
---|
622 | n/a | |
---|
623 | n/a | _name_list.append(_parent._mock_new_name + dot) |
---|
624 | n/a | dot = '.' |
---|
625 | n/a | if _parent._mock_new_name == '()': |
---|
626 | n/a | dot = '' |
---|
627 | n/a | |
---|
628 | n/a | _parent = _parent._mock_new_parent |
---|
629 | n/a | |
---|
630 | n/a | # use ids here so as not to call __hash__ on the mocks |
---|
631 | n/a | if id(_parent) in seen: |
---|
632 | n/a | break |
---|
633 | n/a | seen.add(id(_parent)) |
---|
634 | n/a | |
---|
635 | n/a | _name_list = list(reversed(_name_list)) |
---|
636 | n/a | _first = last._mock_name or 'mock' |
---|
637 | n/a | if len(_name_list) > 1: |
---|
638 | n/a | if _name_list[1] not in ('()', '().'): |
---|
639 | n/a | _first += '.' |
---|
640 | n/a | _name_list[0] = _first |
---|
641 | n/a | name = ''.join(_name_list) |
---|
642 | n/a | |
---|
643 | n/a | name_string = '' |
---|
644 | n/a | if name not in ('mock', 'mock.'): |
---|
645 | n/a | name_string = ' name=%r' % name |
---|
646 | n/a | |
---|
647 | n/a | spec_string = '' |
---|
648 | n/a | if self._spec_class is not None: |
---|
649 | n/a | spec_string = ' spec=%r' |
---|
650 | n/a | if self._spec_set: |
---|
651 | n/a | spec_string = ' spec_set=%r' |
---|
652 | n/a | spec_string = spec_string % self._spec_class.__name__ |
---|
653 | n/a | return "<%s%s%s id='%s'>" % ( |
---|
654 | n/a | type(self).__name__, |
---|
655 | n/a | name_string, |
---|
656 | n/a | spec_string, |
---|
657 | n/a | id(self) |
---|
658 | n/a | ) |
---|
659 | n/a | |
---|
660 | n/a | |
---|
661 | n/a | def __dir__(self): |
---|
662 | n/a | """Filter the output of `dir(mock)` to only useful members.""" |
---|
663 | n/a | if not FILTER_DIR: |
---|
664 | n/a | return object.__dir__(self) |
---|
665 | n/a | |
---|
666 | n/a | extras = self._mock_methods or [] |
---|
667 | n/a | from_type = dir(type(self)) |
---|
668 | n/a | from_dict = list(self.__dict__) |
---|
669 | n/a | |
---|
670 | n/a | from_type = [e for e in from_type if not e.startswith('_')] |
---|
671 | n/a | from_dict = [e for e in from_dict if not e.startswith('_') or |
---|
672 | n/a | _is_magic(e)] |
---|
673 | n/a | return sorted(set(extras + from_type + from_dict + |
---|
674 | n/a | list(self._mock_children))) |
---|
675 | n/a | |
---|
676 | n/a | |
---|
677 | n/a | def __setattr__(self, name, value): |
---|
678 | n/a | if name in _allowed_names: |
---|
679 | n/a | # property setters go through here |
---|
680 | n/a | return object.__setattr__(self, name, value) |
---|
681 | n/a | elif (self._spec_set and self._mock_methods is not None and |
---|
682 | n/a | name not in self._mock_methods and |
---|
683 | n/a | name not in self.__dict__): |
---|
684 | n/a | raise AttributeError("Mock object has no attribute '%s'" % name) |
---|
685 | n/a | elif name in _unsupported_magics: |
---|
686 | n/a | msg = 'Attempting to set unsupported magic method %r.' % name |
---|
687 | n/a | raise AttributeError(msg) |
---|
688 | n/a | elif name in _all_magics: |
---|
689 | n/a | if self._mock_methods is not None and name not in self._mock_methods: |
---|
690 | n/a | raise AttributeError("Mock object has no attribute '%s'" % name) |
---|
691 | n/a | |
---|
692 | n/a | if not _is_instance_mock(value): |
---|
693 | n/a | setattr(type(self), name, _get_method(name, value)) |
---|
694 | n/a | original = value |
---|
695 | n/a | value = lambda *args, **kw: original(self, *args, **kw) |
---|
696 | n/a | else: |
---|
697 | n/a | # only set _new_name and not name so that mock_calls is tracked |
---|
698 | n/a | # but not method calls |
---|
699 | n/a | _check_and_set_parent(self, value, None, name) |
---|
700 | n/a | setattr(type(self), name, value) |
---|
701 | n/a | self._mock_children[name] = value |
---|
702 | n/a | elif name == '__class__': |
---|
703 | n/a | self._spec_class = value |
---|
704 | n/a | return |
---|
705 | n/a | else: |
---|
706 | n/a | if _check_and_set_parent(self, value, name, name): |
---|
707 | n/a | self._mock_children[name] = value |
---|
708 | n/a | return object.__setattr__(self, name, value) |
---|
709 | n/a | |
---|
710 | n/a | |
---|
711 | n/a | def __delattr__(self, name): |
---|
712 | n/a | if name in _all_magics and name in type(self).__dict__: |
---|
713 | n/a | delattr(type(self), name) |
---|
714 | n/a | if name not in self.__dict__: |
---|
715 | n/a | # for magic methods that are still MagicProxy objects and |
---|
716 | n/a | # not set on the instance itself |
---|
717 | n/a | return |
---|
718 | n/a | |
---|
719 | n/a | if name in self.__dict__: |
---|
720 | n/a | object.__delattr__(self, name) |
---|
721 | n/a | |
---|
722 | n/a | obj = self._mock_children.get(name, _missing) |
---|
723 | n/a | if obj is _deleted: |
---|
724 | n/a | raise AttributeError(name) |
---|
725 | n/a | if obj is not _missing: |
---|
726 | n/a | del self._mock_children[name] |
---|
727 | n/a | self._mock_children[name] = _deleted |
---|
728 | n/a | |
---|
729 | n/a | |
---|
730 | n/a | def _format_mock_call_signature(self, args, kwargs): |
---|
731 | n/a | name = self._mock_name or 'mock' |
---|
732 | n/a | return _format_call_signature(name, args, kwargs) |
---|
733 | n/a | |
---|
734 | n/a | |
---|
735 | n/a | def _format_mock_failure_message(self, args, kwargs): |
---|
736 | n/a | message = 'Expected call: %s\nActual call: %s' |
---|
737 | n/a | expected_string = self._format_mock_call_signature(args, kwargs) |
---|
738 | n/a | call_args = self.call_args |
---|
739 | n/a | if len(call_args) == 3: |
---|
740 | n/a | call_args = call_args[1:] |
---|
741 | n/a | actual_string = self._format_mock_call_signature(*call_args) |
---|
742 | n/a | return message % (expected_string, actual_string) |
---|
743 | n/a | |
---|
744 | n/a | |
---|
745 | n/a | def _call_matcher(self, _call): |
---|
746 | n/a | """ |
---|
747 | n/a | Given a call (or simply an (args, kwargs) tuple), return a |
---|
748 | n/a | comparison key suitable for matching with other calls. |
---|
749 | n/a | This is a best effort method which relies on the spec's signature, |
---|
750 | n/a | if available, or falls back on the arguments themselves. |
---|
751 | n/a | """ |
---|
752 | n/a | sig = self._spec_signature |
---|
753 | n/a | if sig is not None: |
---|
754 | n/a | if len(_call) == 2: |
---|
755 | n/a | name = '' |
---|
756 | n/a | args, kwargs = _call |
---|
757 | n/a | else: |
---|
758 | n/a | name, args, kwargs = _call |
---|
759 | n/a | try: |
---|
760 | n/a | return name, sig.bind(*args, **kwargs) |
---|
761 | n/a | except TypeError as e: |
---|
762 | n/a | return e.with_traceback(None) |
---|
763 | n/a | else: |
---|
764 | n/a | return _call |
---|
765 | n/a | |
---|
766 | n/a | def assert_not_called(_mock_self): |
---|
767 | n/a | """assert that the mock was never called. |
---|
768 | n/a | """ |
---|
769 | n/a | self = _mock_self |
---|
770 | n/a | if self.call_count != 0: |
---|
771 | n/a | msg = ("Expected '%s' to not have been called. Called %s times." % |
---|
772 | n/a | (self._mock_name or 'mock', self.call_count)) |
---|
773 | n/a | raise AssertionError(msg) |
---|
774 | n/a | |
---|
775 | n/a | def assert_called(_mock_self): |
---|
776 | n/a | """assert that the mock was called at least once |
---|
777 | n/a | """ |
---|
778 | n/a | self = _mock_self |
---|
779 | n/a | if self.call_count == 0: |
---|
780 | n/a | msg = ("Expected '%s' to have been called." % |
---|
781 | n/a | self._mock_name or 'mock') |
---|
782 | n/a | raise AssertionError(msg) |
---|
783 | n/a | |
---|
784 | n/a | def assert_called_once(_mock_self): |
---|
785 | n/a | """assert that the mock was called only once. |
---|
786 | n/a | """ |
---|
787 | n/a | self = _mock_self |
---|
788 | n/a | if not self.call_count == 1: |
---|
789 | n/a | msg = ("Expected '%s' to have been called once. Called %s times." % |
---|
790 | n/a | (self._mock_name or 'mock', self.call_count)) |
---|
791 | n/a | raise AssertionError(msg) |
---|
792 | n/a | |
---|
793 | n/a | def assert_called_with(_mock_self, *args, **kwargs): |
---|
794 | n/a | """assert that the mock was called with the specified arguments. |
---|
795 | n/a | |
---|
796 | n/a | Raises an AssertionError if the args and keyword args passed in are |
---|
797 | n/a | different to the last call to the mock.""" |
---|
798 | n/a | self = _mock_self |
---|
799 | n/a | if self.call_args is None: |
---|
800 | n/a | expected = self._format_mock_call_signature(args, kwargs) |
---|
801 | n/a | raise AssertionError('Expected call: %s\nNot called' % (expected,)) |
---|
802 | n/a | |
---|
803 | n/a | def _error_message(): |
---|
804 | n/a | msg = self._format_mock_failure_message(args, kwargs) |
---|
805 | n/a | return msg |
---|
806 | n/a | expected = self._call_matcher((args, kwargs)) |
---|
807 | n/a | actual = self._call_matcher(self.call_args) |
---|
808 | n/a | if expected != actual: |
---|
809 | n/a | cause = expected if isinstance(expected, Exception) else None |
---|
810 | n/a | raise AssertionError(_error_message()) from cause |
---|
811 | n/a | |
---|
812 | n/a | |
---|
813 | n/a | def assert_called_once_with(_mock_self, *args, **kwargs): |
---|
814 | n/a | """assert that the mock was called exactly once and with the specified |
---|
815 | n/a | arguments.""" |
---|
816 | n/a | self = _mock_self |
---|
817 | n/a | if not self.call_count == 1: |
---|
818 | n/a | msg = ("Expected '%s' to be called once. Called %s times." % |
---|
819 | n/a | (self._mock_name or 'mock', self.call_count)) |
---|
820 | n/a | raise AssertionError(msg) |
---|
821 | n/a | return self.assert_called_with(*args, **kwargs) |
---|
822 | n/a | |
---|
823 | n/a | |
---|
824 | n/a | def assert_has_calls(self, calls, any_order=False): |
---|
825 | n/a | """assert the mock has been called with the specified calls. |
---|
826 | n/a | The `mock_calls` list is checked for the calls. |
---|
827 | n/a | |
---|
828 | n/a | If `any_order` is False (the default) then the calls must be |
---|
829 | n/a | sequential. There can be extra calls before or after the |
---|
830 | n/a | specified calls. |
---|
831 | n/a | |
---|
832 | n/a | If `any_order` is True then the calls can be in any order, but |
---|
833 | n/a | they must all appear in `mock_calls`.""" |
---|
834 | n/a | expected = [self._call_matcher(c) for c in calls] |
---|
835 | n/a | cause = expected if isinstance(expected, Exception) else None |
---|
836 | n/a | all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls) |
---|
837 | n/a | if not any_order: |
---|
838 | n/a | if expected not in all_calls: |
---|
839 | n/a | raise AssertionError( |
---|
840 | n/a | 'Calls not found.\nExpected: %r\n' |
---|
841 | n/a | 'Actual: %r' % (_CallList(calls), self.mock_calls) |
---|
842 | n/a | ) from cause |
---|
843 | n/a | return |
---|
844 | n/a | |
---|
845 | n/a | all_calls = list(all_calls) |
---|
846 | n/a | |
---|
847 | n/a | not_found = [] |
---|
848 | n/a | for kall in expected: |
---|
849 | n/a | try: |
---|
850 | n/a | all_calls.remove(kall) |
---|
851 | n/a | except ValueError: |
---|
852 | n/a | not_found.append(kall) |
---|
853 | n/a | if not_found: |
---|
854 | n/a | raise AssertionError( |
---|
855 | n/a | '%r not all found in call list' % (tuple(not_found),) |
---|
856 | n/a | ) from cause |
---|
857 | n/a | |
---|
858 | n/a | |
---|
859 | n/a | def assert_any_call(self, *args, **kwargs): |
---|
860 | n/a | """assert the mock has been called with the specified arguments. |
---|
861 | n/a | |
---|
862 | n/a | The assert passes if the mock has *ever* been called, unlike |
---|
863 | n/a | `assert_called_with` and `assert_called_once_with` that only pass if |
---|
864 | n/a | the call is the most recent one.""" |
---|
865 | n/a | expected = self._call_matcher((args, kwargs)) |
---|
866 | n/a | actual = [self._call_matcher(c) for c in self.call_args_list] |
---|
867 | n/a | if expected not in actual: |
---|
868 | n/a | cause = expected if isinstance(expected, Exception) else None |
---|
869 | n/a | expected_string = self._format_mock_call_signature(args, kwargs) |
---|
870 | n/a | raise AssertionError( |
---|
871 | n/a | '%s call not found' % expected_string |
---|
872 | n/a | ) from cause |
---|
873 | n/a | |
---|
874 | n/a | |
---|
875 | n/a | def _get_child_mock(self, **kw): |
---|
876 | n/a | """Create the child mocks for attributes and return value. |
---|
877 | n/a | By default child mocks will be the same type as the parent. |
---|
878 | n/a | Subclasses of Mock may want to override this to customize the way |
---|
879 | n/a | child mocks are made. |
---|
880 | n/a | |
---|
881 | n/a | For non-callable mocks the callable variant will be used (rather than |
---|
882 | n/a | any custom subclass).""" |
---|
883 | n/a | _type = type(self) |
---|
884 | n/a | if not issubclass(_type, CallableMixin): |
---|
885 | n/a | if issubclass(_type, NonCallableMagicMock): |
---|
886 | n/a | klass = MagicMock |
---|
887 | n/a | elif issubclass(_type, NonCallableMock) : |
---|
888 | n/a | klass = Mock |
---|
889 | n/a | else: |
---|
890 | n/a | klass = _type.__mro__[1] |
---|
891 | n/a | return klass(**kw) |
---|
892 | n/a | |
---|
893 | n/a | |
---|
894 | n/a | |
---|
895 | n/a | def _try_iter(obj): |
---|
896 | n/a | if obj is None: |
---|
897 | n/a | return obj |
---|
898 | n/a | if _is_exception(obj): |
---|
899 | n/a | return obj |
---|
900 | n/a | if _callable(obj): |
---|
901 | n/a | return obj |
---|
902 | n/a | try: |
---|
903 | n/a | return iter(obj) |
---|
904 | n/a | except TypeError: |
---|
905 | n/a | # XXXX backwards compatibility |
---|
906 | n/a | # but this will blow up on first call - so maybe we should fail early? |
---|
907 | n/a | return obj |
---|
908 | n/a | |
---|
909 | n/a | |
---|
910 | n/a | |
---|
911 | n/a | class CallableMixin(Base): |
---|
912 | n/a | |
---|
913 | n/a | def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, |
---|
914 | n/a | wraps=None, name=None, spec_set=None, parent=None, |
---|
915 | n/a | _spec_state=None, _new_name='', _new_parent=None, **kwargs): |
---|
916 | n/a | self.__dict__['_mock_return_value'] = return_value |
---|
917 | n/a | |
---|
918 | n/a | _safe_super(CallableMixin, self).__init__( |
---|
919 | n/a | spec, wraps, name, spec_set, parent, |
---|
920 | n/a | _spec_state, _new_name, _new_parent, **kwargs |
---|
921 | n/a | ) |
---|
922 | n/a | |
---|
923 | n/a | self.side_effect = side_effect |
---|
924 | n/a | |
---|
925 | n/a | |
---|
926 | n/a | def _mock_check_sig(self, *args, **kwargs): |
---|
927 | n/a | # stub method that can be replaced with one with a specific signature |
---|
928 | n/a | pass |
---|
929 | n/a | |
---|
930 | n/a | |
---|
931 | n/a | def __call__(_mock_self, *args, **kwargs): |
---|
932 | n/a | # can't use self in-case a function / method we are mocking uses self |
---|
933 | n/a | # in the signature |
---|
934 | n/a | _mock_self._mock_check_sig(*args, **kwargs) |
---|
935 | n/a | return _mock_self._mock_call(*args, **kwargs) |
---|
936 | n/a | |
---|
937 | n/a | |
---|
938 | n/a | def _mock_call(_mock_self, *args, **kwargs): |
---|
939 | n/a | self = _mock_self |
---|
940 | n/a | self.called = True |
---|
941 | n/a | self.call_count += 1 |
---|
942 | n/a | _new_name = self._mock_new_name |
---|
943 | n/a | _new_parent = self._mock_new_parent |
---|
944 | n/a | |
---|
945 | n/a | _call = _Call((args, kwargs), two=True) |
---|
946 | n/a | self.call_args = _call |
---|
947 | n/a | self.call_args_list.append(_call) |
---|
948 | n/a | self.mock_calls.append(_Call(('', args, kwargs))) |
---|
949 | n/a | |
---|
950 | n/a | seen = set() |
---|
951 | n/a | skip_next_dot = _new_name == '()' |
---|
952 | n/a | do_method_calls = self._mock_parent is not None |
---|
953 | n/a | name = self._mock_name |
---|
954 | n/a | while _new_parent is not None: |
---|
955 | n/a | this_mock_call = _Call((_new_name, args, kwargs)) |
---|
956 | n/a | if _new_parent._mock_new_name: |
---|
957 | n/a | dot = '.' |
---|
958 | n/a | if skip_next_dot: |
---|
959 | n/a | dot = '' |
---|
960 | n/a | |
---|
961 | n/a | skip_next_dot = False |
---|
962 | n/a | if _new_parent._mock_new_name == '()': |
---|
963 | n/a | skip_next_dot = True |
---|
964 | n/a | |
---|
965 | n/a | _new_name = _new_parent._mock_new_name + dot + _new_name |
---|
966 | n/a | |
---|
967 | n/a | if do_method_calls: |
---|
968 | n/a | if _new_name == name: |
---|
969 | n/a | this_method_call = this_mock_call |
---|
970 | n/a | else: |
---|
971 | n/a | this_method_call = _Call((name, args, kwargs)) |
---|
972 | n/a | _new_parent.method_calls.append(this_method_call) |
---|
973 | n/a | |
---|
974 | n/a | do_method_calls = _new_parent._mock_parent is not None |
---|
975 | n/a | if do_method_calls: |
---|
976 | n/a | name = _new_parent._mock_name + '.' + name |
---|
977 | n/a | |
---|
978 | n/a | _new_parent.mock_calls.append(this_mock_call) |
---|
979 | n/a | _new_parent = _new_parent._mock_new_parent |
---|
980 | n/a | |
---|
981 | n/a | # use ids here so as not to call __hash__ on the mocks |
---|
982 | n/a | _new_parent_id = id(_new_parent) |
---|
983 | n/a | if _new_parent_id in seen: |
---|
984 | n/a | break |
---|
985 | n/a | seen.add(_new_parent_id) |
---|
986 | n/a | |
---|
987 | n/a | ret_val = DEFAULT |
---|
988 | n/a | effect = self.side_effect |
---|
989 | n/a | if effect is not None: |
---|
990 | n/a | if _is_exception(effect): |
---|
991 | n/a | raise effect |
---|
992 | n/a | |
---|
993 | n/a | if not _callable(effect): |
---|
994 | n/a | result = next(effect) |
---|
995 | n/a | if _is_exception(result): |
---|
996 | n/a | raise result |
---|
997 | n/a | if result is DEFAULT: |
---|
998 | n/a | result = self.return_value |
---|
999 | n/a | return result |
---|
1000 | n/a | |
---|
1001 | n/a | ret_val = effect(*args, **kwargs) |
---|
1002 | n/a | |
---|
1003 | n/a | if (self._mock_wraps is not None and |
---|
1004 | n/a | self._mock_return_value is DEFAULT): |
---|
1005 | n/a | return self._mock_wraps(*args, **kwargs) |
---|
1006 | n/a | if ret_val is DEFAULT: |
---|
1007 | n/a | ret_val = self.return_value |
---|
1008 | n/a | return ret_val |
---|
1009 | n/a | |
---|
1010 | n/a | |
---|
1011 | n/a | |
---|
1012 | n/a | class Mock(CallableMixin, NonCallableMock): |
---|
1013 | n/a | """ |
---|
1014 | n/a | Create a new `Mock` object. `Mock` takes several optional arguments |
---|
1015 | n/a | that specify the behaviour of the Mock object: |
---|
1016 | n/a | |
---|
1017 | n/a | * `spec`: This can be either a list of strings or an existing object (a |
---|
1018 | n/a | class or instance) that acts as the specification for the mock object. If |
---|
1019 | n/a | you pass in an object then a list of strings is formed by calling dir on |
---|
1020 | n/a | the object (excluding unsupported magic attributes and methods). Accessing |
---|
1021 | n/a | any attribute not in this list will raise an `AttributeError`. |
---|
1022 | n/a | |
---|
1023 | n/a | If `spec` is an object (rather than a list of strings) then |
---|
1024 | n/a | `mock.__class__` returns the class of the spec object. This allows mocks |
---|
1025 | n/a | to pass `isinstance` tests. |
---|
1026 | n/a | |
---|
1027 | n/a | * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* |
---|
1028 | n/a | or get an attribute on the mock that isn't on the object passed as |
---|
1029 | n/a | `spec_set` will raise an `AttributeError`. |
---|
1030 | n/a | |
---|
1031 | n/a | * `side_effect`: A function to be called whenever the Mock is called. See |
---|
1032 | n/a | the `side_effect` attribute. Useful for raising exceptions or |
---|
1033 | n/a | dynamically changing return values. The function is called with the same |
---|
1034 | n/a | arguments as the mock, and unless it returns `DEFAULT`, the return |
---|
1035 | n/a | value of this function is used as the return value. |
---|
1036 | n/a | |
---|
1037 | n/a | If `side_effect` is an iterable then each call to the mock will return |
---|
1038 | n/a | the next value from the iterable. If any of the members of the iterable |
---|
1039 | n/a | are exceptions they will be raised instead of returned. |
---|
1040 | n/a | |
---|
1041 | n/a | * `return_value`: The value returned when the mock is called. By default |
---|
1042 | n/a | this is a new Mock (created on first access). See the |
---|
1043 | n/a | `return_value` attribute. |
---|
1044 | n/a | |
---|
1045 | n/a | * `wraps`: Item for the mock object to wrap. If `wraps` is not None then |
---|
1046 | n/a | calling the Mock will pass the call through to the wrapped object |
---|
1047 | n/a | (returning the real result). Attribute access on the mock will return a |
---|
1048 | n/a | Mock object that wraps the corresponding attribute of the wrapped object |
---|
1049 | n/a | (so attempting to access an attribute that doesn't exist will raise an |
---|
1050 | n/a | `AttributeError`). |
---|
1051 | n/a | |
---|
1052 | n/a | If the mock has an explicit `return_value` set then calls are not passed |
---|
1053 | n/a | to the wrapped object and the `return_value` is returned instead. |
---|
1054 | n/a | |
---|
1055 | n/a | * `name`: If the mock has a name then it will be used in the repr of the |
---|
1056 | n/a | mock. This can be useful for debugging. The name is propagated to child |
---|
1057 | n/a | mocks. |
---|
1058 | n/a | |
---|
1059 | n/a | Mocks can also be called with arbitrary keyword arguments. These will be |
---|
1060 | n/a | used to set attributes on the mock after it is created. |
---|
1061 | n/a | """ |
---|
1062 | n/a | |
---|
1063 | n/a | |
---|
1064 | n/a | |
---|
1065 | n/a | def _dot_lookup(thing, comp, import_path): |
---|
1066 | n/a | try: |
---|
1067 | n/a | return getattr(thing, comp) |
---|
1068 | n/a | except AttributeError: |
---|
1069 | n/a | __import__(import_path) |
---|
1070 | n/a | return getattr(thing, comp) |
---|
1071 | n/a | |
---|
1072 | n/a | |
---|
1073 | n/a | def _importer(target): |
---|
1074 | n/a | components = target.split('.') |
---|
1075 | n/a | import_path = components.pop(0) |
---|
1076 | n/a | thing = __import__(import_path) |
---|
1077 | n/a | |
---|
1078 | n/a | for comp in components: |
---|
1079 | n/a | import_path += ".%s" % comp |
---|
1080 | n/a | thing = _dot_lookup(thing, comp, import_path) |
---|
1081 | n/a | return thing |
---|
1082 | n/a | |
---|
1083 | n/a | |
---|
1084 | n/a | def _is_started(patcher): |
---|
1085 | n/a | # XXXX horrible |
---|
1086 | n/a | return hasattr(patcher, 'is_local') |
---|
1087 | n/a | |
---|
1088 | n/a | |
---|
1089 | n/a | class _patch(object): |
---|
1090 | n/a | |
---|
1091 | n/a | attribute_name = None |
---|
1092 | n/a | _active_patches = [] |
---|
1093 | n/a | |
---|
1094 | n/a | def __init__( |
---|
1095 | n/a | self, getter, attribute, new, spec, create, |
---|
1096 | n/a | spec_set, autospec, new_callable, kwargs |
---|
1097 | n/a | ): |
---|
1098 | n/a | if new_callable is not None: |
---|
1099 | n/a | if new is not DEFAULT: |
---|
1100 | n/a | raise ValueError( |
---|
1101 | n/a | "Cannot use 'new' and 'new_callable' together" |
---|
1102 | n/a | ) |
---|
1103 | n/a | if autospec is not None: |
---|
1104 | n/a | raise ValueError( |
---|
1105 | n/a | "Cannot use 'autospec' and 'new_callable' together" |
---|
1106 | n/a | ) |
---|
1107 | n/a | |
---|
1108 | n/a | self.getter = getter |
---|
1109 | n/a | self.attribute = attribute |
---|
1110 | n/a | self.new = new |
---|
1111 | n/a | self.new_callable = new_callable |
---|
1112 | n/a | self.spec = spec |
---|
1113 | n/a | self.create = create |
---|
1114 | n/a | self.has_local = False |
---|
1115 | n/a | self.spec_set = spec_set |
---|
1116 | n/a | self.autospec = autospec |
---|
1117 | n/a | self.kwargs = kwargs |
---|
1118 | n/a | self.additional_patchers = [] |
---|
1119 | n/a | |
---|
1120 | n/a | |
---|
1121 | n/a | def copy(self): |
---|
1122 | n/a | patcher = _patch( |
---|
1123 | n/a | self.getter, self.attribute, self.new, self.spec, |
---|
1124 | n/a | self.create, self.spec_set, |
---|
1125 | n/a | self.autospec, self.new_callable, self.kwargs |
---|
1126 | n/a | ) |
---|
1127 | n/a | patcher.attribute_name = self.attribute_name |
---|
1128 | n/a | patcher.additional_patchers = [ |
---|
1129 | n/a | p.copy() for p in self.additional_patchers |
---|
1130 | n/a | ] |
---|
1131 | n/a | return patcher |
---|
1132 | n/a | |
---|
1133 | n/a | |
---|
1134 | n/a | def __call__(self, func): |
---|
1135 | n/a | if isinstance(func, type): |
---|
1136 | n/a | return self.decorate_class(func) |
---|
1137 | n/a | return self.decorate_callable(func) |
---|
1138 | n/a | |
---|
1139 | n/a | |
---|
1140 | n/a | def decorate_class(self, klass): |
---|
1141 | n/a | for attr in dir(klass): |
---|
1142 | n/a | if not attr.startswith(patch.TEST_PREFIX): |
---|
1143 | n/a | continue |
---|
1144 | n/a | |
---|
1145 | n/a | attr_value = getattr(klass, attr) |
---|
1146 | n/a | if not hasattr(attr_value, "__call__"): |
---|
1147 | n/a | continue |
---|
1148 | n/a | |
---|
1149 | n/a | patcher = self.copy() |
---|
1150 | n/a | setattr(klass, attr, patcher(attr_value)) |
---|
1151 | n/a | return klass |
---|
1152 | n/a | |
---|
1153 | n/a | |
---|
1154 | n/a | def decorate_callable(self, func): |
---|
1155 | n/a | if hasattr(func, 'patchings'): |
---|
1156 | n/a | func.patchings.append(self) |
---|
1157 | n/a | return func |
---|
1158 | n/a | |
---|
1159 | n/a | @wraps(func) |
---|
1160 | n/a | def patched(*args, **keywargs): |
---|
1161 | n/a | extra_args = [] |
---|
1162 | n/a | entered_patchers = [] |
---|
1163 | n/a | |
---|
1164 | n/a | exc_info = tuple() |
---|
1165 | n/a | try: |
---|
1166 | n/a | for patching in patched.patchings: |
---|
1167 | n/a | arg = patching.__enter__() |
---|
1168 | n/a | entered_patchers.append(patching) |
---|
1169 | n/a | if patching.attribute_name is not None: |
---|
1170 | n/a | keywargs.update(arg) |
---|
1171 | n/a | elif patching.new is DEFAULT: |
---|
1172 | n/a | extra_args.append(arg) |
---|
1173 | n/a | |
---|
1174 | n/a | args += tuple(extra_args) |
---|
1175 | n/a | return func(*args, **keywargs) |
---|
1176 | n/a | except: |
---|
1177 | n/a | if (patching not in entered_patchers and |
---|
1178 | n/a | _is_started(patching)): |
---|
1179 | n/a | # the patcher may have been started, but an exception |
---|
1180 | n/a | # raised whilst entering one of its additional_patchers |
---|
1181 | n/a | entered_patchers.append(patching) |
---|
1182 | n/a | # Pass the exception to __exit__ |
---|
1183 | n/a | exc_info = sys.exc_info() |
---|
1184 | n/a | # re-raise the exception |
---|
1185 | n/a | raise |
---|
1186 | n/a | finally: |
---|
1187 | n/a | for patching in reversed(entered_patchers): |
---|
1188 | n/a | patching.__exit__(*exc_info) |
---|
1189 | n/a | |
---|
1190 | n/a | patched.patchings = [self] |
---|
1191 | n/a | return patched |
---|
1192 | n/a | |
---|
1193 | n/a | |
---|
1194 | n/a | def get_original(self): |
---|
1195 | n/a | target = self.getter() |
---|
1196 | n/a | name = self.attribute |
---|
1197 | n/a | |
---|
1198 | n/a | original = DEFAULT |
---|
1199 | n/a | local = False |
---|
1200 | n/a | |
---|
1201 | n/a | try: |
---|
1202 | n/a | original = target.__dict__[name] |
---|
1203 | n/a | except (AttributeError, KeyError): |
---|
1204 | n/a | original = getattr(target, name, DEFAULT) |
---|
1205 | n/a | else: |
---|
1206 | n/a | local = True |
---|
1207 | n/a | |
---|
1208 | n/a | if name in _builtins and isinstance(target, ModuleType): |
---|
1209 | n/a | self.create = True |
---|
1210 | n/a | |
---|
1211 | n/a | if not self.create and original is DEFAULT: |
---|
1212 | n/a | raise AttributeError( |
---|
1213 | n/a | "%s does not have the attribute %r" % (target, name) |
---|
1214 | n/a | ) |
---|
1215 | n/a | return original, local |
---|
1216 | n/a | |
---|
1217 | n/a | |
---|
1218 | n/a | def __enter__(self): |
---|
1219 | n/a | """Perform the patch.""" |
---|
1220 | n/a | new, spec, spec_set = self.new, self.spec, self.spec_set |
---|
1221 | n/a | autospec, kwargs = self.autospec, self.kwargs |
---|
1222 | n/a | new_callable = self.new_callable |
---|
1223 | n/a | self.target = self.getter() |
---|
1224 | n/a | |
---|
1225 | n/a | # normalise False to None |
---|
1226 | n/a | if spec is False: |
---|
1227 | n/a | spec = None |
---|
1228 | n/a | if spec_set is False: |
---|
1229 | n/a | spec_set = None |
---|
1230 | n/a | if autospec is False: |
---|
1231 | n/a | autospec = None |
---|
1232 | n/a | |
---|
1233 | n/a | if spec is not None and autospec is not None: |
---|
1234 | n/a | raise TypeError("Can't specify spec and autospec") |
---|
1235 | n/a | if ((spec is not None or autospec is not None) and |
---|
1236 | n/a | spec_set not in (True, None)): |
---|
1237 | n/a | raise TypeError("Can't provide explicit spec_set *and* spec or autospec") |
---|
1238 | n/a | |
---|
1239 | n/a | original, local = self.get_original() |
---|
1240 | n/a | |
---|
1241 | n/a | if new is DEFAULT and autospec is None: |
---|
1242 | n/a | inherit = False |
---|
1243 | n/a | if spec is True: |
---|
1244 | n/a | # set spec to the object we are replacing |
---|
1245 | n/a | spec = original |
---|
1246 | n/a | if spec_set is True: |
---|
1247 | n/a | spec_set = original |
---|
1248 | n/a | spec = None |
---|
1249 | n/a | elif spec is not None: |
---|
1250 | n/a | if spec_set is True: |
---|
1251 | n/a | spec_set = spec |
---|
1252 | n/a | spec = None |
---|
1253 | n/a | elif spec_set is True: |
---|
1254 | n/a | spec_set = original |
---|
1255 | n/a | |
---|
1256 | n/a | if spec is not None or spec_set is not None: |
---|
1257 | n/a | if original is DEFAULT: |
---|
1258 | n/a | raise TypeError("Can't use 'spec' with create=True") |
---|
1259 | n/a | if isinstance(original, type): |
---|
1260 | n/a | # If we're patching out a class and there is a spec |
---|
1261 | n/a | inherit = True |
---|
1262 | n/a | |
---|
1263 | n/a | Klass = MagicMock |
---|
1264 | n/a | _kwargs = {} |
---|
1265 | n/a | if new_callable is not None: |
---|
1266 | n/a | Klass = new_callable |
---|
1267 | n/a | elif spec is not None or spec_set is not None: |
---|
1268 | n/a | this_spec = spec |
---|
1269 | n/a | if spec_set is not None: |
---|
1270 | n/a | this_spec = spec_set |
---|
1271 | n/a | if _is_list(this_spec): |
---|
1272 | n/a | not_callable = '__call__' not in this_spec |
---|
1273 | n/a | else: |
---|
1274 | n/a | not_callable = not callable(this_spec) |
---|
1275 | n/a | if not_callable: |
---|
1276 | n/a | Klass = NonCallableMagicMock |
---|
1277 | n/a | |
---|
1278 | n/a | if spec is not None: |
---|
1279 | n/a | _kwargs['spec'] = spec |
---|
1280 | n/a | if spec_set is not None: |
---|
1281 | n/a | _kwargs['spec_set'] = spec_set |
---|
1282 | n/a | |
---|
1283 | n/a | # add a name to mocks |
---|
1284 | n/a | if (isinstance(Klass, type) and |
---|
1285 | n/a | issubclass(Klass, NonCallableMock) and self.attribute): |
---|
1286 | n/a | _kwargs['name'] = self.attribute |
---|
1287 | n/a | |
---|
1288 | n/a | _kwargs.update(kwargs) |
---|
1289 | n/a | new = Klass(**_kwargs) |
---|
1290 | n/a | |
---|
1291 | n/a | if inherit and _is_instance_mock(new): |
---|
1292 | n/a | # we can only tell if the instance should be callable if the |
---|
1293 | n/a | # spec is not a list |
---|
1294 | n/a | this_spec = spec |
---|
1295 | n/a | if spec_set is not None: |
---|
1296 | n/a | this_spec = spec_set |
---|
1297 | n/a | if (not _is_list(this_spec) and not |
---|
1298 | n/a | _instance_callable(this_spec)): |
---|
1299 | n/a | Klass = NonCallableMagicMock |
---|
1300 | n/a | |
---|
1301 | n/a | _kwargs.pop('name') |
---|
1302 | n/a | new.return_value = Klass(_new_parent=new, _new_name='()', |
---|
1303 | n/a | **_kwargs) |
---|
1304 | n/a | elif autospec is not None: |
---|
1305 | n/a | # spec is ignored, new *must* be default, spec_set is treated |
---|
1306 | n/a | # as a boolean. Should we check spec is not None and that spec_set |
---|
1307 | n/a | # is a bool? |
---|
1308 | n/a | if new is not DEFAULT: |
---|
1309 | n/a | raise TypeError( |
---|
1310 | n/a | "autospec creates the mock for you. Can't specify " |
---|
1311 | n/a | "autospec and new." |
---|
1312 | n/a | ) |
---|
1313 | n/a | if original is DEFAULT: |
---|
1314 | n/a | raise TypeError("Can't use 'autospec' with create=True") |
---|
1315 | n/a | spec_set = bool(spec_set) |
---|
1316 | n/a | if autospec is True: |
---|
1317 | n/a | autospec = original |
---|
1318 | n/a | |
---|
1319 | n/a | new = create_autospec(autospec, spec_set=spec_set, |
---|
1320 | n/a | _name=self.attribute, **kwargs) |
---|
1321 | n/a | elif kwargs: |
---|
1322 | n/a | # can't set keyword args when we aren't creating the mock |
---|
1323 | n/a | # XXXX If new is a Mock we could call new.configure_mock(**kwargs) |
---|
1324 | n/a | raise TypeError("Can't pass kwargs to a mock we aren't creating") |
---|
1325 | n/a | |
---|
1326 | n/a | new_attr = new |
---|
1327 | n/a | |
---|
1328 | n/a | self.temp_original = original |
---|
1329 | n/a | self.is_local = local |
---|
1330 | n/a | setattr(self.target, self.attribute, new_attr) |
---|
1331 | n/a | if self.attribute_name is not None: |
---|
1332 | n/a | extra_args = {} |
---|
1333 | n/a | if self.new is DEFAULT: |
---|
1334 | n/a | extra_args[self.attribute_name] = new |
---|
1335 | n/a | for patching in self.additional_patchers: |
---|
1336 | n/a | arg = patching.__enter__() |
---|
1337 | n/a | if patching.new is DEFAULT: |
---|
1338 | n/a | extra_args.update(arg) |
---|
1339 | n/a | return extra_args |
---|
1340 | n/a | |
---|
1341 | n/a | return new |
---|
1342 | n/a | |
---|
1343 | n/a | |
---|
1344 | n/a | def __exit__(self, *exc_info): |
---|
1345 | n/a | """Undo the patch.""" |
---|
1346 | n/a | if not _is_started(self): |
---|
1347 | n/a | raise RuntimeError('stop called on unstarted patcher') |
---|
1348 | n/a | |
---|
1349 | n/a | if self.is_local and self.temp_original is not DEFAULT: |
---|
1350 | n/a | setattr(self.target, self.attribute, self.temp_original) |
---|
1351 | n/a | else: |
---|
1352 | n/a | delattr(self.target, self.attribute) |
---|
1353 | n/a | if not self.create and (not hasattr(self.target, self.attribute) or |
---|
1354 | n/a | self.attribute in ('__doc__', '__module__', |
---|
1355 | n/a | '__defaults__', '__annotations__', |
---|
1356 | n/a | '__kwdefaults__')): |
---|
1357 | n/a | # needed for proxy objects like django settings |
---|
1358 | n/a | setattr(self.target, self.attribute, self.temp_original) |
---|
1359 | n/a | |
---|
1360 | n/a | del self.temp_original |
---|
1361 | n/a | del self.is_local |
---|
1362 | n/a | del self.target |
---|
1363 | n/a | for patcher in reversed(self.additional_patchers): |
---|
1364 | n/a | if _is_started(patcher): |
---|
1365 | n/a | patcher.__exit__(*exc_info) |
---|
1366 | n/a | |
---|
1367 | n/a | |
---|
1368 | n/a | def start(self): |
---|
1369 | n/a | """Activate a patch, returning any created mock.""" |
---|
1370 | n/a | result = self.__enter__() |
---|
1371 | n/a | self._active_patches.append(self) |
---|
1372 | n/a | return result |
---|
1373 | n/a | |
---|
1374 | n/a | |
---|
1375 | n/a | def stop(self): |
---|
1376 | n/a | """Stop an active patch.""" |
---|
1377 | n/a | try: |
---|
1378 | n/a | self._active_patches.remove(self) |
---|
1379 | n/a | except ValueError: |
---|
1380 | n/a | # If the patch hasn't been started this will fail |
---|
1381 | n/a | pass |
---|
1382 | n/a | |
---|
1383 | n/a | return self.__exit__() |
---|
1384 | n/a | |
---|
1385 | n/a | |
---|
1386 | n/a | |
---|
1387 | n/a | def _get_target(target): |
---|
1388 | n/a | try: |
---|
1389 | n/a | target, attribute = target.rsplit('.', 1) |
---|
1390 | n/a | except (TypeError, ValueError): |
---|
1391 | n/a | raise TypeError("Need a valid target to patch. You supplied: %r" % |
---|
1392 | n/a | (target,)) |
---|
1393 | n/a | getter = lambda: _importer(target) |
---|
1394 | n/a | return getter, attribute |
---|
1395 | n/a | |
---|
1396 | n/a | |
---|
1397 | n/a | def _patch_object( |
---|
1398 | n/a | target, attribute, new=DEFAULT, spec=None, |
---|
1399 | n/a | create=False, spec_set=None, autospec=None, |
---|
1400 | n/a | new_callable=None, **kwargs |
---|
1401 | n/a | ): |
---|
1402 | n/a | """ |
---|
1403 | n/a | patch the named member (`attribute`) on an object (`target`) with a mock |
---|
1404 | n/a | object. |
---|
1405 | n/a | |
---|
1406 | n/a | `patch.object` can be used as a decorator, class decorator or a context |
---|
1407 | n/a | manager. Arguments `new`, `spec`, `create`, `spec_set`, |
---|
1408 | n/a | `autospec` and `new_callable` have the same meaning as for `patch`. Like |
---|
1409 | n/a | `patch`, `patch.object` takes arbitrary keyword arguments for configuring |
---|
1410 | n/a | the mock object it creates. |
---|
1411 | n/a | |
---|
1412 | n/a | When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` |
---|
1413 | n/a | for choosing which methods to wrap. |
---|
1414 | n/a | """ |
---|
1415 | n/a | getter = lambda: target |
---|
1416 | n/a | return _patch( |
---|
1417 | n/a | getter, attribute, new, spec, create, |
---|
1418 | n/a | spec_set, autospec, new_callable, kwargs |
---|
1419 | n/a | ) |
---|
1420 | n/a | |
---|
1421 | n/a | |
---|
1422 | n/a | def _patch_multiple(target, spec=None, create=False, spec_set=None, |
---|
1423 | n/a | autospec=None, new_callable=None, **kwargs): |
---|
1424 | n/a | """Perform multiple patches in a single call. It takes the object to be |
---|
1425 | n/a | patched (either as an object or a string to fetch the object by importing) |
---|
1426 | n/a | and keyword arguments for the patches:: |
---|
1427 | n/a | |
---|
1428 | n/a | with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): |
---|
1429 | n/a | ... |
---|
1430 | n/a | |
---|
1431 | n/a | Use `DEFAULT` as the value if you want `patch.multiple` to create |
---|
1432 | n/a | mocks for you. In this case the created mocks are passed into a decorated |
---|
1433 | n/a | function by keyword, and a dictionary is returned when `patch.multiple` is |
---|
1434 | n/a | used as a context manager. |
---|
1435 | n/a | |
---|
1436 | n/a | `patch.multiple` can be used as a decorator, class decorator or a context |
---|
1437 | n/a | manager. The arguments `spec`, `spec_set`, `create`, |
---|
1438 | n/a | `autospec` and `new_callable` have the same meaning as for `patch`. These |
---|
1439 | n/a | arguments will be applied to *all* patches done by `patch.multiple`. |
---|
1440 | n/a | |
---|
1441 | n/a | When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` |
---|
1442 | n/a | for choosing which methods to wrap. |
---|
1443 | n/a | """ |
---|
1444 | n/a | if type(target) is str: |
---|
1445 | n/a | getter = lambda: _importer(target) |
---|
1446 | n/a | else: |
---|
1447 | n/a | getter = lambda: target |
---|
1448 | n/a | |
---|
1449 | n/a | if not kwargs: |
---|
1450 | n/a | raise ValueError( |
---|
1451 | n/a | 'Must supply at least one keyword argument with patch.multiple' |
---|
1452 | n/a | ) |
---|
1453 | n/a | # need to wrap in a list for python 3, where items is a view |
---|
1454 | n/a | items = list(kwargs.items()) |
---|
1455 | n/a | attribute, new = items[0] |
---|
1456 | n/a | patcher = _patch( |
---|
1457 | n/a | getter, attribute, new, spec, create, spec_set, |
---|
1458 | n/a | autospec, new_callable, {} |
---|
1459 | n/a | ) |
---|
1460 | n/a | patcher.attribute_name = attribute |
---|
1461 | n/a | for attribute, new in items[1:]: |
---|
1462 | n/a | this_patcher = _patch( |
---|
1463 | n/a | getter, attribute, new, spec, create, spec_set, |
---|
1464 | n/a | autospec, new_callable, {} |
---|
1465 | n/a | ) |
---|
1466 | n/a | this_patcher.attribute_name = attribute |
---|
1467 | n/a | patcher.additional_patchers.append(this_patcher) |
---|
1468 | n/a | return patcher |
---|
1469 | n/a | |
---|
1470 | n/a | |
---|
1471 | n/a | def patch( |
---|
1472 | n/a | target, new=DEFAULT, spec=None, create=False, |
---|
1473 | n/a | spec_set=None, autospec=None, new_callable=None, **kwargs |
---|
1474 | n/a | ): |
---|
1475 | n/a | """ |
---|
1476 | n/a | `patch` acts as a function decorator, class decorator or a context |
---|
1477 | n/a | manager. Inside the body of the function or with statement, the `target` |
---|
1478 | n/a | is patched with a `new` object. When the function/with statement exits |
---|
1479 | n/a | the patch is undone. |
---|
1480 | n/a | |
---|
1481 | n/a | If `new` is omitted, then the target is replaced with a |
---|
1482 | n/a | `MagicMock`. If `patch` is used as a decorator and `new` is |
---|
1483 | n/a | omitted, the created mock is passed in as an extra argument to the |
---|
1484 | n/a | decorated function. If `patch` is used as a context manager the created |
---|
1485 | n/a | mock is returned by the context manager. |
---|
1486 | n/a | |
---|
1487 | n/a | `target` should be a string in the form `'package.module.ClassName'`. The |
---|
1488 | n/a | `target` is imported and the specified object replaced with the `new` |
---|
1489 | n/a | object, so the `target` must be importable from the environment you are |
---|
1490 | n/a | calling `patch` from. The target is imported when the decorated function |
---|
1491 | n/a | is executed, not at decoration time. |
---|
1492 | n/a | |
---|
1493 | n/a | The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` |
---|
1494 | n/a | if patch is creating one for you. |
---|
1495 | n/a | |
---|
1496 | n/a | In addition you can pass `spec=True` or `spec_set=True`, which causes |
---|
1497 | n/a | patch to pass in the object being mocked as the spec/spec_set object. |
---|
1498 | n/a | |
---|
1499 | n/a | `new_callable` allows you to specify a different class, or callable object, |
---|
1500 | n/a | that will be called to create the `new` object. By default `MagicMock` is |
---|
1501 | n/a | used. |
---|
1502 | n/a | |
---|
1503 | n/a | A more powerful form of `spec` is `autospec`. If you set `autospec=True` |
---|
1504 | n/a | then the mock will be created with a spec from the object being replaced. |
---|
1505 | n/a | All attributes of the mock will also have the spec of the corresponding |
---|
1506 | n/a | attribute of the object being replaced. Methods and functions being |
---|
1507 | n/a | mocked will have their arguments checked and will raise a `TypeError` if |
---|
1508 | n/a | they are called with the wrong signature. For mocks replacing a class, |
---|
1509 | n/a | their return value (the 'instance') will have the same spec as the class. |
---|
1510 | n/a | |
---|
1511 | n/a | Instead of `autospec=True` you can pass `autospec=some_object` to use an |
---|
1512 | n/a | arbitrary object as the spec instead of the one being replaced. |
---|
1513 | n/a | |
---|
1514 | n/a | By default `patch` will fail to replace attributes that don't exist. If |
---|
1515 | n/a | you pass in `create=True`, and the attribute doesn't exist, patch will |
---|
1516 | n/a | create the attribute for you when the patched function is called, and |
---|
1517 | n/a | delete it again afterwards. This is useful for writing tests against |
---|
1518 | n/a | attributes that your production code creates at runtime. It is off by |
---|
1519 | n/a | default because it can be dangerous. With it switched on you can write |
---|
1520 | n/a | passing tests against APIs that don't actually exist! |
---|
1521 | n/a | |
---|
1522 | n/a | Patch can be used as a `TestCase` class decorator. It works by |
---|
1523 | n/a | decorating each test method in the class. This reduces the boilerplate |
---|
1524 | n/a | code when your test methods share a common patchings set. `patch` finds |
---|
1525 | n/a | tests by looking for method names that start with `patch.TEST_PREFIX`. |
---|
1526 | n/a | By default this is `test`, which matches the way `unittest` finds tests. |
---|
1527 | n/a | You can specify an alternative prefix by setting `patch.TEST_PREFIX`. |
---|
1528 | n/a | |
---|
1529 | n/a | Patch can be used as a context manager, with the with statement. Here the |
---|
1530 | n/a | patching applies to the indented block after the with statement. If you |
---|
1531 | n/a | use "as" then the patched object will be bound to the name after the |
---|
1532 | n/a | "as"; very useful if `patch` is creating a mock object for you. |
---|
1533 | n/a | |
---|
1534 | n/a | `patch` takes arbitrary keyword arguments. These will be passed to |
---|
1535 | n/a | the `Mock` (or `new_callable`) on construction. |
---|
1536 | n/a | |
---|
1537 | n/a | `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are |
---|
1538 | n/a | available for alternate use-cases. |
---|
1539 | n/a | """ |
---|
1540 | n/a | getter, attribute = _get_target(target) |
---|
1541 | n/a | return _patch( |
---|
1542 | n/a | getter, attribute, new, spec, create, |
---|
1543 | n/a | spec_set, autospec, new_callable, kwargs |
---|
1544 | n/a | ) |
---|
1545 | n/a | |
---|
1546 | n/a | |
---|
1547 | n/a | class _patch_dict(object): |
---|
1548 | n/a | """ |
---|
1549 | n/a | Patch a dictionary, or dictionary like object, and restore the dictionary |
---|
1550 | n/a | to its original state after the test. |
---|
1551 | n/a | |
---|
1552 | n/a | `in_dict` can be a dictionary or a mapping like container. If it is a |
---|
1553 | n/a | mapping then it must at least support getting, setting and deleting items |
---|
1554 | n/a | plus iterating over keys. |
---|
1555 | n/a | |
---|
1556 | n/a | `in_dict` can also be a string specifying the name of the dictionary, which |
---|
1557 | n/a | will then be fetched by importing it. |
---|
1558 | n/a | |
---|
1559 | n/a | `values` can be a dictionary of values to set in the dictionary. `values` |
---|
1560 | n/a | can also be an iterable of `(key, value)` pairs. |
---|
1561 | n/a | |
---|
1562 | n/a | If `clear` is True then the dictionary will be cleared before the new |
---|
1563 | n/a | values are set. |
---|
1564 | n/a | |
---|
1565 | n/a | `patch.dict` can also be called with arbitrary keyword arguments to set |
---|
1566 | n/a | values in the dictionary:: |
---|
1567 | n/a | |
---|
1568 | n/a | with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): |
---|
1569 | n/a | ... |
---|
1570 | n/a | |
---|
1571 | n/a | `patch.dict` can be used as a context manager, decorator or class |
---|
1572 | n/a | decorator. When used as a class decorator `patch.dict` honours |
---|
1573 | n/a | `patch.TEST_PREFIX` for choosing which methods to wrap. |
---|
1574 | n/a | """ |
---|
1575 | n/a | |
---|
1576 | n/a | def __init__(self, in_dict, values=(), clear=False, **kwargs): |
---|
1577 | n/a | if isinstance(in_dict, str): |
---|
1578 | n/a | in_dict = _importer(in_dict) |
---|
1579 | n/a | self.in_dict = in_dict |
---|
1580 | n/a | # support any argument supported by dict(...) constructor |
---|
1581 | n/a | self.values = dict(values) |
---|
1582 | n/a | self.values.update(kwargs) |
---|
1583 | n/a | self.clear = clear |
---|
1584 | n/a | self._original = None |
---|
1585 | n/a | |
---|
1586 | n/a | |
---|
1587 | n/a | def __call__(self, f): |
---|
1588 | n/a | if isinstance(f, type): |
---|
1589 | n/a | return self.decorate_class(f) |
---|
1590 | n/a | @wraps(f) |
---|
1591 | n/a | def _inner(*args, **kw): |
---|
1592 | n/a | self._patch_dict() |
---|
1593 | n/a | try: |
---|
1594 | n/a | return f(*args, **kw) |
---|
1595 | n/a | finally: |
---|
1596 | n/a | self._unpatch_dict() |
---|
1597 | n/a | |
---|
1598 | n/a | return _inner |
---|
1599 | n/a | |
---|
1600 | n/a | |
---|
1601 | n/a | def decorate_class(self, klass): |
---|
1602 | n/a | for attr in dir(klass): |
---|
1603 | n/a | attr_value = getattr(klass, attr) |
---|
1604 | n/a | if (attr.startswith(patch.TEST_PREFIX) and |
---|
1605 | n/a | hasattr(attr_value, "__call__")): |
---|
1606 | n/a | decorator = _patch_dict(self.in_dict, self.values, self.clear) |
---|
1607 | n/a | decorated = decorator(attr_value) |
---|
1608 | n/a | setattr(klass, attr, decorated) |
---|
1609 | n/a | return klass |
---|
1610 | n/a | |
---|
1611 | n/a | |
---|
1612 | n/a | def __enter__(self): |
---|
1613 | n/a | """Patch the dict.""" |
---|
1614 | n/a | self._patch_dict() |
---|
1615 | n/a | |
---|
1616 | n/a | |
---|
1617 | n/a | def _patch_dict(self): |
---|
1618 | n/a | values = self.values |
---|
1619 | n/a | in_dict = self.in_dict |
---|
1620 | n/a | clear = self.clear |
---|
1621 | n/a | |
---|
1622 | n/a | try: |
---|
1623 | n/a | original = in_dict.copy() |
---|
1624 | n/a | except AttributeError: |
---|
1625 | n/a | # dict like object with no copy method |
---|
1626 | n/a | # must support iteration over keys |
---|
1627 | n/a | original = {} |
---|
1628 | n/a | for key in in_dict: |
---|
1629 | n/a | original[key] = in_dict[key] |
---|
1630 | n/a | self._original = original |
---|
1631 | n/a | |
---|
1632 | n/a | if clear: |
---|
1633 | n/a | _clear_dict(in_dict) |
---|
1634 | n/a | |
---|
1635 | n/a | try: |
---|
1636 | n/a | in_dict.update(values) |
---|
1637 | n/a | except AttributeError: |
---|
1638 | n/a | # dict like object with no update method |
---|
1639 | n/a | for key in values: |
---|
1640 | n/a | in_dict[key] = values[key] |
---|
1641 | n/a | |
---|
1642 | n/a | |
---|
1643 | n/a | def _unpatch_dict(self): |
---|
1644 | n/a | in_dict = self.in_dict |
---|
1645 | n/a | original = self._original |
---|
1646 | n/a | |
---|
1647 | n/a | _clear_dict(in_dict) |
---|
1648 | n/a | |
---|
1649 | n/a | try: |
---|
1650 | n/a | in_dict.update(original) |
---|
1651 | n/a | except AttributeError: |
---|
1652 | n/a | for key in original: |
---|
1653 | n/a | in_dict[key] = original[key] |
---|
1654 | n/a | |
---|
1655 | n/a | |
---|
1656 | n/a | def __exit__(self, *args): |
---|
1657 | n/a | """Unpatch the dict.""" |
---|
1658 | n/a | self._unpatch_dict() |
---|
1659 | n/a | return False |
---|
1660 | n/a | |
---|
1661 | n/a | start = __enter__ |
---|
1662 | n/a | stop = __exit__ |
---|
1663 | n/a | |
---|
1664 | n/a | |
---|
1665 | n/a | def _clear_dict(in_dict): |
---|
1666 | n/a | try: |
---|
1667 | n/a | in_dict.clear() |
---|
1668 | n/a | except AttributeError: |
---|
1669 | n/a | keys = list(in_dict) |
---|
1670 | n/a | for key in keys: |
---|
1671 | n/a | del in_dict[key] |
---|
1672 | n/a | |
---|
1673 | n/a | |
---|
1674 | n/a | def _patch_stopall(): |
---|
1675 | n/a | """Stop all active patches. LIFO to unroll nested patches.""" |
---|
1676 | n/a | for patch in reversed(_patch._active_patches): |
---|
1677 | n/a | patch.stop() |
---|
1678 | n/a | |
---|
1679 | n/a | |
---|
1680 | n/a | patch.object = _patch_object |
---|
1681 | n/a | patch.dict = _patch_dict |
---|
1682 | n/a | patch.multiple = _patch_multiple |
---|
1683 | n/a | patch.stopall = _patch_stopall |
---|
1684 | n/a | patch.TEST_PREFIX = 'test' |
---|
1685 | n/a | |
---|
1686 | n/a | magic_methods = ( |
---|
1687 | n/a | "lt le gt ge eq ne " |
---|
1688 | n/a | "getitem setitem delitem " |
---|
1689 | n/a | "len contains iter " |
---|
1690 | n/a | "hash str sizeof " |
---|
1691 | n/a | "enter exit " |
---|
1692 | n/a | # we added divmod and rdivmod here instead of numerics |
---|
1693 | n/a | # because there is no idivmod |
---|
1694 | n/a | "divmod rdivmod neg pos abs invert " |
---|
1695 | n/a | "complex int float index " |
---|
1696 | n/a | "trunc floor ceil " |
---|
1697 | n/a | "bool next " |
---|
1698 | n/a | ) |
---|
1699 | n/a | |
---|
1700 | n/a | numerics = ( |
---|
1701 | n/a | "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv" |
---|
1702 | n/a | ) |
---|
1703 | n/a | inplace = ' '.join('i%s' % n for n in numerics.split()) |
---|
1704 | n/a | right = ' '.join('r%s' % n for n in numerics.split()) |
---|
1705 | n/a | |
---|
1706 | n/a | # not including __prepare__, __instancecheck__, __subclasscheck__ |
---|
1707 | n/a | # (as they are metaclass methods) |
---|
1708 | n/a | # __del__ is not supported at all as it causes problems if it exists |
---|
1709 | n/a | |
---|
1710 | n/a | _non_defaults = { |
---|
1711 | n/a | '__get__', '__set__', '__delete__', '__reversed__', '__missing__', |
---|
1712 | n/a | '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__', |
---|
1713 | n/a | '__getstate__', '__setstate__', '__getformat__', '__setformat__', |
---|
1714 | n/a | '__repr__', '__dir__', '__subclasses__', '__format__', |
---|
1715 | n/a | '__getnewargs_ex__', |
---|
1716 | n/a | } |
---|
1717 | n/a | |
---|
1718 | n/a | |
---|
1719 | n/a | def _get_method(name, func): |
---|
1720 | n/a | "Turns a callable object (like a mock) into a real function" |
---|
1721 | n/a | def method(self, *args, **kw): |
---|
1722 | n/a | return func(self, *args, **kw) |
---|
1723 | n/a | method.__name__ = name |
---|
1724 | n/a | return method |
---|
1725 | n/a | |
---|
1726 | n/a | |
---|
1727 | n/a | _magics = { |
---|
1728 | n/a | '__%s__' % method for method in |
---|
1729 | n/a | ' '.join([magic_methods, numerics, inplace, right]).split() |
---|
1730 | n/a | } |
---|
1731 | n/a | |
---|
1732 | n/a | _all_magics = _magics | _non_defaults |
---|
1733 | n/a | |
---|
1734 | n/a | _unsupported_magics = { |
---|
1735 | n/a | '__getattr__', '__setattr__', |
---|
1736 | n/a | '__init__', '__new__', '__prepare__' |
---|
1737 | n/a | '__instancecheck__', '__subclasscheck__', |
---|
1738 | n/a | '__del__' |
---|
1739 | n/a | } |
---|
1740 | n/a | |
---|
1741 | n/a | _calculate_return_value = { |
---|
1742 | n/a | '__hash__': lambda self: object.__hash__(self), |
---|
1743 | n/a | '__str__': lambda self: object.__str__(self), |
---|
1744 | n/a | '__sizeof__': lambda self: object.__sizeof__(self), |
---|
1745 | n/a | } |
---|
1746 | n/a | |
---|
1747 | n/a | _return_values = { |
---|
1748 | n/a | '__lt__': NotImplemented, |
---|
1749 | n/a | '__gt__': NotImplemented, |
---|
1750 | n/a | '__le__': NotImplemented, |
---|
1751 | n/a | '__ge__': NotImplemented, |
---|
1752 | n/a | '__int__': 1, |
---|
1753 | n/a | '__contains__': False, |
---|
1754 | n/a | '__len__': 0, |
---|
1755 | n/a | '__exit__': False, |
---|
1756 | n/a | '__complex__': 1j, |
---|
1757 | n/a | '__float__': 1.0, |
---|
1758 | n/a | '__bool__': True, |
---|
1759 | n/a | '__index__': 1, |
---|
1760 | n/a | } |
---|
1761 | n/a | |
---|
1762 | n/a | |
---|
1763 | n/a | def _get_eq(self): |
---|
1764 | n/a | def __eq__(other): |
---|
1765 | n/a | ret_val = self.__eq__._mock_return_value |
---|
1766 | n/a | if ret_val is not DEFAULT: |
---|
1767 | n/a | return ret_val |
---|
1768 | n/a | if self is other: |
---|
1769 | n/a | return True |
---|
1770 | n/a | return NotImplemented |
---|
1771 | n/a | return __eq__ |
---|
1772 | n/a | |
---|
1773 | n/a | def _get_ne(self): |
---|
1774 | n/a | def __ne__(other): |
---|
1775 | n/a | if self.__ne__._mock_return_value is not DEFAULT: |
---|
1776 | n/a | return DEFAULT |
---|
1777 | n/a | if self is other: |
---|
1778 | n/a | return False |
---|
1779 | n/a | return NotImplemented |
---|
1780 | n/a | return __ne__ |
---|
1781 | n/a | |
---|
1782 | n/a | def _get_iter(self): |
---|
1783 | n/a | def __iter__(): |
---|
1784 | n/a | ret_val = self.__iter__._mock_return_value |
---|
1785 | n/a | if ret_val is DEFAULT: |
---|
1786 | n/a | return iter([]) |
---|
1787 | n/a | # if ret_val was already an iterator, then calling iter on it should |
---|
1788 | n/a | # return the iterator unchanged |
---|
1789 | n/a | return iter(ret_val) |
---|
1790 | n/a | return __iter__ |
---|
1791 | n/a | |
---|
1792 | n/a | _side_effect_methods = { |
---|
1793 | n/a | '__eq__': _get_eq, |
---|
1794 | n/a | '__ne__': _get_ne, |
---|
1795 | n/a | '__iter__': _get_iter, |
---|
1796 | n/a | } |
---|
1797 | n/a | |
---|
1798 | n/a | |
---|
1799 | n/a | |
---|
1800 | n/a | def _set_return_value(mock, method, name): |
---|
1801 | n/a | fixed = _return_values.get(name, DEFAULT) |
---|
1802 | n/a | if fixed is not DEFAULT: |
---|
1803 | n/a | method.return_value = fixed |
---|
1804 | n/a | return |
---|
1805 | n/a | |
---|
1806 | n/a | return_calulator = _calculate_return_value.get(name) |
---|
1807 | n/a | if return_calulator is not None: |
---|
1808 | n/a | try: |
---|
1809 | n/a | return_value = return_calulator(mock) |
---|
1810 | n/a | except AttributeError: |
---|
1811 | n/a | # XXXX why do we return AttributeError here? |
---|
1812 | n/a | # set it as a side_effect instead? |
---|
1813 | n/a | return_value = AttributeError(name) |
---|
1814 | n/a | method.return_value = return_value |
---|
1815 | n/a | return |
---|
1816 | n/a | |
---|
1817 | n/a | side_effector = _side_effect_methods.get(name) |
---|
1818 | n/a | if side_effector is not None: |
---|
1819 | n/a | method.side_effect = side_effector(mock) |
---|
1820 | n/a | |
---|
1821 | n/a | |
---|
1822 | n/a | |
---|
1823 | n/a | class MagicMixin(object): |
---|
1824 | n/a | def __init__(self, *args, **kw): |
---|
1825 | n/a | self._mock_set_magics() # make magic work for kwargs in init |
---|
1826 | n/a | _safe_super(MagicMixin, self).__init__(*args, **kw) |
---|
1827 | n/a | self._mock_set_magics() # fix magic broken by upper level init |
---|
1828 | n/a | |
---|
1829 | n/a | |
---|
1830 | n/a | def _mock_set_magics(self): |
---|
1831 | n/a | these_magics = _magics |
---|
1832 | n/a | |
---|
1833 | n/a | if getattr(self, "_mock_methods", None) is not None: |
---|
1834 | n/a | these_magics = _magics.intersection(self._mock_methods) |
---|
1835 | n/a | |
---|
1836 | n/a | remove_magics = set() |
---|
1837 | n/a | remove_magics = _magics - these_magics |
---|
1838 | n/a | |
---|
1839 | n/a | for entry in remove_magics: |
---|
1840 | n/a | if entry in type(self).__dict__: |
---|
1841 | n/a | # remove unneeded magic methods |
---|
1842 | n/a | delattr(self, entry) |
---|
1843 | n/a | |
---|
1844 | n/a | # don't overwrite existing attributes if called a second time |
---|
1845 | n/a | these_magics = these_magics - set(type(self).__dict__) |
---|
1846 | n/a | |
---|
1847 | n/a | _type = type(self) |
---|
1848 | n/a | for entry in these_magics: |
---|
1849 | n/a | setattr(_type, entry, MagicProxy(entry, self)) |
---|
1850 | n/a | |
---|
1851 | n/a | |
---|
1852 | n/a | |
---|
1853 | n/a | class NonCallableMagicMock(MagicMixin, NonCallableMock): |
---|
1854 | n/a | """A version of `MagicMock` that isn't callable.""" |
---|
1855 | n/a | def mock_add_spec(self, spec, spec_set=False): |
---|
1856 | n/a | """Add a spec to a mock. `spec` can either be an object or a |
---|
1857 | n/a | list of strings. Only attributes on the `spec` can be fetched as |
---|
1858 | n/a | attributes from the mock. |
---|
1859 | n/a | |
---|
1860 | n/a | If `spec_set` is True then only attributes on the spec can be set.""" |
---|
1861 | n/a | self._mock_add_spec(spec, spec_set) |
---|
1862 | n/a | self._mock_set_magics() |
---|
1863 | n/a | |
---|
1864 | n/a | |
---|
1865 | n/a | |
---|
1866 | n/a | class MagicMock(MagicMixin, Mock): |
---|
1867 | n/a | """ |
---|
1868 | n/a | MagicMock is a subclass of Mock with default implementations |
---|
1869 | n/a | of most of the magic methods. You can use MagicMock without having to |
---|
1870 | n/a | configure the magic methods yourself. |
---|
1871 | n/a | |
---|
1872 | n/a | If you use the `spec` or `spec_set` arguments then *only* magic |
---|
1873 | n/a | methods that exist in the spec will be created. |
---|
1874 | n/a | |
---|
1875 | n/a | Attributes and the return value of a `MagicMock` will also be `MagicMocks`. |
---|
1876 | n/a | """ |
---|
1877 | n/a | def mock_add_spec(self, spec, spec_set=False): |
---|
1878 | n/a | """Add a spec to a mock. `spec` can either be an object or a |
---|
1879 | n/a | list of strings. Only attributes on the `spec` can be fetched as |
---|
1880 | n/a | attributes from the mock. |
---|
1881 | n/a | |
---|
1882 | n/a | If `spec_set` is True then only attributes on the spec can be set.""" |
---|
1883 | n/a | self._mock_add_spec(spec, spec_set) |
---|
1884 | n/a | self._mock_set_magics() |
---|
1885 | n/a | |
---|
1886 | n/a | |
---|
1887 | n/a | |
---|
1888 | n/a | class MagicProxy(object): |
---|
1889 | n/a | def __init__(self, name, parent): |
---|
1890 | n/a | self.name = name |
---|
1891 | n/a | self.parent = parent |
---|
1892 | n/a | |
---|
1893 | n/a | def __call__(self, *args, **kwargs): |
---|
1894 | n/a | m = self.create_mock() |
---|
1895 | n/a | return m(*args, **kwargs) |
---|
1896 | n/a | |
---|
1897 | n/a | def create_mock(self): |
---|
1898 | n/a | entry = self.name |
---|
1899 | n/a | parent = self.parent |
---|
1900 | n/a | m = parent._get_child_mock(name=entry, _new_name=entry, |
---|
1901 | n/a | _new_parent=parent) |
---|
1902 | n/a | setattr(parent, entry, m) |
---|
1903 | n/a | _set_return_value(parent, m, entry) |
---|
1904 | n/a | return m |
---|
1905 | n/a | |
---|
1906 | n/a | def __get__(self, obj, _type=None): |
---|
1907 | n/a | return self.create_mock() |
---|
1908 | n/a | |
---|
1909 | n/a | |
---|
1910 | n/a | |
---|
1911 | n/a | class _ANY(object): |
---|
1912 | n/a | "A helper object that compares equal to everything." |
---|
1913 | n/a | |
---|
1914 | n/a | def __eq__(self, other): |
---|
1915 | n/a | return True |
---|
1916 | n/a | |
---|
1917 | n/a | def __ne__(self, other): |
---|
1918 | n/a | return False |
---|
1919 | n/a | |
---|
1920 | n/a | def __repr__(self): |
---|
1921 | n/a | return '<ANY>' |
---|
1922 | n/a | |
---|
1923 | n/a | ANY = _ANY() |
---|
1924 | n/a | |
---|
1925 | n/a | |
---|
1926 | n/a | |
---|
1927 | n/a | def _format_call_signature(name, args, kwargs): |
---|
1928 | n/a | message = '%s(%%s)' % name |
---|
1929 | n/a | formatted_args = '' |
---|
1930 | n/a | args_string = ', '.join([repr(arg) for arg in args]) |
---|
1931 | n/a | kwargs_string = ', '.join([ |
---|
1932 | n/a | '%s=%r' % (key, value) for key, value in sorted(kwargs.items()) |
---|
1933 | n/a | ]) |
---|
1934 | n/a | if args_string: |
---|
1935 | n/a | formatted_args = args_string |
---|
1936 | n/a | if kwargs_string: |
---|
1937 | n/a | if formatted_args: |
---|
1938 | n/a | formatted_args += ', ' |
---|
1939 | n/a | formatted_args += kwargs_string |
---|
1940 | n/a | |
---|
1941 | n/a | return message % formatted_args |
---|
1942 | n/a | |
---|
1943 | n/a | |
---|
1944 | n/a | |
---|
1945 | n/a | class _Call(tuple): |
---|
1946 | n/a | """ |
---|
1947 | n/a | A tuple for holding the results of a call to a mock, either in the form |
---|
1948 | n/a | `(args, kwargs)` or `(name, args, kwargs)`. |
---|
1949 | n/a | |
---|
1950 | n/a | If args or kwargs are empty then a call tuple will compare equal to |
---|
1951 | n/a | a tuple without those values. This makes comparisons less verbose:: |
---|
1952 | n/a | |
---|
1953 | n/a | _Call(('name', (), {})) == ('name',) |
---|
1954 | n/a | _Call(('name', (1,), {})) == ('name', (1,)) |
---|
1955 | n/a | _Call(((), {'a': 'b'})) == ({'a': 'b'},) |
---|
1956 | n/a | |
---|
1957 | n/a | The `_Call` object provides a useful shortcut for comparing with call:: |
---|
1958 | n/a | |
---|
1959 | n/a | _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) |
---|
1960 | n/a | _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) |
---|
1961 | n/a | |
---|
1962 | n/a | If the _Call has no name then it will match any name. |
---|
1963 | n/a | """ |
---|
1964 | n/a | def __new__(cls, value=(), name='', parent=None, two=False, |
---|
1965 | n/a | from_kall=True): |
---|
1966 | n/a | args = () |
---|
1967 | n/a | kwargs = {} |
---|
1968 | n/a | _len = len(value) |
---|
1969 | n/a | if _len == 3: |
---|
1970 | n/a | name, args, kwargs = value |
---|
1971 | n/a | elif _len == 2: |
---|
1972 | n/a | first, second = value |
---|
1973 | n/a | if isinstance(first, str): |
---|
1974 | n/a | name = first |
---|
1975 | n/a | if isinstance(second, tuple): |
---|
1976 | n/a | args = second |
---|
1977 | n/a | else: |
---|
1978 | n/a | kwargs = second |
---|
1979 | n/a | else: |
---|
1980 | n/a | args, kwargs = first, second |
---|
1981 | n/a | elif _len == 1: |
---|
1982 | n/a | value, = value |
---|
1983 | n/a | if isinstance(value, str): |
---|
1984 | n/a | name = value |
---|
1985 | n/a | elif isinstance(value, tuple): |
---|
1986 | n/a | args = value |
---|
1987 | n/a | else: |
---|
1988 | n/a | kwargs = value |
---|
1989 | n/a | |
---|
1990 | n/a | if two: |
---|
1991 | n/a | return tuple.__new__(cls, (args, kwargs)) |
---|
1992 | n/a | |
---|
1993 | n/a | return tuple.__new__(cls, (name, args, kwargs)) |
---|
1994 | n/a | |
---|
1995 | n/a | |
---|
1996 | n/a | def __init__(self, value=(), name=None, parent=None, two=False, |
---|
1997 | n/a | from_kall=True): |
---|
1998 | n/a | self.name = name |
---|
1999 | n/a | self.parent = parent |
---|
2000 | n/a | self.from_kall = from_kall |
---|
2001 | n/a | |
---|
2002 | n/a | |
---|
2003 | n/a | def __eq__(self, other): |
---|
2004 | n/a | if other is ANY: |
---|
2005 | n/a | return True |
---|
2006 | n/a | try: |
---|
2007 | n/a | len_other = len(other) |
---|
2008 | n/a | except TypeError: |
---|
2009 | n/a | return False |
---|
2010 | n/a | |
---|
2011 | n/a | self_name = '' |
---|
2012 | n/a | if len(self) == 2: |
---|
2013 | n/a | self_args, self_kwargs = self |
---|
2014 | n/a | else: |
---|
2015 | n/a | self_name, self_args, self_kwargs = self |
---|
2016 | n/a | |
---|
2017 | n/a | other_name = '' |
---|
2018 | n/a | if len_other == 0: |
---|
2019 | n/a | other_args, other_kwargs = (), {} |
---|
2020 | n/a | elif len_other == 3: |
---|
2021 | n/a | other_name, other_args, other_kwargs = other |
---|
2022 | n/a | elif len_other == 1: |
---|
2023 | n/a | value, = other |
---|
2024 | n/a | if isinstance(value, tuple): |
---|
2025 | n/a | other_args = value |
---|
2026 | n/a | other_kwargs = {} |
---|
2027 | n/a | elif isinstance(value, str): |
---|
2028 | n/a | other_name = value |
---|
2029 | n/a | other_args, other_kwargs = (), {} |
---|
2030 | n/a | else: |
---|
2031 | n/a | other_args = () |
---|
2032 | n/a | other_kwargs = value |
---|
2033 | n/a | elif len_other == 2: |
---|
2034 | n/a | # could be (name, args) or (name, kwargs) or (args, kwargs) |
---|
2035 | n/a | first, second = other |
---|
2036 | n/a | if isinstance(first, str): |
---|
2037 | n/a | other_name = first |
---|
2038 | n/a | if isinstance(second, tuple): |
---|
2039 | n/a | other_args, other_kwargs = second, {} |
---|
2040 | n/a | else: |
---|
2041 | n/a | other_args, other_kwargs = (), second |
---|
2042 | n/a | else: |
---|
2043 | n/a | other_args, other_kwargs = first, second |
---|
2044 | n/a | else: |
---|
2045 | n/a | return False |
---|
2046 | n/a | |
---|
2047 | n/a | if self_name and other_name != self_name: |
---|
2048 | n/a | return False |
---|
2049 | n/a | |
---|
2050 | n/a | # this order is important for ANY to work! |
---|
2051 | n/a | return (other_args, other_kwargs) == (self_args, self_kwargs) |
---|
2052 | n/a | |
---|
2053 | n/a | |
---|
2054 | n/a | __ne__ = object.__ne__ |
---|
2055 | n/a | |
---|
2056 | n/a | |
---|
2057 | n/a | def __call__(self, *args, **kwargs): |
---|
2058 | n/a | if self.name is None: |
---|
2059 | n/a | return _Call(('', args, kwargs), name='()') |
---|
2060 | n/a | |
---|
2061 | n/a | name = self.name + '()' |
---|
2062 | n/a | return _Call((self.name, args, kwargs), name=name, parent=self) |
---|
2063 | n/a | |
---|
2064 | n/a | |
---|
2065 | n/a | def __getattr__(self, attr): |
---|
2066 | n/a | if self.name is None: |
---|
2067 | n/a | return _Call(name=attr, from_kall=False) |
---|
2068 | n/a | name = '%s.%s' % (self.name, attr) |
---|
2069 | n/a | return _Call(name=name, parent=self, from_kall=False) |
---|
2070 | n/a | |
---|
2071 | n/a | |
---|
2072 | n/a | def count(self, *args, **kwargs): |
---|
2073 | n/a | return self.__getattr__('count')(*args, **kwargs) |
---|
2074 | n/a | |
---|
2075 | n/a | def index(self, *args, **kwargs): |
---|
2076 | n/a | return self.__getattr__('index')(*args, **kwargs) |
---|
2077 | n/a | |
---|
2078 | n/a | def __repr__(self): |
---|
2079 | n/a | if not self.from_kall: |
---|
2080 | n/a | name = self.name or 'call' |
---|
2081 | n/a | if name.startswith('()'): |
---|
2082 | n/a | name = 'call%s' % name |
---|
2083 | n/a | return name |
---|
2084 | n/a | |
---|
2085 | n/a | if len(self) == 2: |
---|
2086 | n/a | name = 'call' |
---|
2087 | n/a | args, kwargs = self |
---|
2088 | n/a | else: |
---|
2089 | n/a | name, args, kwargs = self |
---|
2090 | n/a | if not name: |
---|
2091 | n/a | name = 'call' |
---|
2092 | n/a | elif not name.startswith('()'): |
---|
2093 | n/a | name = 'call.%s' % name |
---|
2094 | n/a | else: |
---|
2095 | n/a | name = 'call%s' % name |
---|
2096 | n/a | return _format_call_signature(name, args, kwargs) |
---|
2097 | n/a | |
---|
2098 | n/a | |
---|
2099 | n/a | def call_list(self): |
---|
2100 | n/a | """For a call object that represents multiple calls, `call_list` |
---|
2101 | n/a | returns a list of all the intermediate calls as well as the |
---|
2102 | n/a | final call.""" |
---|
2103 | n/a | vals = [] |
---|
2104 | n/a | thing = self |
---|
2105 | n/a | while thing is not None: |
---|
2106 | n/a | if thing.from_kall: |
---|
2107 | n/a | vals.append(thing) |
---|
2108 | n/a | thing = thing.parent |
---|
2109 | n/a | return _CallList(reversed(vals)) |
---|
2110 | n/a | |
---|
2111 | n/a | |
---|
2112 | n/a | call = _Call(from_kall=False) |
---|
2113 | n/a | |
---|
2114 | n/a | |
---|
2115 | n/a | |
---|
2116 | n/a | def create_autospec(spec, spec_set=False, instance=False, _parent=None, |
---|
2117 | n/a | _name=None, **kwargs): |
---|
2118 | n/a | """Create a mock object using another object as a spec. Attributes on the |
---|
2119 | n/a | mock will use the corresponding attribute on the `spec` object as their |
---|
2120 | n/a | spec. |
---|
2121 | n/a | |
---|
2122 | n/a | Functions or methods being mocked will have their arguments checked |
---|
2123 | n/a | to check that they are called with the correct signature. |
---|
2124 | n/a | |
---|
2125 | n/a | If `spec_set` is True then attempting to set attributes that don't exist |
---|
2126 | n/a | on the spec object will raise an `AttributeError`. |
---|
2127 | n/a | |
---|
2128 | n/a | If a class is used as a spec then the return value of the mock (the |
---|
2129 | n/a | instance of the class) will have the same spec. You can use a class as the |
---|
2130 | n/a | spec for an instance object by passing `instance=True`. The returned mock |
---|
2131 | n/a | will only be callable if instances of the mock are callable. |
---|
2132 | n/a | |
---|
2133 | n/a | `create_autospec` also takes arbitrary keyword arguments that are passed to |
---|
2134 | n/a | the constructor of the created mock.""" |
---|
2135 | n/a | if _is_list(spec): |
---|
2136 | n/a | # can't pass a list instance to the mock constructor as it will be |
---|
2137 | n/a | # interpreted as a list of strings |
---|
2138 | n/a | spec = type(spec) |
---|
2139 | n/a | |
---|
2140 | n/a | is_type = isinstance(spec, type) |
---|
2141 | n/a | |
---|
2142 | n/a | _kwargs = {'spec': spec} |
---|
2143 | n/a | if spec_set: |
---|
2144 | n/a | _kwargs = {'spec_set': spec} |
---|
2145 | n/a | elif spec is None: |
---|
2146 | n/a | # None we mock with a normal mock without a spec |
---|
2147 | n/a | _kwargs = {} |
---|
2148 | n/a | if _kwargs and instance: |
---|
2149 | n/a | _kwargs['_spec_as_instance'] = True |
---|
2150 | n/a | |
---|
2151 | n/a | _kwargs.update(kwargs) |
---|
2152 | n/a | |
---|
2153 | n/a | Klass = MagicMock |
---|
2154 | n/a | if inspect.isdatadescriptor(spec): |
---|
2155 | n/a | # descriptors don't have a spec |
---|
2156 | n/a | # because we don't know what type they return |
---|
2157 | n/a | _kwargs = {} |
---|
2158 | n/a | elif not _callable(spec): |
---|
2159 | n/a | Klass = NonCallableMagicMock |
---|
2160 | n/a | elif is_type and instance and not _instance_callable(spec): |
---|
2161 | n/a | Klass = NonCallableMagicMock |
---|
2162 | n/a | |
---|
2163 | n/a | _name = _kwargs.pop('name', _name) |
---|
2164 | n/a | |
---|
2165 | n/a | _new_name = _name |
---|
2166 | n/a | if _parent is None: |
---|
2167 | n/a | # for a top level object no _new_name should be set |
---|
2168 | n/a | _new_name = '' |
---|
2169 | n/a | |
---|
2170 | n/a | mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, |
---|
2171 | n/a | name=_name, **_kwargs) |
---|
2172 | n/a | |
---|
2173 | n/a | if isinstance(spec, FunctionTypes): |
---|
2174 | n/a | # should only happen at the top level because we don't |
---|
2175 | n/a | # recurse for functions |
---|
2176 | n/a | mock = _set_signature(mock, spec) |
---|
2177 | n/a | else: |
---|
2178 | n/a | _check_signature(spec, mock, is_type, instance) |
---|
2179 | n/a | |
---|
2180 | n/a | if _parent is not None and not instance: |
---|
2181 | n/a | _parent._mock_children[_name] = mock |
---|
2182 | n/a | |
---|
2183 | n/a | if is_type and not instance and 'return_value' not in kwargs: |
---|
2184 | n/a | mock.return_value = create_autospec(spec, spec_set, instance=True, |
---|
2185 | n/a | _name='()', _parent=mock) |
---|
2186 | n/a | |
---|
2187 | n/a | for entry in dir(spec): |
---|
2188 | n/a | if _is_magic(entry): |
---|
2189 | n/a | # MagicMock already does the useful magic methods for us |
---|
2190 | n/a | continue |
---|
2191 | n/a | |
---|
2192 | n/a | # XXXX do we need a better way of getting attributes without |
---|
2193 | n/a | # triggering code execution (?) Probably not - we need the actual |
---|
2194 | n/a | # object to mock it so we would rather trigger a property than mock |
---|
2195 | n/a | # the property descriptor. Likewise we want to mock out dynamically |
---|
2196 | n/a | # provided attributes. |
---|
2197 | n/a | # XXXX what about attributes that raise exceptions other than |
---|
2198 | n/a | # AttributeError on being fetched? |
---|
2199 | n/a | # we could be resilient against it, or catch and propagate the |
---|
2200 | n/a | # exception when the attribute is fetched from the mock |
---|
2201 | n/a | try: |
---|
2202 | n/a | original = getattr(spec, entry) |
---|
2203 | n/a | except AttributeError: |
---|
2204 | n/a | continue |
---|
2205 | n/a | |
---|
2206 | n/a | kwargs = {'spec': original} |
---|
2207 | n/a | if spec_set: |
---|
2208 | n/a | kwargs = {'spec_set': original} |
---|
2209 | n/a | |
---|
2210 | n/a | if not isinstance(original, FunctionTypes): |
---|
2211 | n/a | new = _SpecState(original, spec_set, mock, entry, instance) |
---|
2212 | n/a | mock._mock_children[entry] = new |
---|
2213 | n/a | else: |
---|
2214 | n/a | parent = mock |
---|
2215 | n/a | if isinstance(spec, FunctionTypes): |
---|
2216 | n/a | parent = mock.mock |
---|
2217 | n/a | |
---|
2218 | n/a | skipfirst = _must_skip(spec, entry, is_type) |
---|
2219 | n/a | kwargs['_eat_self'] = skipfirst |
---|
2220 | n/a | new = MagicMock(parent=parent, name=entry, _new_name=entry, |
---|
2221 | n/a | _new_parent=parent, |
---|
2222 | n/a | **kwargs) |
---|
2223 | n/a | mock._mock_children[entry] = new |
---|
2224 | n/a | _check_signature(original, new, skipfirst=skipfirst) |
---|
2225 | n/a | |
---|
2226 | n/a | # so functions created with _set_signature become instance attributes, |
---|
2227 | n/a | # *plus* their underlying mock exists in _mock_children of the parent |
---|
2228 | n/a | # mock. Adding to _mock_children may be unnecessary where we are also |
---|
2229 | n/a | # setting as an instance attribute? |
---|
2230 | n/a | if isinstance(new, FunctionTypes): |
---|
2231 | n/a | setattr(mock, entry, new) |
---|
2232 | n/a | |
---|
2233 | n/a | return mock |
---|
2234 | n/a | |
---|
2235 | n/a | |
---|
2236 | n/a | def _must_skip(spec, entry, is_type): |
---|
2237 | n/a | """ |
---|
2238 | n/a | Return whether we should skip the first argument on spec's `entry` |
---|
2239 | n/a | attribute. |
---|
2240 | n/a | """ |
---|
2241 | n/a | if not isinstance(spec, type): |
---|
2242 | n/a | if entry in getattr(spec, '__dict__', {}): |
---|
2243 | n/a | # instance attribute - shouldn't skip |
---|
2244 | n/a | return False |
---|
2245 | n/a | spec = spec.__class__ |
---|
2246 | n/a | |
---|
2247 | n/a | for klass in spec.__mro__: |
---|
2248 | n/a | result = klass.__dict__.get(entry, DEFAULT) |
---|
2249 | n/a | if result is DEFAULT: |
---|
2250 | n/a | continue |
---|
2251 | n/a | if isinstance(result, (staticmethod, classmethod)): |
---|
2252 | n/a | return False |
---|
2253 | n/a | elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes): |
---|
2254 | n/a | # Normal method => skip if looked up on type |
---|
2255 | n/a | # (if looked up on instance, self is already skipped) |
---|
2256 | n/a | return is_type |
---|
2257 | n/a | else: |
---|
2258 | n/a | return False |
---|
2259 | n/a | |
---|
2260 | n/a | # shouldn't get here unless function is a dynamically provided attribute |
---|
2261 | n/a | # XXXX untested behaviour |
---|
2262 | n/a | return is_type |
---|
2263 | n/a | |
---|
2264 | n/a | |
---|
2265 | n/a | def _get_class(obj): |
---|
2266 | n/a | try: |
---|
2267 | n/a | return obj.__class__ |
---|
2268 | n/a | except AttributeError: |
---|
2269 | n/a | # it is possible for objects to have no __class__ |
---|
2270 | n/a | return type(obj) |
---|
2271 | n/a | |
---|
2272 | n/a | |
---|
2273 | n/a | class _SpecState(object): |
---|
2274 | n/a | |
---|
2275 | n/a | def __init__(self, spec, spec_set=False, parent=None, |
---|
2276 | n/a | name=None, ids=None, instance=False): |
---|
2277 | n/a | self.spec = spec |
---|
2278 | n/a | self.ids = ids |
---|
2279 | n/a | self.spec_set = spec_set |
---|
2280 | n/a | self.parent = parent |
---|
2281 | n/a | self.instance = instance |
---|
2282 | n/a | self.name = name |
---|
2283 | n/a | |
---|
2284 | n/a | |
---|
2285 | n/a | FunctionTypes = ( |
---|
2286 | n/a | # python function |
---|
2287 | n/a | type(create_autospec), |
---|
2288 | n/a | # instance method |
---|
2289 | n/a | type(ANY.__eq__), |
---|
2290 | n/a | ) |
---|
2291 | n/a | |
---|
2292 | n/a | MethodWrapperTypes = ( |
---|
2293 | n/a | type(ANY.__eq__.__get__), |
---|
2294 | n/a | ) |
---|
2295 | n/a | |
---|
2296 | n/a | |
---|
2297 | n/a | file_spec = None |
---|
2298 | n/a | |
---|
2299 | n/a | def _iterate_read_data(read_data): |
---|
2300 | n/a | # Helper for mock_open: |
---|
2301 | n/a | # Retrieve lines from read_data via a generator so that separate calls to |
---|
2302 | n/a | # readline, read, and readlines are properly interleaved |
---|
2303 | n/a | sep = b'\n' if isinstance(read_data, bytes) else '\n' |
---|
2304 | n/a | data_as_list = [l + sep for l in read_data.split(sep)] |
---|
2305 | n/a | |
---|
2306 | n/a | if data_as_list[-1] == sep: |
---|
2307 | n/a | # If the last line ended in a newline, the list comprehension will have an |
---|
2308 | n/a | # extra entry that's just a newline. Remove this. |
---|
2309 | n/a | data_as_list = data_as_list[:-1] |
---|
2310 | n/a | else: |
---|
2311 | n/a | # If there wasn't an extra newline by itself, then the file being |
---|
2312 | n/a | # emulated doesn't have a newline to end the last line remove the |
---|
2313 | n/a | # newline that our naive format() added |
---|
2314 | n/a | data_as_list[-1] = data_as_list[-1][:-1] |
---|
2315 | n/a | |
---|
2316 | n/a | for line in data_as_list: |
---|
2317 | n/a | yield line |
---|
2318 | n/a | |
---|
2319 | n/a | |
---|
2320 | n/a | def mock_open(mock=None, read_data=''): |
---|
2321 | n/a | """ |
---|
2322 | n/a | A helper function to create a mock to replace the use of `open`. It works |
---|
2323 | n/a | for `open` called directly or used as a context manager. |
---|
2324 | n/a | |
---|
2325 | n/a | The `mock` argument is the mock object to configure. If `None` (the |
---|
2326 | n/a | default) then a `MagicMock` will be created for you, with the API limited |
---|
2327 | n/a | to methods or attributes available on standard file handles. |
---|
2328 | n/a | |
---|
2329 | n/a | `read_data` is a string for the `read` methoddline`, and `readlines` of the |
---|
2330 | n/a | file handle to return. This is an empty string by default. |
---|
2331 | n/a | """ |
---|
2332 | n/a | def _readlines_side_effect(*args, **kwargs): |
---|
2333 | n/a | if handle.readlines.return_value is not None: |
---|
2334 | n/a | return handle.readlines.return_value |
---|
2335 | n/a | return list(_state[0]) |
---|
2336 | n/a | |
---|
2337 | n/a | def _read_side_effect(*args, **kwargs): |
---|
2338 | n/a | if handle.read.return_value is not None: |
---|
2339 | n/a | return handle.read.return_value |
---|
2340 | n/a | return type(read_data)().join(_state[0]) |
---|
2341 | n/a | |
---|
2342 | n/a | def _readline_side_effect(): |
---|
2343 | n/a | if handle.readline.return_value is not None: |
---|
2344 | n/a | while True: |
---|
2345 | n/a | yield handle.readline.return_value |
---|
2346 | n/a | for line in _state[0]: |
---|
2347 | n/a | yield line |
---|
2348 | n/a | while True: |
---|
2349 | n/a | yield type(read_data)() |
---|
2350 | n/a | |
---|
2351 | n/a | |
---|
2352 | n/a | global file_spec |
---|
2353 | n/a | if file_spec is None: |
---|
2354 | n/a | import _io |
---|
2355 | n/a | file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) |
---|
2356 | n/a | |
---|
2357 | n/a | if mock is None: |
---|
2358 | n/a | mock = MagicMock(name='open', spec=open) |
---|
2359 | n/a | |
---|
2360 | n/a | handle = MagicMock(spec=file_spec) |
---|
2361 | n/a | handle.__enter__.return_value = handle |
---|
2362 | n/a | |
---|
2363 | n/a | _state = [_iterate_read_data(read_data), None] |
---|
2364 | n/a | |
---|
2365 | n/a | handle.write.return_value = None |
---|
2366 | n/a | handle.read.return_value = None |
---|
2367 | n/a | handle.readline.return_value = None |
---|
2368 | n/a | handle.readlines.return_value = None |
---|
2369 | n/a | |
---|
2370 | n/a | handle.read.side_effect = _read_side_effect |
---|
2371 | n/a | _state[1] = _readline_side_effect() |
---|
2372 | n/a | handle.readline.side_effect = _state[1] |
---|
2373 | n/a | handle.readlines.side_effect = _readlines_side_effect |
---|
2374 | n/a | |
---|
2375 | n/a | def reset_data(*args, **kwargs): |
---|
2376 | n/a | _state[0] = _iterate_read_data(read_data) |
---|
2377 | n/a | if handle.readline.side_effect == _state[1]: |
---|
2378 | n/a | # Only reset the side effect if the user hasn't overridden it. |
---|
2379 | n/a | _state[1] = _readline_side_effect() |
---|
2380 | n/a | handle.readline.side_effect = _state[1] |
---|
2381 | n/a | return DEFAULT |
---|
2382 | n/a | |
---|
2383 | n/a | mock.side_effect = reset_data |
---|
2384 | n/a | mock.return_value = handle |
---|
2385 | n/a | return mock |
---|
2386 | n/a | |
---|
2387 | n/a | |
---|
2388 | n/a | class PropertyMock(Mock): |
---|
2389 | n/a | """ |
---|
2390 | n/a | A mock intended to be used as a property, or other descriptor, on a class. |
---|
2391 | n/a | `PropertyMock` provides `__get__` and `__set__` methods so you can specify |
---|
2392 | n/a | a return value when it is fetched. |
---|
2393 | n/a | |
---|
2394 | n/a | Fetching a `PropertyMock` instance from an object calls the mock, with |
---|
2395 | n/a | no args. Setting it calls the mock with the value being set. |
---|
2396 | n/a | """ |
---|
2397 | n/a | def _get_child_mock(self, **kwargs): |
---|
2398 | n/a | return MagicMock(**kwargs) |
---|
2399 | n/a | |
---|
2400 | n/a | def __get__(self, obj, obj_type): |
---|
2401 | n/a | return self() |
---|
2402 | n/a | def __set__(self, obj, val): |
---|
2403 | n/a | self(val) |
---|