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