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