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