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