python/mock-1.0.0/mock.py

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

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

mercurial