mock.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. The Mock Class
  2. ==============
  3. .. currentmodule:: mock
  4. .. testsetup::
  5. class SomeClass:
  6. pass
  7. `Mock` is a flexible mock object intended to replace the use of stubs and
  8. test doubles throughout your code. Mocks are callable and create attributes as
  9. new mocks when you access them [#]_. Accessing the same attribute will always
  10. return the same mock. Mocks record how you use them, allowing you to make
  11. assertions about what your code has done to them.
  12. :class:`MagicMock` is a subclass of `Mock` with all the magic methods
  13. pre-created and ready to use. There are also non-callable variants, useful
  14. when you are mocking out objects that aren't callable:
  15. :class:`NonCallableMock` and :class:`NonCallableMagicMock`
  16. The :func:`patch` decorators makes it easy to temporarily replace classes
  17. in a particular module with a `Mock` object. By default `patch` will create
  18. a `MagicMock` for you. You can specify an alternative class of `Mock` using
  19. the `new_callable` argument to `patch`.
  20. .. index:: side_effect
  21. .. index:: return_value
  22. .. index:: wraps
  23. .. index:: name
  24. .. index:: spec
  25. .. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, **kwargs)
  26. Create a new `Mock` object. `Mock` takes several optional arguments
  27. that specify the behaviour of the Mock object:
  28. * `spec`: This can be either a list of strings or an existing object (a
  29. class or instance) that acts as the specification for the mock object. If
  30. you pass in an object then a list of strings is formed by calling dir on
  31. the object (excluding unsupported magic attributes and methods).
  32. Accessing any attribute not in this list will raise an `AttributeError`.
  33. If `spec` is an object (rather than a list of strings) then
  34. :attr:`__class__` returns the class of the spec object. This allows mocks
  35. to pass `isinstance` tests.
  36. * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
  37. or get an attribute on the mock that isn't on the object passed as
  38. `spec_set` will raise an `AttributeError`.
  39. * `side_effect`: A function to be called whenever the Mock is called. See
  40. the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
  41. dynamically changing return values. The function is called with the same
  42. arguments as the mock, and unless it returns :data:`DEFAULT`, the return
  43. value of this function is used as the return value.
  44. Alternatively `side_effect` can be an exception class or instance. In
  45. this case the exception will be raised when the mock is called.
  46. If `side_effect` is an iterable then each call to the mock will return
  47. the next value from the iterable. If any of the members of the iterable
  48. are exceptions they will be raised instead of returned.
  49. A `side_effect` can be cleared by setting it to `None`.
  50. * `return_value`: The value returned when the mock is called. By default
  51. this is a new Mock (created on first access). See the
  52. :attr:`return_value` attribute.
  53. * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
  54. calling the Mock will pass the call through to the wrapped object
  55. (returning the real result and ignoring `return_value`). Attribute access
  56. on the mock will return a Mock object that wraps the corresponding
  57. attribute of the wrapped object (so attempting to access an attribute
  58. that doesn't exist will raise an `AttributeError`).
  59. If the mock has an explicit `return_value` set then calls are not passed
  60. to the wrapped object and the `return_value` is returned instead.
  61. * `name`: If the mock has a name then it will be used in the repr of the
  62. mock. This can be useful for debugging. The name is propagated to child
  63. mocks.
  64. Mocks can also be called with arbitrary keyword arguments. These will be
  65. used to set attributes on the mock after it is created. See the
  66. :meth:`configure_mock` method for details.
  67. .. method:: assert_called_with(*args, **kwargs)
  68. This method is a convenient way of asserting that calls are made in a
  69. particular way:
  70. .. doctest::
  71. >>> mock = Mock()
  72. >>> mock.method(1, 2, 3, test='wow')
  73. <Mock name='mock.method()' id='...'>
  74. >>> mock.method.assert_called_with(1, 2, 3, test='wow')
  75. .. method:: assert_called_once_with(*args, **kwargs)
  76. Assert that the mock was called exactly once and with the specified
  77. arguments.
  78. .. doctest::
  79. >>> mock = Mock(return_value=None)
  80. >>> mock('foo', bar='baz')
  81. >>> mock.assert_called_once_with('foo', bar='baz')
  82. >>> mock('foo', bar='baz')
  83. >>> mock.assert_called_once_with('foo', bar='baz')
  84. Traceback (most recent call last):
  85. ...
  86. AssertionError: Expected to be called once. Called 2 times.
  87. .. method:: assert_any_call(*args, **kwargs)
  88. assert the mock has been called with the specified arguments.
  89. The assert passes if the mock has *ever* been called, unlike
  90. :meth:`assert_called_with` and :meth:`assert_called_once_with` that
  91. only pass if the call is the most recent one.
  92. .. doctest::
  93. >>> mock = Mock(return_value=None)
  94. >>> mock(1, 2, arg='thing')
  95. >>> mock('some', 'thing', 'else')
  96. >>> mock.assert_any_call(1, 2, arg='thing')
  97. .. method:: assert_has_calls(calls, any_order=False)
  98. assert the mock has been called with the specified calls.
  99. The `mock_calls` list is checked for the calls.
  100. If `any_order` is False (the default) then the calls must be
  101. sequential. There can be extra calls before or after the
  102. specified calls.
  103. If `any_order` is True then the calls can be in any order, but
  104. they must all appear in :attr:`mock_calls`.
  105. .. doctest::
  106. >>> mock = Mock(return_value=None)
  107. >>> mock(1)
  108. >>> mock(2)
  109. >>> mock(3)
  110. >>> mock(4)
  111. >>> calls = [call(2), call(3)]
  112. >>> mock.assert_has_calls(calls)
  113. >>> calls = [call(4), call(2), call(3)]
  114. >>> mock.assert_has_calls(calls, any_order=True)
  115. .. method:: reset_mock()
  116. The reset_mock method resets all the call attributes on a mock object:
  117. .. doctest::
  118. >>> mock = Mock(return_value=None)
  119. >>> mock('hello')
  120. >>> mock.called
  121. True
  122. >>> mock.reset_mock()
  123. >>> mock.called
  124. False
  125. This can be useful where you want to make a series of assertions that
  126. reuse the same object. Note that `reset_mock` *doesn't* clear the
  127. return value, :attr:`side_effect` or any child attributes you have
  128. set using normal assignment. Child mocks and the return value mock
  129. (if any) are reset as well.
  130. .. method:: mock_add_spec(spec, spec_set=False)
  131. Add a spec to a mock. `spec` can either be an object or a
  132. list of strings. Only attributes on the `spec` can be fetched as
  133. attributes from the mock.
  134. If `spec_set` is `True` then only attributes on the spec can be set.
  135. .. method:: attach_mock(mock, attribute)
  136. Attach a mock as an attribute of this one, replacing its name and
  137. parent. Calls to the attached mock will be recorded in the
  138. :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
  139. .. method:: configure_mock(**kwargs)
  140. Set attributes on the mock through keyword arguments.
  141. Attributes plus return values and side effects can be set on child
  142. mocks using standard dot notation and unpacking a dictionary in the
  143. method call:
  144. .. doctest::
  145. >>> mock = Mock()
  146. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
  147. >>> mock.configure_mock(**attrs)
  148. >>> mock.method()
  149. 3
  150. >>> mock.other()
  151. Traceback (most recent call last):
  152. ...
  153. KeyError
  154. The same thing can be achieved in the constructor call to mocks:
  155. .. doctest::
  156. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
  157. >>> mock = Mock(some_attribute='eggs', **attrs)
  158. >>> mock.some_attribute
  159. 'eggs'
  160. >>> mock.method()
  161. 3
  162. >>> mock.other()
  163. Traceback (most recent call last):
  164. ...
  165. KeyError
  166. `configure_mock` exists to make it easier to do configuration
  167. after the mock has been created.
  168. .. method:: __dir__()
  169. `Mock` objects limit the results of `dir(some_mock)` to useful results.
  170. For mocks with a `spec` this includes all the permitted attributes
  171. for the mock.
  172. See :data:`FILTER_DIR` for what this filtering does, and how to
  173. switch it off.
  174. .. method:: _get_child_mock(**kw)
  175. Create the child mocks for attributes and return value.
  176. By default child mocks will be the same type as the parent.
  177. Subclasses of Mock may want to override this to customize the way
  178. child mocks are made.
  179. For non-callable mocks the callable variant will be used (rather than
  180. any custom subclass).
  181. .. attribute:: called
  182. A boolean representing whether or not the mock object has been called:
  183. .. doctest::
  184. >>> mock = Mock(return_value=None)
  185. >>> mock.called
  186. False
  187. >>> mock()
  188. >>> mock.called
  189. True
  190. .. attribute:: call_count
  191. An integer telling you how many times the mock object has been called:
  192. .. doctest::
  193. >>> mock = Mock(return_value=None)
  194. >>> mock.call_count
  195. 0
  196. >>> mock()
  197. >>> mock()
  198. >>> mock.call_count
  199. 2
  200. .. attribute:: return_value
  201. Set this to configure the value returned by calling the mock:
  202. .. doctest::
  203. >>> mock = Mock()
  204. >>> mock.return_value = 'fish'
  205. >>> mock()
  206. 'fish'
  207. The default return value is a mock object and you can configure it in
  208. the normal way:
  209. .. doctest::
  210. >>> mock = Mock()
  211. >>> mock.return_value.attribute = sentinel.Attribute
  212. >>> mock.return_value()
  213. <Mock name='mock()()' id='...'>
  214. >>> mock.return_value.assert_called_with()
  215. `return_value` can also be set in the constructor:
  216. .. doctest::
  217. >>> mock = Mock(return_value=3)
  218. >>> mock.return_value
  219. 3
  220. >>> mock()
  221. 3
  222. .. attribute:: side_effect
  223. This can either be a function to be called when the mock is called,
  224. or an exception (class or instance) to be raised.
  225. If you pass in a function it will be called with same arguments as the
  226. mock and unless the function returns the :data:`DEFAULT` singleton the
  227. call to the mock will then return whatever the function returns. If the
  228. function returns :data:`DEFAULT` then the mock will return its normal
  229. value (from the :attr:`return_value`.
  230. An example of a mock that raises an exception (to test exception
  231. handling of an API):
  232. .. doctest::
  233. >>> mock = Mock()
  234. >>> mock.side_effect = Exception('Boom!')
  235. >>> mock()
  236. Traceback (most recent call last):
  237. ...
  238. Exception: Boom!
  239. Using `side_effect` to return a sequence of values:
  240. .. doctest::
  241. >>> mock = Mock()
  242. >>> mock.side_effect = [3, 2, 1]
  243. >>> mock(), mock(), mock()
  244. (3, 2, 1)
  245. The `side_effect` function is called with the same arguments as the
  246. mock (so it is wise for it to take arbitrary args and keyword
  247. arguments) and whatever it returns is used as the return value for
  248. the call. The exception is if `side_effect` returns :data:`DEFAULT`,
  249. in which case the normal :attr:`return_value` is used.
  250. .. doctest::
  251. >>> mock = Mock(return_value=3)
  252. >>> def side_effect(*args, **kwargs):
  253. ... return DEFAULT
  254. ...
  255. >>> mock.side_effect = side_effect
  256. >>> mock()
  257. 3
  258. `side_effect` can be set in the constructor. Here's an example that
  259. adds one to the value the mock is called with and returns it:
  260. .. doctest::
  261. >>> side_effect = lambda value: value + 1
  262. >>> mock = Mock(side_effect=side_effect)
  263. >>> mock(3)
  264. 4
  265. >>> mock(-8)
  266. -7
  267. Setting `side_effect` to `None` clears it:
  268. .. doctest::
  269. >>> from mock import Mock
  270. >>> m = Mock(side_effect=KeyError, return_value=3)
  271. >>> m()
  272. Traceback (most recent call last):
  273. ...
  274. KeyError
  275. >>> m.side_effect = None
  276. >>> m()
  277. 3
  278. .. attribute:: call_args
  279. This is either `None` (if the mock hasn't been called), or the
  280. arguments that the mock was last called with. This will be in the
  281. form of a tuple: the first member is any ordered arguments the mock
  282. was called with (or an empty tuple) and the second member is any
  283. keyword arguments (or an empty dictionary).
  284. .. doctest::
  285. >>> mock = Mock(return_value=None)
  286. >>> print mock.call_args
  287. None
  288. >>> mock()
  289. >>> mock.call_args
  290. call()
  291. >>> mock.call_args == ()
  292. True
  293. >>> mock(3, 4)
  294. >>> mock.call_args
  295. call(3, 4)
  296. >>> mock.call_args == ((3, 4),)
  297. True
  298. >>> mock(3, 4, 5, key='fish', next='w00t!')
  299. >>> mock.call_args
  300. call(3, 4, 5, key='fish', next='w00t!')
  301. `call_args`, along with members of the lists :attr:`call_args_list`,
  302. :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
  303. These are tuples, so they can be unpacked to get at the individual
  304. arguments and make more complex assertions. See
  305. :ref:`calls as tuples <calls-as-tuples>`.
  306. .. attribute:: call_args_list
  307. This is a list of all the calls made to the mock object in sequence
  308. (so the length of the list is the number of times it has been
  309. called). Before any calls have been made it is an empty list. The
  310. :data:`call` object can be used for conveniently constructing lists of
  311. calls to compare with `call_args_list`.
  312. .. doctest::
  313. >>> mock = Mock(return_value=None)
  314. >>> mock()
  315. >>> mock(3, 4)
  316. >>> mock(key='fish', next='w00t!')
  317. >>> mock.call_args_list
  318. [call(), call(3, 4), call(key='fish', next='w00t!')]
  319. >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
  320. >>> mock.call_args_list == expected
  321. True
  322. Members of `call_args_list` are :data:`call` objects. These can be
  323. unpacked as tuples to get at the individual arguments. See
  324. :ref:`calls as tuples <calls-as-tuples>`.
  325. .. attribute:: method_calls
  326. As well as tracking calls to themselves, mocks also track calls to
  327. methods and attributes, and *their* methods and attributes:
  328. .. doctest::
  329. >>> mock = Mock()
  330. >>> mock.method()
  331. <Mock name='mock.method()' id='...'>
  332. >>> mock.property.method.attribute()
  333. <Mock name='mock.property.method.attribute()' id='...'>
  334. >>> mock.method_calls
  335. [call.method(), call.property.method.attribute()]
  336. Members of `method_calls` are :data:`call` objects. These can be
  337. unpacked as tuples to get at the individual arguments. See
  338. :ref:`calls as tuples <calls-as-tuples>`.
  339. .. attribute:: mock_calls
  340. `mock_calls` records *all* calls to the mock object, its methods, magic
  341. methods *and* return value mocks.
  342. .. doctest::
  343. >>> mock = MagicMock()
  344. >>> result = mock(1, 2, 3)
  345. >>> mock.first(a=3)
  346. <MagicMock name='mock.first()' id='...'>
  347. >>> mock.second()
  348. <MagicMock name='mock.second()' id='...'>
  349. >>> int(mock)
  350. 1
  351. >>> result(1)
  352. <MagicMock name='mock()()' id='...'>
  353. >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
  354. ... call.__int__(), call()(1)]
  355. >>> mock.mock_calls == expected
  356. True
  357. Members of `mock_calls` are :data:`call` objects. These can be
  358. unpacked as tuples to get at the individual arguments. See
  359. :ref:`calls as tuples <calls-as-tuples>`.
  360. .. attribute:: __class__
  361. Normally the `__class__` attribute of an object will return its type.
  362. For a mock object with a `spec` `__class__` returns the spec class
  363. instead. This allows mock objects to pass `isinstance` tests for the
  364. object they are replacing / masquerading as:
  365. .. doctest::
  366. >>> mock = Mock(spec=3)
  367. >>> isinstance(mock, int)
  368. True
  369. `__class__` is assignable to, this allows a mock to pass an
  370. `isinstance` check without forcing you to use a spec:
  371. .. doctest::
  372. >>> mock = Mock()
  373. >>> mock.__class__ = dict
  374. >>> isinstance(mock, dict)
  375. True
  376. .. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
  377. A non-callable version of `Mock`. The constructor parameters have the same
  378. meaning of `Mock`, with the exception of `return_value` and `side_effect`
  379. which have no meaning on a non-callable mock.
  380. Mock objects that use a class or an instance as a `spec` or `spec_set` are able
  381. to pass `isintance` tests:
  382. .. doctest::
  383. >>> mock = Mock(spec=SomeClass)
  384. >>> isinstance(mock, SomeClass)
  385. True
  386. >>> mock = Mock(spec_set=SomeClass())
  387. >>> isinstance(mock, SomeClass)
  388. True
  389. The `Mock` classes have support for mocking magic methods. See :ref:`magic
  390. methods <magic-methods>` for the full details.
  391. The mock classes and the :func:`patch` decorators all take arbitrary keyword
  392. arguments for configuration. For the `patch` decorators the keywords are
  393. passed to the constructor of the mock being created. The keyword arguments
  394. are for configuring attributes of the mock:
  395. .. doctest::
  396. >>> m = MagicMock(attribute=3, other='fish')
  397. >>> m.attribute
  398. 3
  399. >>> m.other
  400. 'fish'
  401. The return value and side effect of child mocks can be set in the same way,
  402. using dotted notation. As you can't use dotted names directly in a call you
  403. have to create a dictionary and unpack it using `**`:
  404. .. doctest::
  405. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
  406. >>> mock = Mock(some_attribute='eggs', **attrs)
  407. >>> mock.some_attribute
  408. 'eggs'
  409. >>> mock.method()
  410. 3
  411. >>> mock.other()
  412. Traceback (most recent call last):
  413. ...
  414. KeyError
  415. .. class:: PropertyMock(*args, **kwargs)
  416. A mock intended to be used as a property, or other descriptor, on a class.
  417. `PropertyMock` provides `__get__` and `__set__` methods so you can specify
  418. a return value when it is fetched.
  419. Fetching a `PropertyMock` instance from an object calls the mock, with
  420. no args. Setting it calls the mock with the value being set.
  421. .. doctest::
  422. >>> class Foo(object):
  423. ... @property
  424. ... def foo(self):
  425. ... return 'something'
  426. ... @foo.setter
  427. ... def foo(self, value):
  428. ... pass
  429. ...
  430. >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
  431. ... mock_foo.return_value = 'mockity-mock'
  432. ... this_foo = Foo()
  433. ... print this_foo.foo
  434. ... this_foo.foo = 6
  435. ...
  436. mockity-mock
  437. >>> mock_foo.mock_calls
  438. [call(), call(6)]
  439. Because of the way mock attributes are stored you can't directly attach a
  440. `PropertyMock` to a mock object. Instead you can attach it to the mock type
  441. object:
  442. .. doctest::
  443. >>> m = MagicMock()
  444. >>> p = PropertyMock(return_value=3)
  445. >>> type(m).foo = p
  446. >>> m.foo
  447. 3
  448. >>> p.assert_called_once_with()
  449. .. index:: __call__
  450. .. index:: calling
  451. Calling
  452. =======
  453. Mock objects are callable. The call will return the value set as the
  454. :attr:`~Mock.return_value` attribute. The default return value is a new Mock
  455. object; it is created the first time the return value is accessed (either
  456. explicitly or by calling the Mock) - but it is stored and the same one
  457. returned each time.
  458. Calls made to the object will be recorded in the attributes
  459. like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
  460. If :attr:`~Mock.side_effect` is set then it will be called after the call has
  461. been recorded, so if `side_effect` raises an exception the call is still
  462. recorded.
  463. The simplest way to make a mock raise an exception when called is to make
  464. :attr:`~Mock.side_effect` an exception class or instance:
  465. .. doctest::
  466. >>> m = MagicMock(side_effect=IndexError)
  467. >>> m(1, 2, 3)
  468. Traceback (most recent call last):
  469. ...
  470. IndexError
  471. >>> m.mock_calls
  472. [call(1, 2, 3)]
  473. >>> m.side_effect = KeyError('Bang!')
  474. >>> m('two', 'three', 'four')
  475. Traceback (most recent call last):
  476. ...
  477. KeyError: 'Bang!'
  478. >>> m.mock_calls
  479. [call(1, 2, 3), call('two', 'three', 'four')]
  480. If `side_effect` is a function then whatever that function returns is what
  481. calls to the mock return. The `side_effect` function is called with the
  482. same arguments as the mock. This allows you to vary the return value of the
  483. call dynamically, based on the input:
  484. .. doctest::
  485. >>> def side_effect(value):
  486. ... return value + 1
  487. ...
  488. >>> m = MagicMock(side_effect=side_effect)
  489. >>> m(1)
  490. 2
  491. >>> m(2)
  492. 3
  493. >>> m.mock_calls
  494. [call(1), call(2)]
  495. If you want the mock to still return the default return value (a new mock), or
  496. any set return value, then there are two ways of doing this. Either return
  497. `mock.return_value` from inside `side_effect`, or return :data:`DEFAULT`:
  498. .. doctest::
  499. >>> m = MagicMock()
  500. >>> def side_effect(*args, **kwargs):
  501. ... return m.return_value
  502. ...
  503. >>> m.side_effect = side_effect
  504. >>> m.return_value = 3
  505. >>> m()
  506. 3
  507. >>> def side_effect(*args, **kwargs):
  508. ... return DEFAULT
  509. ...
  510. >>> m.side_effect = side_effect
  511. >>> m()
  512. 3
  513. To remove a `side_effect`, and return to the default behaviour, set the
  514. `side_effect` to `None`:
  515. .. doctest::
  516. >>> m = MagicMock(return_value=6)
  517. >>> def side_effect(*args, **kwargs):
  518. ... return 3
  519. ...
  520. >>> m.side_effect = side_effect
  521. >>> m()
  522. 3
  523. >>> m.side_effect = None
  524. >>> m()
  525. 6
  526. The `side_effect` can also be any iterable object. Repeated calls to the mock
  527. will return values from the iterable (until the iterable is exhausted and
  528. a `StopIteration` is raised):
  529. .. doctest::
  530. >>> m = MagicMock(side_effect=[1, 2, 3])
  531. >>> m()
  532. 1
  533. >>> m()
  534. 2
  535. >>> m()
  536. 3
  537. >>> m()
  538. Traceback (most recent call last):
  539. ...
  540. StopIteration
  541. If any members of the iterable are exceptions they will be raised instead of
  542. returned:
  543. .. doctest::
  544. >>> iterable = (33, ValueError, 66)
  545. >>> m = MagicMock(side_effect=iterable)
  546. >>> m()
  547. 33
  548. >>> m()
  549. Traceback (most recent call last):
  550. ...
  551. ValueError
  552. >>> m()
  553. 66
  554. .. _deleting-attributes:
  555. Deleting Attributes
  556. ===================
  557. Mock objects create attributes on demand. This allows them to pretend to be
  558. objects of any type.
  559. You may want a mock object to return `False` to a `hasattr` call, or raise an
  560. `AttributeError` when an attribute is fetched. You can do this by providing
  561. an object as a `spec` for a mock, but that isn't always convenient.
  562. You "block" attributes by deleting them. Once deleted, accessing an attribute
  563. will raise an `AttributeError`.
  564. .. doctest::
  565. >>> mock = MagicMock()
  566. >>> hasattr(mock, 'm')
  567. True
  568. >>> del mock.m
  569. >>> hasattr(mock, 'm')
  570. False
  571. >>> del mock.f
  572. >>> mock.f
  573. Traceback (most recent call last):
  574. ...
  575. AttributeError: f
  576. Attaching Mocks as Attributes
  577. =============================
  578. When you attach a mock as an attribute of another mock (or as the return
  579. value) it becomes a "child" of that mock. Calls to the child are recorded in
  580. the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
  581. parent. This is useful for configuring child mocks and then attaching them to
  582. the parent, or for attaching mocks to a parent that records all calls to the
  583. children and allows you to make assertions about the order of calls between
  584. mocks:
  585. .. doctest::
  586. >>> parent = MagicMock()
  587. >>> child1 = MagicMock(return_value=None)
  588. >>> child2 = MagicMock(return_value=None)
  589. >>> parent.child1 = child1
  590. >>> parent.child2 = child2
  591. >>> child1(1)
  592. >>> child2(2)
  593. >>> parent.mock_calls
  594. [call.child1(1), call.child2(2)]
  595. The exception to this is if the mock has a name. This allows you to prevent
  596. the "parenting" if for some reason you don't want it to happen.
  597. .. doctest::
  598. >>> mock = MagicMock()
  599. >>> not_a_child = MagicMock(name='not-a-child')
  600. >>> mock.attribute = not_a_child
  601. >>> mock.attribute()
  602. <MagicMock name='not-a-child()' id='...'>
  603. >>> mock.mock_calls
  604. []
  605. Mocks created for you by :func:`patch` are automatically given names. To
  606. attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
  607. method:
  608. .. doctest::
  609. >>> thing1 = object()
  610. >>> thing2 = object()
  611. >>> parent = MagicMock()
  612. >>> with patch('__main__.thing1', return_value=None) as child1:
  613. ... with patch('__main__.thing2', return_value=None) as child2:
  614. ... parent.attach_mock(child1, 'child1')
  615. ... parent.attach_mock(child2, 'child2')
  616. ... child1('one')
  617. ... child2('two')
  618. ...
  619. >>> parent.mock_calls
  620. [call.child1('one'), call.child2('two')]
  621. -----
  622. .. [#] The only exceptions are magic methods and attributes (those that have
  623. leading and trailing double underscores). Mock doesn't create these but
  624. instead of raises an ``AttributeError``. This is because the interpreter
  625. will often implicitly request these methods, and gets *very* confused to
  626. get a new Mock object when it expects a magic method. If you need magic
  627. method support see :ref:`magic methods <magic-methods>`.