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