Debian Codegraph @

docs/walk-through.rst

raw
1 The Walk-through
2 ================
3
4 The 90% use case is that want to stub out a side effect. This is also known as (monkey-)patching. With mockito, it's::
5
6 from mockito import when
7
8 # stub `os.path.exists`
9 when(os.path).exists('/foo').thenReturn(True)
10
11 os.path.exists('/foo') # => True
12 os.path.exists('/bar') # -> throws unexpected invocation
13
14 So in difference to traditional patching, in mockito you always specify concrete arguments (a call signature), and its outcome, usually a return value via `thenReturn` or a raised exception via `thenRaise`. That effectively turns function calls into constants for the time of the test.
15
16 There are of course reasons when you don't want to overspecify specific tests. You _just_ want the desired stub answer. Here we go::
17
18 when(os.path).exists(...).thenReturn(True)
19
20 # now, obviously, you get the same answer, regardless of the arguments
21 os.path.exists('FooBar') # => True
22 os.path.exists('BarFoo') # => True
23
24 You can combine both stubs. E.g. nothing exists, except one file::
25
26 when(os.path).exists(...).thenReturn(False)
27 when(os.path).exists('.flake8').thenReturn(True)
28
29 And because it's a similar pattern, we can introduce :func:`spy2` here. Spies call through the original implementation of a given function. E.g. everything is as it is, except `'.flake8'` is just not there::
30
31 from mockito import spy2
32 spy2(os.path.exists)
33 when(os.path).exists('.flake8').thenReturn(False)
34
35 Another way to write the same thing is::
36
37 when(os.path).exists(...).thenCallOriginalImplementation()
38 when(os.path).exists('.flake8').thenReturn(False)
39
40 And actually `spy2` uses `thenCallOriginalImplementation` under the hood. Why spying at all: either you want the implementation *almost* intact as above or you
41 need the implementation to stay intact but want to `verify` its usage. E.g.::
42
43 spy2(os.path.exists)
44 # now do some stuff
45 do_stuff()
46 # then verify the we asked for the cache exactly once
47 verify(os.path, times=1).exists("cache/.foo")
48
49
50 When patching, you **MUST** **not** forget to :func:`unstub` of course! You can do this explicitly
51
52 ::
53
54 from mockito import unstub
55 unstub() # restore os.path module
56
57 Usually you do this unconditionally in your `teardown` function. If you're using `pytest`, you could define a fixture instead
58
59 ::
60
61 # conftest.py
62 import pytest
63
64 @pytest.fixture
65 def unstub():
66 from mockito import unstub
67 yield
68 unstub()
69
70 # my_test.py
71 import pytest
72 pytestmark = pytest.mark.usefixtures("unstub")
73
74 But very often you just use context managers (aka `with`), and mockito will unstub on 'exit' automatically::
75
76 # E.g. test that `exists` gets never called
77 with expect(os.path, times=0).exists('.flake8'):
78 # within the block `os.path.exists` is patched
79 cached_dir_lookup('.flake8')
80 # at the end of the block `os.path` gets unpatched
81
82 # Which is btw roughly the same as doing
83 with when(os.path).exists('.flake8'):
84 cached_dir_lookup('.flake8')
85 verify(os.path, times=0).exists(...)
86
87 Now let's mix global module patching with mocks. We want to test the following function using the fab `requests` library::
88
89 import requests
90
91 def get_text(url):
92 res = requests.get(url)
93 if 200 <= res.status_code < 300:
94 return res.text
95 return None
96
97 How, dare, we did not inject our dependencies! Obviously we can get over that by patching at the module level like before::
98
99 when(requests).get('https://example.com/api').thenReturn(...)
100
101 But what should we return? We know it's a `requests.Response` object, (Actually I know this bc I typed this in the ipython REPL first.) But how to construct such a `Response`, its `__init__` doesn't even take any arguments?
102
103 Should we actually use a 'real' response object? No, we fake it using :func:`mock`.
104
105 ::
106
107 # setup
108 response = mock({
109 'status_code': 200,
110 'text': 'Ok'
111 }, spec=requests.Response)
112 when(requests).get('https://example.com/api').thenReturn(response)
113
114 # run
115 assert get_text('https://example.com/api') == 'Ok'
116
117 # done!
118
119 Say you want to mock the class Dog::
120
121 class Dog(object):
122 def bark(self):
123 return 'Wuff'
124
125
126 # either mock the class
127 when(Dog).bark().thenReturn('Miau!')
128 # now all instances have a different behavior
129 rex = Dog()
130 assert rex.bark() == 'Miau!'
131
132 # or mock a concrete instance
133 when(rex).bark().thenReturn('Grrrr')
134 assert rex.bark() == 'Grrrr'
135 # a different dog will still 'Miau!'
136 assert Dog().bark() == 'Miau!'
137
138 # be sure to call unstub() once in while
139 unstub()
140
141
142 Sure, you can verify your interactions::
143
144 from mockito import verify
145 # once again
146 rex = Dog()
147 when(rex).bark().thenReturn('Grrrr')
148
149 rex.bark()
150 rex.bark()
151
152 # `times` defaults to 1
153 verify(rex, times=2).bark()
154
155
156 In general mockito is very picky::
157
158 # this will fail because `Dog` has no method named `waggle`
159 when(rex).waggle().thenReturn('Nope')
160 # this will fail because `bark` does not take any arguments
161 when(rex).bark('Grrr').thenReturn('Nope')
162
163
164 # given this function
165 def bark(sound, post='!'):
166 return sound + post
167
168 from mockito import kwargs
169 when(main).bark('Grrr', **kwargs).thenReturn('Nope')
170
171 # now this one will fail
172 bark('Grrr') # because there are no keyword arguments used
173 # this one will fail because `then` does not match the function signature
174 bark('Grrr', then='!!')
175 # this one will go
176 bark('Grrr', post='?')
177
178 # there is also an args matcher
179 def add_tasks(*tasks, verbose=False):
180 pass
181
182 from mockito import args
183 # If you omit the `thenReturn` it will just return `None`
184 when(main).add_tasks(*args)
185
186 add_tasks('task1', 'task2') # will go
187 add_tasks() # will fail
188 add_tasks('task1', verbose=True) # will fail too
189
190 # On Python 3 you can also use `...`
191 when(main).add_tasks(...)
192 # when(main).add_tasks(Ellipsis) on Python 2
193
194 add_tasks('task1') # will go
195 add_tasks(verbose=True) # will go
196 add_tasks('task1', verbose=True) # will go
197 add_tasks() # will go
198
199
200 To start with an empty stub use :func:`mock`::
201
202 from mockito import mock
203
204 obj = mock()
205
206 # pass it around, eventually it will be used
207 obj.say('Hi')
208
209 # back in the tests, verify the interactions
210 verify(obj).say('Hi')
211
212 # by default all invoked methods take any arguments and return None
213 # you can configure your expected method calls with the usual `when`
214 when(obj).say('Hi').thenReturn('Ho')
215
216 # There is also a shortcut to set some attributes
217 obj = mock({
218 'hi': 'ho'
219 })
220
221 assert obj.hi == 'ho'
222
223 # This would work for methods as well; in this case
224 obj = mock({
225 'say': lambda _: 'Ho'
226 })
227
228 # But you don't have any argument and signature matching
229 assert obj.say('Anything') == 'Ho'
230
231 # At least you can verify your calls
232 verify(obj).say(...)
233
234 # Btw, you can make screaming strict mocks::
235 obj = mock(strict=True) # every unconfigured, unexpected call will raise
236
237
238 You can use an empty stub specced against a concrete class::
239
240 # Given the above `Dog`
241 rex = mock(Dog)
242
243 # Now you can stub out any known method on `Dog` but other will throw
244 when(rex).bark().thenReturn('Miau')
245 # this one will fail
246 when(rex).waggle()
247
248 # These mocks are in general very strict, so even this will fail
249 rex.health # unconfigured attribute
250
251 # Of course you can just set it in a setup routine
252 rex.health = 121
253
254 # Or again preconfigure
255 rex = mock({'health': 121}, spec=Dog)
256
257 # preconfigure stubbed method
258 rex = mock({'bark': lambda sound: 'Miau'}, spec=Dog)
259
260 # as you specced the mock, you get at least function signature matching
261 # `bark` does not take any arguments so
262 rex.bark('sound') # will throw TypeError
263
264 # Btw, you can make loose specced mocks::
265 rex = mock(Dog, strict=False)
266
267