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