helpers.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. =========
  2. Helpers
  3. =========
  4. .. currentmodule:: mock
  5. .. testsetup::
  6. mock.FILTER_DIR = True
  7. from pprint import pprint as pp
  8. original_dir = dir
  9. def dir(obj):
  10. print pp(original_dir(obj))
  11. import urllib2
  12. __main__.urllib2 = urllib2
  13. .. testcleanup::
  14. dir = original_dir
  15. mock.FILTER_DIR = True
  16. call
  17. ====
  18. .. function:: call(*args, **kwargs)
  19. `call` is a helper object for making simpler assertions, for comparing
  20. with :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
  21. :attr:`~Mock.mock_calls` and :attr: `~Mock.method_calls`. `call` can also be
  22. used with :meth:`~Mock.assert_has_calls`.
  23. .. doctest::
  24. >>> m = MagicMock(return_value=None)
  25. >>> m(1, 2, a='foo', b='bar')
  26. >>> m()
  27. >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
  28. True
  29. .. method:: call.call_list()
  30. For a call object that represents multiple calls, `call_list`
  31. returns a list of all the intermediate calls as well as the
  32. final call.
  33. `call_list` is particularly useful for making assertions on "chained calls". A
  34. chained call is multiple calls on a single line of code. This results in
  35. multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
  36. the sequence of calls can be tedious.
  37. :meth:`~call.call_list` can construct the sequence of calls from the same
  38. chained call:
  39. .. doctest::
  40. >>> m = MagicMock()
  41. >>> m(1).method(arg='foo').other('bar')(2.0)
  42. <MagicMock name='mock().method().other()()' id='...'>
  43. >>> kall = call(1).method(arg='foo').other('bar')(2.0)
  44. >>> kall.call_list()
  45. [call(1),
  46. call().method(arg='foo'),
  47. call().method().other('bar'),
  48. call().method().other()(2.0)]
  49. >>> m.mock_calls == kall.call_list()
  50. True
  51. .. _calls-as-tuples:
  52. A `call` object is either a tuple of (positional args, keyword args) or
  53. (name, positional args, keyword args) depending on how it was constructed. When
  54. you construct them yourself this isn't particularly interesting, but the `call`
  55. objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
  56. :attr:`Mock.mock_calls` attributes can be introspected to get at the individual
  57. arguments they contain.
  58. The `call` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
  59. are two-tuples of (positional args, keyword args) whereas the `call` objects
  60. in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
  61. three-tuples of (name, positional args, keyword args).
  62. You can use their "tupleness" to pull out the individual arguments for more
  63. complex introspection and assertions. The positional arguments are a tuple
  64. (an empty tuple if there are no positional arguments) and the keyword
  65. arguments are a dictionary:
  66. .. doctest::
  67. >>> m = MagicMock(return_value=None)
  68. >>> m(1, 2, 3, arg='one', arg2='two')
  69. >>> kall = m.call_args
  70. >>> args, kwargs = kall
  71. >>> args
  72. (1, 2, 3)
  73. >>> kwargs
  74. {'arg2': 'two', 'arg': 'one'}
  75. >>> args is kall[0]
  76. True
  77. >>> kwargs is kall[1]
  78. True
  79. >>> m = MagicMock()
  80. >>> m.foo(4, 5, 6, arg='two', arg2='three')
  81. <MagicMock name='mock.foo()' id='...'>
  82. >>> kall = m.mock_calls[0]
  83. >>> name, args, kwargs = kall
  84. >>> name
  85. 'foo'
  86. >>> args
  87. (4, 5, 6)
  88. >>> kwargs
  89. {'arg2': 'three', 'arg': 'two'}
  90. >>> name is m.mock_calls[0][0]
  91. True
  92. create_autospec
  93. ===============
  94. .. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
  95. Create a mock object using another object as a spec. Attributes on the
  96. mock will use the corresponding attribute on the `spec` object as their
  97. spec.
  98. Functions or methods being mocked will have their arguments checked to
  99. ensure that they are called with the correct signature.
  100. If `spec_set` is `True` then attempting to set attributes that don't exist
  101. on the spec object will raise an `AttributeError`.
  102. If a class is used as a spec then the return value of the mock (the
  103. instance of the class) will have the same spec. You can use a class as the
  104. spec for an instance object by passing `instance=True`. The returned mock
  105. will only be callable if instances of the mock are callable.
  106. `create_autospec` also takes arbitrary keyword arguments that are passed to
  107. the constructor of the created mock.
  108. See :ref:`auto-speccing` for examples of how to use auto-speccing with
  109. `create_autospec` and the `autospec` argument to :func:`patch`.
  110. ANY
  111. ===
  112. .. data:: ANY
  113. Sometimes you may need to make assertions about *some* of the arguments in a
  114. call to mock, but either not care about some of the arguments or want to pull
  115. them individually out of :attr:`~Mock.call_args` and make more complex
  116. assertions on them.
  117. To ignore certain arguments you can pass in objects that compare equal to
  118. *everything*. Calls to :meth:`~Mock.assert_called_with` and
  119. :meth:`~Mock.assert_called_once_with` will then succeed no matter what was
  120. passed in.
  121. .. doctest::
  122. >>> mock = Mock(return_value=None)
  123. >>> mock('foo', bar=object())
  124. >>> mock.assert_called_once_with('foo', bar=ANY)
  125. `ANY` can also be used in comparisons with call lists like
  126. :attr:`~Mock.mock_calls`:
  127. .. doctest::
  128. >>> m = MagicMock(return_value=None)
  129. >>> m(1)
  130. >>> m(1, 2)
  131. >>> m(object())
  132. >>> m.mock_calls == [call(1), call(1, 2), ANY]
  133. True
  134. FILTER_DIR
  135. ==========
  136. .. data:: FILTER_DIR
  137. `FILTER_DIR` is a module level variable that controls the way mock objects
  138. respond to `dir` (only for Python 2.6 or more recent). The default is `True`,
  139. which uses the filtering described below, to only show useful members. If you
  140. dislike this filtering, or need to switch it off for diagnostic purposes, then
  141. set `mock.FILTER_DIR = False`.
  142. With filtering on, `dir(some_mock)` shows only useful attributes and will
  143. include any dynamically created attributes that wouldn't normally be shown.
  144. If the mock was created with a `spec` (or `autospec` of course) then all the
  145. attributes from the original are shown, even if they haven't been accessed
  146. yet:
  147. .. doctest::
  148. >>> dir(Mock())
  149. ['assert_any_call',
  150. 'assert_called_once_with',
  151. 'assert_called_with',
  152. 'assert_has_calls',
  153. 'attach_mock',
  154. ...
  155. >>> import urllib2
  156. >>> dir(Mock(spec=urllib2))
  157. ['AbstractBasicAuthHandler',
  158. 'AbstractDigestAuthHandler',
  159. 'AbstractHTTPHandler',
  160. 'BaseHandler',
  161. ...
  162. Many of the not-very-useful (private to `Mock` rather than the thing being
  163. mocked) underscore and double underscore prefixed attributes have been
  164. filtered from the result of calling `dir` on a `Mock`. If you dislike this
  165. behaviour you can switch it off by setting the module level switch
  166. `FILTER_DIR`:
  167. .. doctest::
  168. >>> import mock
  169. >>> mock.FILTER_DIR = False
  170. >>> dir(mock.Mock())
  171. ['_NonCallableMock__get_return_value',
  172. '_NonCallableMock__get_side_effect',
  173. '_NonCallableMock__return_value_doc',
  174. '_NonCallableMock__set_return_value',
  175. '_NonCallableMock__set_side_effect',
  176. '__call__',
  177. '__class__',
  178. ...
  179. Alternatively you can just use `vars(my_mock)` (instance members) and
  180. `dir(type(my_mock))` (type members) to bypass the filtering irrespective of
  181. `mock.FILTER_DIR`.
  182. mock_open
  183. =========
  184. .. function:: mock_open(mock=None, read_data=None)
  185. A helper function to create a mock to replace the use of `open`. It works
  186. for `open` called directly or used as a context manager.
  187. The `mock` argument is the mock object to configure. If `None` (the
  188. default) then a `MagicMock` will be created for you, with the API limited
  189. to methods or attributes available on standard file handles.
  190. `read_data` is a string for the `read` method of the file handle to return.
  191. This is an empty string by default.
  192. Using `open` as a context manager is a great way to ensure your file handles
  193. are closed properly and is becoming common::
  194. with open('/some/path', 'w') as f:
  195. f.write('something')
  196. The issue is that even if you mock out the call to `open` it is the
  197. *returned object* that is used as a context manager (and has `__enter__` and
  198. `__exit__` called).
  199. Mocking context managers with a :class:`MagicMock` is common enough and fiddly
  200. enough that a helper function is useful.
  201. .. doctest::
  202. >>> from mock import mock_open
  203. >>> m = mock_open()
  204. >>> with patch('__main__.open', m, create=True):
  205. ... with open('foo', 'w') as h:
  206. ... h.write('some stuff')
  207. ...
  208. >>> m.mock_calls
  209. [call('foo', 'w'),
  210. call().__enter__(),
  211. call().write('some stuff'),
  212. call().__exit__(None, None, None)]
  213. >>> m.assert_called_once_with('foo', 'w')
  214. >>> handle = m()
  215. >>> handle.write.assert_called_once_with('some stuff')
  216. And for reading files:
  217. .. doctest::
  218. >>> with patch('__main__.open', mock_open(read_data='bibble'), create=True) as m:
  219. ... with open('foo') as h:
  220. ... result = h.read()
  221. ...
  222. >>> m.assert_called_once_with('foo')
  223. >>> assert result == 'bibble'
  224. .. _auto-speccing:
  225. Autospeccing
  226. ============
  227. Autospeccing is based on the existing `spec` feature of mock. It limits the
  228. api of mocks to the api of an original object (the spec), but it is recursive
  229. (implemented lazily) so that attributes of mocks only have the same api as
  230. the attributes of the spec. In addition mocked functions / methods have the
  231. same call signature as the original so they raise a `TypeError` if they are
  232. called incorrectly.
  233. Before I explain how auto-speccing works, here's why it is needed.
  234. `Mock` is a very powerful and flexible object, but it suffers from two flaws
  235. when used to mock out objects from a system under test. One of these flaws is
  236. specific to the `Mock` api and the other is a more general problem with using
  237. mock objects.
  238. First the problem specific to `Mock`. `Mock` has two assert methods that are
  239. extremely handy: :meth:`~Mock.assert_called_with` and
  240. :meth:`~Mock.assert_called_once_with`.
  241. .. doctest::
  242. >>> mock = Mock(name='Thing', return_value=None)
  243. >>> mock(1, 2, 3)
  244. >>> mock.assert_called_once_with(1, 2, 3)
  245. >>> mock(1, 2, 3)
  246. >>> mock.assert_called_once_with(1, 2, 3)
  247. Traceback (most recent call last):
  248. ...
  249. AssertionError: Expected to be called once. Called 2 times.
  250. Because mocks auto-create attributes on demand, and allow you to call them
  251. with arbitrary arguments, if you misspell one of these assert methods then
  252. your assertion is gone:
  253. .. code-block:: pycon
  254. >>> mock = Mock(name='Thing', return_value=None)
  255. >>> mock(1, 2, 3)
  256. >>> mock.assret_called_once_with(4, 5, 6)
  257. Your tests can pass silently and incorrectly because of the typo.
  258. The second issue is more general to mocking. If you refactor some of your
  259. code, rename members and so on, any tests for code that is still using the
  260. *old api* but uses mocks instead of the real objects will still pass. This
  261. means your tests can all pass even though your code is broken.
  262. Note that this is another reason why you need integration tests as well as
  263. unit tests. Testing everything in isolation is all fine and dandy, but if you
  264. don't test how your units are "wired together" there is still lots of room
  265. for bugs that tests might have caught.
  266. `mock` already provides a feature to help with this, called speccing. If you
  267. use a class or instance as the `spec` for a mock then you can only access
  268. attributes on the mock that exist on the real class:
  269. .. doctest::
  270. >>> import urllib2
  271. >>> mock = Mock(spec=urllib2.Request)
  272. >>> mock.assret_called_with
  273. Traceback (most recent call last):
  274. ...
  275. AttributeError: Mock object has no attribute 'assret_called_with'
  276. The spec only applies to the mock itself, so we still have the same issue
  277. with any methods on the mock:
  278. .. code-block:: pycon
  279. >>> mock.has_data()
  280. <mock.Mock object at 0x...>
  281. >>> mock.has_data.assret_called_with()
  282. Auto-speccing solves this problem. You can either pass `autospec=True` to
  283. `patch` / `patch.object` or use the `create_autospec` function to create a
  284. mock with a spec. If you use the `autospec=True` argument to `patch` then the
  285. object that is being replaced will be used as the spec object. Because the
  286. speccing is done "lazily" (the spec is created as attributes on the mock are
  287. accessed) you can use it with very complex or deeply nested objects (like
  288. modules that import modules that import modules) without a big performance
  289. hit.
  290. Here's an example of it in use:
  291. .. doctest::
  292. >>> import urllib2
  293. >>> patcher = patch('__main__.urllib2', autospec=True)
  294. >>> mock_urllib2 = patcher.start()
  295. >>> urllib2 is mock_urllib2
  296. True
  297. >>> urllib2.Request
  298. <MagicMock name='urllib2.Request' spec='Request' id='...'>
  299. You can see that `urllib2.Request` has a spec. `urllib2.Request` takes two
  300. arguments in the constructor (one of which is `self`). Here's what happens if
  301. we try to call it incorrectly:
  302. .. doctest::
  303. >>> req = urllib2.Request()
  304. Traceback (most recent call last):
  305. ...
  306. TypeError: <lambda>() takes at least 2 arguments (1 given)
  307. The spec also applies to instantiated classes (i.e. the return value of
  308. specced mocks):
  309. .. doctest::
  310. >>> req = urllib2.Request('foo')
  311. >>> req
  312. <NonCallableMagicMock name='urllib2.Request()' spec='Request' id='...'>
  313. `Request` objects are not callable, so the return value of instantiating our
  314. mocked out `urllib2.Request` is a non-callable mock. With the spec in place
  315. any typos in our asserts will raise the correct error:
  316. .. doctest::
  317. >>> req.add_header('spam', 'eggs')
  318. <MagicMock name='urllib2.Request().add_header()' id='...'>
  319. >>> req.add_header.assret_called_with
  320. Traceback (most recent call last):
  321. ...
  322. AttributeError: Mock object has no attribute 'assret_called_with'
  323. >>> req.add_header.assert_called_with('spam', 'eggs')
  324. In many cases you will just be able to add `autospec=True` to your existing
  325. `patch` calls and then be protected against bugs due to typos and api
  326. changes.
  327. As well as using `autospec` through `patch` there is a
  328. :func:`create_autospec` for creating autospecced mocks directly:
  329. .. doctest::
  330. >>> import urllib2
  331. >>> mock_urllib2 = create_autospec(urllib2)
  332. >>> mock_urllib2.Request('foo', 'bar')
  333. <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
  334. This isn't without caveats and limitations however, which is why it is not
  335. the default behaviour. In order to know what attributes are available on the
  336. spec object, autospec has to introspect (access attributes) the spec. As you
  337. traverse attributes on the mock a corresponding traversal of the original
  338. object is happening under the hood. If any of your specced objects have
  339. properties or descriptors that can trigger code execution then you may not be
  340. able to use autospec. On the other hand it is much better to design your
  341. objects so that introspection is safe [#]_.
  342. A more serious problem is that it is common for instance attributes to be
  343. created in the `__init__` method and not to exist on the class at all.
  344. `autospec` can't know about any dynamically created attributes and restricts
  345. the api to visible attributes.
  346. .. doctest::
  347. >>> class Something(object):
  348. ... def __init__(self):
  349. ... self.a = 33
  350. ...
  351. >>> with patch('__main__.Something', autospec=True):
  352. ... thing = Something()
  353. ... thing.a
  354. ...
  355. Traceback (most recent call last):
  356. ...
  357. AttributeError: Mock object has no attribute 'a'
  358. There are a few different ways of resolving this problem. The easiest, but
  359. not necessarily the least annoying, way is to simply set the required
  360. attributes on the mock after creation. Just because `autospec` doesn't allow
  361. you to fetch attributes that don't exist on the spec it doesn't prevent you
  362. setting them:
  363. .. doctest::
  364. >>> with patch('__main__.Something', autospec=True):
  365. ... thing = Something()
  366. ... thing.a = 33
  367. ...
  368. There is a more aggressive version of both `spec` and `autospec` that *does*
  369. prevent you setting non-existent attributes. This is useful if you want to
  370. ensure your code only *sets* valid attributes too, but obviously it prevents
  371. this particular scenario:
  372. .. doctest::
  373. >>> with patch('__main__.Something', autospec=True, spec_set=True):
  374. ... thing = Something()
  375. ... thing.a = 33
  376. ...
  377. Traceback (most recent call last):
  378. ...
  379. AttributeError: Mock object has no attribute 'a'
  380. Probably the best way of solving the problem is to add class attributes as
  381. default values for instance members initialised in `__init__`. Note that if
  382. you are only setting default attributes in `__init__` then providing them via
  383. class attributes (shared between instances of course) is faster too. e.g.
  384. .. code-block:: python
  385. class Something(object):
  386. a = 33
  387. This brings up another issue. It is relatively common to provide a default
  388. value of `None` for members that will later be an object of a different type.
  389. `None` would be useless as a spec because it wouldn't let you access *any*
  390. attributes or methods on it. As `None` is *never* going to be useful as a
  391. spec, and probably indicates a member that will normally of some other type,
  392. `autospec` doesn't use a spec for members that are set to `None`. These will
  393. just be ordinary mocks (well - `MagicMocks`):
  394. .. doctest::
  395. >>> class Something(object):
  396. ... member = None
  397. ...
  398. >>> mock = create_autospec(Something)
  399. >>> mock.member.foo.bar.baz()
  400. <MagicMock name='mock.member.foo.bar.baz()' id='...'>
  401. If modifying your production classes to add defaults isn't to your liking
  402. then there are more options. One of these is simply to use an instance as the
  403. spec rather than the class. The other is to create a subclass of the
  404. production class and add the defaults to the subclass without affecting the
  405. production class. Both of these require you to use an alternative object as
  406. the spec. Thankfully `patch` supports this - you can simply pass the
  407. alternative object as the `autospec` argument:
  408. .. doctest::
  409. >>> class Something(object):
  410. ... def __init__(self):
  411. ... self.a = 33
  412. ...
  413. >>> class SomethingForTest(Something):
  414. ... a = 33
  415. ...
  416. >>> p = patch('__main__.Something', autospec=SomethingForTest)
  417. >>> mock = p.start()
  418. >>> mock.a
  419. <NonCallableMagicMock name='Something.a' spec='int' id='...'>
  420. .. note::
  421. An additional limitation (currently) with `autospec` is that unbound
  422. methods on mocked classes *don't* take an "explicit self" as the first
  423. argument - so this usage will fail with `autospec`.
  424. .. doctest::
  425. >>> class Foo(object):
  426. ... def foo(self):
  427. ... pass
  428. ...
  429. >>> Foo.foo(Foo())
  430. >>> MockFoo = create_autospec(Foo)
  431. >>> MockFoo.foo(MockFoo())
  432. Traceback (most recent call last):
  433. ...
  434. TypeError: <lambda>() takes exactly 1 argument (2 given)
  435. The reason is that its very hard to tell the difference between functions,
  436. unbound methods and staticmethods across Python 2 & 3 and the alternative
  437. implementations. This restriction may be fixed in future versions.
  438. ------
  439. .. [#] This only applies to classes or already instantiated objects. Calling
  440. a mocked class to create a mock instance *does not* create a real instance.
  441. It is only attribute lookups - along with calls to `dir` - that are done. A
  442. way round this problem would have been to use `getattr_static
  443. <http://docs.python.org/dev/library/inspect.html#inspect.getattr_static>`_,
  444. which can fetch attributes without triggering code execution. Descriptors
  445. like `classmethod` and `staticmethod` *need* to be fetched correctly though,
  446. so that their signatures can be mocked correctly.