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