-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.html
More file actions
657 lines (633 loc) · 41.5 KB
/
index.html
File metadata and controls
657 lines (633 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="pandoc" />
<title></title>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<link rel="stylesheet" type="text/css" media="screen, projection, print"
href="http://www.w3.org/Talks/Tools/Slidy2/styles/slidy.css" />
<script src="http://www.w3.org/Talks/Tools/Slidy2/scripts/slidy.js"
charset="utf-8" type="text/javascript"></script>
</head>
<body>
<div id="mocks-for-testing" class="slide section level1">
<h1>Mocks for Testing</h1>
<dl>
<dt>Author</dt>
<dd><p>Brian Weber, SRE at Twitter</p>
</dd>
<dt>Contact</dt>
<dd><p><script type="text/javascript">
<!--
h='twitter.com';a='@';n='bweber';e=n+a+h;
document.write('<a h'+'ref'+'="ma'+'ilto'+':'+e+'" clas'+'s="em' + 'ail">'+e+'<\/'+'a'+'>');
// -->
</script><noscript>bweber at twitter dot com</noscript></p>
</dd>
<dt>Twitter</dt>
<dd><p>@mistermocha</p>
</dd>
<dt>Link</dt>
<dd><p><a href="https://github.com/mistermocha/python-mock-talk/" class="uri">https://github.com/mistermocha/python-mock-talk/</a></p>
</dd>
</dl>
</div>
<div id="headers" class="slide section level1">
<h1>Headers</h1>
<p>What will be covered:</p>
<ul>
<li>Overview of the mock library and its features</li>
<li>Examples of how to use the mock library</li>
<li>Review of its purposes</li>
<li>When to use and when not to use</li>
</ul>
</div>
<div id="why-i-wrote-this-talk" class="slide section level1">
<h1>Why I wrote this talk</h1>
<p>Timing! I was asked to give a talk after writing a bunch of mock test code.</p>
<p><img src="./commit-strip-tests.jpg" alt="image" /></p>
<p><sup>image credit: http://www.commitstrip.com/en/2017/02/08/where-are-the-tests/</sup></p>
</div>
<div id="what-is-testing" class="slide section level1">
<h1>What is testing?</h1>
<p>Testing makes sure your code behaves as expected by <strong>running your code</strong> and observing the results</p>
</div>
<div id="how-would-you-test-this" class="slide section level1">
<h1>How would you test this?</h1>
<ul>
<li>without actually deleting anything?</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># yourcode.py</span>
<span class="kw">def</span> wipe_directory(path):
p <span class="op">=</span> Popen([<span class="st">'rm'</span>, <span class="st">'-rf'</span>, path], stdout<span class="op">=</span>PIPE, stderr<span class="op">=</span>PIPE)
<span class="cf">if</span> p.wait():
<span class="cf">raise</span> <span class="pp">Exception</span>(<span class="st">'We had a fail'</span>)</code></pre></div>
</div>
<div id="how-would-you-test-this-1" class="slide section level1">
<h1>How would you test this?</h1>
<ul>
<li>without actually deleting anything?</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># yourcode.py</span>
<span class="kw">def</span> delete_everything():
r <span class="op">=</span> requests.post(<span class="st">'http://example.com/'</span>,
data<span class="op">=</span>{<span class="st">'delete'</span>: <span class="st">'everything'</span>, <span class="st">'autocommit'</span>: <span class="st">'true'</span>})
<span class="cf">if</span> r.status_code <span class="op">==</span> <span class="dv">200</span>:
<span class="bu">print</span>(<span class="st">'All things have been deleted'</span>)
<span class="cf">return</span> <span class="va">True</span>
<span class="cf">else</span>:
<span class="bu">print</span>(<span class="st">'Got an error: {}'</span>.<span class="bu">format</span>(r.headers))
<span class="cf">return</span> <span class="va">False</span></code></pre></div>
</div>
<div id="how-would-you-test-this-2" class="slide section level1">
<h1>How would you test this?</h1>
<ul>
<li>without writing to the database?</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">class</span> DBWriter(<span class="bu">object</span>):
counter <span class="op">=</span> <span class="dv">0</span>
<span class="kw">def</span> <span class="fu">__init__</span>(<span class="va">self</span>):
<span class="va">self</span>.db <span class="op">=</span> DBLibrary()
<span class="kw">def</span> commit_to_db(<span class="va">self</span>, sql):
<span class="va">self</span>.counter <span class="op">+=</span> <span class="dv">1</span>
<span class="va">self</span>.db.commit(sql)
<span class="kw">def</span> save(<span class="va">self</span>, string):
sql <span class="op">=</span> <span class="st">"INSERT INTO mytable SET mystring = '{}'"</span>.<span class="bu">format</span>(string)
<span class="va">self</span>.commit_to_db(sql)
<span class="kw">def</span> drop(<span class="va">self</span>, string):
sql <span class="op">=</span> <span class="st">"DELETE FROM mytable WHERE mystring = '{}'"</span>.<span class="bu">format</span>(string)
<span class="va">self</span>.commit_to_db(sql)</code></pre></div>
</div>
<div id="how-would-you-test-this-3" class="slide section level1">
<h1>How would you test this?</h1>
<p>My script that I manage talks to</p>
<ul>
<li>kerberos</li>
<li>git</li>
<li>aurora</li>
<li>package repo</li>
<li>jira</li>
<li>email</li>
<li>shared libraries</li>
</ul>
<p>How do I test my code without beating up these services?</p>
</div>
<div id="what-is-testing-1" class="slide section level1">
<h1>What is testing?</h1>
<ul>
<li>Unit: Just this small part</li>
<li>Integration: When all the parts talk to each other and included parts</li>
<li>Acceptance: When the whole app talks to everything else</li>
</ul>
</div>
<div id="what-is-mocking" class="slide section level1">
<h1>What is mocking?</h1>
<p><code>unittest.mock</code> is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.</p>
<p>Source: <a href="https://docs.python.org/3/library/unittest.mock.html" class="uri">https://docs.python.org/3/library/unittest.mock.html</a></p>
<p>Mocks are primarily used for unit testing. There may be some place in integration testing, highly unlikely in acceptance testing.</p>
</div>
<div id="why-should-i-mock" class="slide section level1">
<h1>Why should I mock?</h1>
<ul>
<li>Unit test safely</li>
<li>Write better code</li>
<li>Isolation</li>
</ul>
</div>
<div id="about-the-mock-library" class="slide section level1">
<h1>About the mock library</h1>
<p>Mock objects intend to replace another part of code so that it pretends to be that code</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="im">from</span> unittest.mock <span class="im">import</span> Mock
<span class="im">from</span> mycode <span class="im">import</span> MyClass
<span class="kw">def</span> test_myclass():
my_object <span class="op">=</span> MyClass()
my_object.sub_method <span class="op">=</span> Mock()
my_object.visible_method()
my_object.sub_method.assert_called_with(<span class="st">"arg"</span>, this<span class="op">=</span><span class="st">"that"</span>)</code></pre></div>
<p>This isolates one function from talking to another function within the same class.</p>
</div>
<div id="an-example-of-using-a-mock" class="slide section level1">
<h1>An example of using a mock</h1>
<p>Replacements can be done with object patching</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># yourcode.py</span>
<span class="kw">def</span> count_the_shells():
p <span class="op">=</span> Popen([<span class="st">'ps'</span>, <span class="st">'-a'</span>], stdout<span class="op">=</span>PIPE, stderr<span class="op">=</span>PIPE)
<span class="cf">if</span> p.wait():
<span class="cf">raise</span> <span class="pp">Exception</span>(<span class="st">'We had a fail'</span>)
count <span class="op">=</span> <span class="dv">0</span>
<span class="cf">for</span> proc <span class="op">in</span> p.stdout.readlines():
<span class="cf">if</span> <span class="st">"-bash"</span> <span class="op">in</span> proc:
count <span class="op">+=</span> <span class="dv">1</span>
<span class="cf">return</span> count</code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># test.py</span>
<span class="at">@mock.patch</span>(<span class="st">'subprocess.Popen'</span>)
<span class="kw">def</span> test_count_the_shells(mocked_popen):
mocked_popen.return_value.stdout <span class="op">=</span> <span class="bu">open</span>(<span class="st">'testps.out'</span>)
mocked_popen.return_value.wait.return_value <span class="op">=</span> <span class="va">False</span>
<span class="cf">assert</span> count_the_shells() <span class="op">==</span> <span class="dv">4</span></code></pre></div>
<p>Let's dive deeper into this</p>
</div>
<div id="an-example-of-using-a-mock-1" class="slide section level1">
<h1>An example of using a mock</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># yourcode.py</span>
<span class="kw">def</span> count_the_shells():
p <span class="op">=</span> Popen([<span class="st">'ps'</span>, <span class="st">'-a'</span>], stdout<span class="op">=</span>PIPE, stderr<span class="op">=</span>PIPE)
<span class="cf">if</span> p.wait():
<span class="cf">raise</span> <span class="pp">Exception</span>(<span class="st">'We had a fail'</span>)
count <span class="op">=</span> <span class="dv">0</span>
<span class="cf">for</span> proc <span class="op">in</span> p.stdout.readlines():
<span class="cf">if</span> <span class="st">"-bash"</span> <span class="op">in</span> proc:
count <span class="op">+=</span> <span class="dv">1</span>
<span class="cf">return</span> count</code></pre></div>
<ul>
<li><code>Popen</code> runs a command line execution and returns a subprocess object. In this case, <code>p</code></li>
<li><code>p.wait()</code> blocks until it gets back the shell's exit code and returns it as an integer.</li>
<li><code>p.stdout</code> is a filelike object that captures STDOUT</li>
</ul>
</div>
<div id="an-example-of-using-a-mock-2" class="slide section level1">
<h1>An example of using a mock</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># test.py</span>
<span class="at">@mock.patch</span>(<span class="st">'subprocess.Popen'</span>)
<span class="kw">def</span> test_count_the_shells(mocked_popen):
mocked_popen.return_value.stdout <span class="op">=</span> <span class="bu">open</span>(<span class="st">'testps.out'</span>)
mocked_popen.return_value.wait.return_value <span class="op">=</span> <span class="va">False</span>
<span class="cf">assert</span> count_the_shells() <span class="op">==</span> <span class="dv">4</span></code></pre></div>
<ul>
<li><code>@mock.patch</code> decorator replaces <code>subprocess.Popen</code> with a mock object. That gets passed in as the first argument in the test function. The test function receives it as <code>mocked_popen</code></li>
<li>The <code>Popen</code> call returns a subprocess object. We're now amending the <code>return_value</code> of that object by applying behavior to <code>stdout</code> and <code>wait</code>, which get used in the function</li>
<li>Now when <code>count_the_shells</code> is executed, it calls the mock instead of <code>Popen</code> and gets back expected values.</li>
</ul>
</div>
<div id="about-the-mock-library-1" class="slide section level1">
<h1>About the mock library</h1>
<p>Plasticity - a default mock object will accept any undeclared function</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> mock <span class="op">=</span> Mock()
<span class="op">>>></span> mock.this_is_never_assigned(<span class="st">'hello'</span>)
<span class="op"><</span>Mock name<span class="op">=</span><span class="st">'mock.this_is_never_assigned()'</span> <span class="bu">id</span><span class="op">=</span><span class="st">'4422797328'</span><span class="op">></span></code></pre></div>
<p>This prevents accidental calls from blowing up your code, but, leaves room for a lot of error.</p>
<p>Safer instantiation by autospeccing - make the mock behave like more like the thing you're mocking</p>
</div>
<div id="spec-and-autospec" class="slide section level1">
<h1>Spec and Autospec</h1>
<ul>
<li><code>spec</code> tells the mock to closely behave like another. Mocks instantiated with <code>spec=RealObject</code> will pass <code>isinstance(the_mock, RealObject)</code></li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> <span class="im">from</span> collections <span class="im">import</span> OrderedDict
<span class="op">>>></span> mymock <span class="op">=</span> Mock(spec<span class="op">=</span>OrderedDict)
<span class="op">>>></span> <span class="bu">isinstance</span>(mymock, OrderedDict)
<span class="va">True</span>
<span class="op">>>></span> <span class="bu">type</span>(mymock)
<span class="op"><</span><span class="kw">class</span> <span class="st">'mock.Mock'</span><span class="op">></span></code></pre></div>
</div>
<div id="spec-and-autospec-1" class="slide section level1">
<h1>Spec and Autospec</h1>
<ul>
<li><code>spec</code> also affords protection, preventing calls to undeclared attributes. You can declare any additional attributes you wish.</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> a <span class="op">=</span> mymock.this_does_not_exist()
Traceback (most recent call last):
File <span class="st">"<stdin>"</span>, line <span class="dv">1</span>, <span class="op">in</span> <span class="op"><</span>module<span class="op">></span>
File <span class="st">"/opt/twitter/lib/python2.7/site-packages/mock.py"</span>, line <span class="dv">658</span>, <span class="op">in</span> <span class="fu">__getattr__</span>
<span class="cf">raise</span> <span class="pp">AttributeError</span>(<span class="st">"Mock object has no attribute </span><span class="sc">%r</span><span class="st">"</span> <span class="op">%</span> name)
<span class="pp">AttributeError</span>: Mock <span class="bu">object</span> has no attribute <span class="st">'this_does_not_exist'</span>
<span class="op">>>></span> mymock.this_does_not_exist <span class="op">=</span> <span class="st">"this exists now"</span>
<span class="op">>>></span> <span class="bu">print</span>(mymock.this_does_not_exist)
this exists now</code></pre></div>
</div>
<div id="spec-and-autospec-2" class="slide section level1">
<h1>Spec and Autospec</h1>
<ul>
<li><code>spec_set</code> stricter spec, prevents amending missing attributes. Attempts to define undeclared attributes will fail on <code>AttributeError</code>.</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> mymock <span class="op">=</span> Mock(spec_set<span class="op">=</span>OrderedDict)
<span class="op">>>></span> mymock.this_does_not_exist <span class="op">=</span> <span class="st">"o no you didn't"</span>
Traceback (most recent call last):
File <span class="st">"<stdin>"</span>, line <span class="dv">1</span>, <span class="op">in</span> <span class="op"><</span>module<span class="op">></span>
File <span class="st">"/opt/twitter/lib/python2.7/site-packages/mock.py"</span>, line <span class="dv">761</span>, <span class="op">in</span> <span class="fu">__setattr__</span>
<span class="cf">raise</span> <span class="pp">AttributeError</span>(<span class="st">"Mock object has no attribute '</span><span class="sc">%s</span><span class="st">'"</span> <span class="op">%</span> name)
<span class="pp">AttributeError</span>: Mock <span class="bu">object</span> has no attribute <span class="st">'this_does_not_exist'</span>
<span class="op">>>></span></code></pre></div>
</div>
<div id="spec-and-autospec-3" class="slide section level1">
<h1>Spec and Autospec</h1>
<ul>
<li><code>create_autospec</code> is even stricter. Mock functions defined to spec will enforce argument patterns for functions.</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> <span class="kw">def</span> myfunc(foo, bar):
... <span class="cf">pass</span>
...
<span class="op">>>></span> mymock <span class="op">=</span> create_autospec(myfunc)
<span class="op">>>></span> mymock(<span class="st">"one"</span>, <span class="st">"two"</span>)
<span class="op"><</span>MagicMock name<span class="op">=</span><span class="st">'mock()'</span> <span class="bu">id</span><span class="op">=</span><span class="st">'4493382480'</span><span class="op">></span>
<span class="op">>>></span> mymock(<span class="st">"just one"</span>)
Traceback (most recent call last):
File <span class="st">"<stdin>"</span>, line <span class="dv">1</span>, <span class="op">in</span> <span class="op"><</span>module<span class="op">></span>
File <span class="st">"<string>"</span>, line <span class="dv">2</span>, <span class="op">in</span> myfunc
<span class="pp">TypeError</span>: <span class="op"><</span><span class="kw">lambda</span><span class="op">></span>() takes exactly <span class="dv">2</span> arguments (<span class="dv">1</span> given)
<span class="op">>>></span></code></pre></div>
</div>
<div id="spec-and-autospec-4" class="slide section level1">
<h1>Spec and Autospec</h1>
<p>Appropriate use of spec can help you write cleaner code and catch typos</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> mock <span class="op">=</span> Mock(name<span class="op">=</span><span class="st">'Thing'</span>, return_value<span class="op">=</span><span class="va">None</span>)
<span class="op">>>></span> mock(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>)
<span class="op">>>></span> mock.assret_called_once_with(<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>)
<span class="co"># typo of "assert" passes because mock objects are forgiving</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> <span class="im">from</span> urllib <span class="im">import</span> request
<span class="op">>>></span> mock <span class="op">=</span> Mock(spec<span class="op">=</span>request.Request)
<span class="op">>>></span> mock.assret_called_with
Traceback (most recent call last):
...
<span class="pp">AttributeError</span>: Mock <span class="bu">object</span> has no attribute <span class="st">'assret_called_with'</span>
<span class="co"># since "assret_called_with" is a typo, it's not declared. Proper exception caught!</span></code></pre></div>
<ul>
<li><code>name</code> your mocks, which shows in the repr - useful for debugging!</li>
</ul>
</div>
<div id="introspection" class="slide section level1">
<h1>Introspection</h1>
<p>Built-in functions for introspection</p>
<ul>
<li><code>called</code> - boolean, true if ever called</li>
<li><code>call_count</code> - integer, number of times called</li>
<li><code>call_args</code> - mock.call() object with args from last call</li>
<li><code>call_args_list</code> - list of mock.call() with all args ever used</li>
<li><code>method_calls</code> - track calls to methods and attributes, and their descendents</li>
<li><code>mock_calls</code> - <em>all</em> calls to the mock object</li>
</ul>
</div>
<div id="introspection-1" class="slide section level1">
<h1>Introspection</h1>
<p>Built-in assertion tests</p>
<ul>
<li><code>assert_called</code> - if ever called</li>
<li><code>assert_called_once</code> - if called exactly once</li>
<li><code>assert_called_with</code> - specific args used in the last call</li>
<li><code>assert_called_once_with</code> - specific args are used exactly once</li>
<li><code>assert_any_call</code> - specific args used in any call ever</li>
<li><code>assert_has_calls</code> - like "any_call" but with multiple calls</li>
<li><code>assert_not_called</code> - has never been called</li>
</ul>
</div>
<div id="modeling-behavior" class="slide section level1">
<h1>Modeling behavior</h1>
<p>Built-in functions that model behavior</p>
<ul>
<li><code>return_value</code> coerces a function's returned value</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="op">>>></span> mymock.return_value <span class="op">=</span> <span class="st">"Your name here"</span>
<span class="op">>>></span> mymock()
<span class="co">'Your name here'</span></code></pre></div>
<ul>
<li><code>side_effect</code> runs arbitrary code</li>
</ul>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">mocked <span class="op">=</span> Mock(spec<span class="op">=</span>MyClass)
<span class="kw">def</span> my_side_effect(some_number):
mocked.increment <span class="op">+=</span> <span class="dv">1</span>
<span class="cf">return</span> some_number <span class="op">+</span> <span class="dv">4</span>
mocked.myfunc.side_effect <span class="op">=</span> my_side_effect
<span class="cf">assert</span> mocked.myfunc(<span class="dv">4</span>) <span class="op">==</span> <span class="dv">8</span>
<span class="cf">assert</span> mocked.increment <span class="op">==</span> <span class="dv">1</span>
<span class="cf">assert</span> mocked.myfunc(<span class="dv">7</span>) <span class="op">==</span> <span class="dv">11</span>
<span class="cf">assert</span> mocked.increment <span class="op">==</span> <span class="dv">2</span></code></pre></div>
</div>
<div id="modeling-behavior-1" class="slide section level1">
<h1>Modeling behavior</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">class</span> DBWriter(<span class="bu">object</span>):
counter <span class="op">=</span> <span class="dv">0</span>
<span class="kw">def</span> <span class="fu">__init__</span>(<span class="va">self</span>):
<span class="va">self</span>.db <span class="op">=</span> DBLibrary()
<span class="kw">def</span> commit_to_db(<span class="va">self</span>, sql):
<span class="va">self</span>.counter <span class="op">+=</span> <span class="dv">1</span>
<span class="va">self</span>.db.commit(sql)
<span class="kw">def</span> save(<span class="va">self</span>, string):
sql <span class="op">=</span> <span class="st">"INSERT INTO mytable SET mystring = '{}'"</span>.<span class="bu">format</span>(string)
<span class="va">self</span>.commit_to_db(sql)
<span class="kw">def</span> drop(<span class="va">self</span>, string):
sql <span class="op">=</span> <span class="st">"DELETE FROM mytable WHERE mystring = '{}'"</span>.<span class="bu">format</span>(string)
<span class="va">self</span>.commit_to_db(sql)</code></pre></div>
<p><code>save</code> and <code>drop</code> Behavior is: - Prepare the sql statement - Write the statement to the database - Increment the counter</p>
<p>How to exercise all code without writing to DB?</p>
</div>
<div id="modeling-behavior-2" class="slide section level1">
<h1>Modeling behavior</h1>
<p>Model 1: Patch commit_to_db and model behavior</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="at">@mock.patch</span>(<span class="st">'dbwriter.DBWriter.commit_to_db'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_save(mock_commit):
writer <span class="op">=</span> DBWriter()
<span class="kw">def</span> fake_commit(<span class="va">self</span>, sql):
writer.counter <span class="op">+=</span> <span class="dv">1</span>
mock_commit.side_effect <span class="op">=</span> fake_commit
writer.save(<span class="st">"Hello World"</span>)
mock_commit.assert_called_with(writer,
<span class="st">"INSERT INTO mytable SET mystring = 'Hello World'"</span>)</code></pre></div>
<ul>
<li>Gain introspection into how <code>DBWriter</code> internals are called</li>
<li>Does not exercise any code in <code>commit_to_db</code></li>
</ul>
</div>
<div id="modeling-behavior-3" class="slide section level1">
<h1>Modeling behavior</h1>
<p>Model 2: Patch db.commit so it doesn't actually run</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="at">@mock.patch</span>(<span class="st">'namespace.of.DBLibrary'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_save(mock_dblib):
writer <span class="op">=</span> DBWriter()
writer.save(<span class="st">"Hello World"</span>)
mock_dblib.return_value.commit.assert_called_with(writer,
<span class="st">"INSERT INTO mytable SET mystring = 'Hello World'"</span>)</code></pre></div>
<ul>
<li>Full exercise of <code>DBWriter</code> internal code</li>
<li>No introspection into how <code>commit_to_db</code> is called</li>
</ul>
</div>
<div id="another-example" class="slide section level1">
<h1>Another example</h1>
<p>Mock objects provide introspection</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> get_example():
r <span class="op">=</span> requests.get(<span class="st">'http://example.com/'</span>)
<span class="cf">if</span> r.status_code <span class="op">==</span> <span class="dv">200</span>:
<span class="cf">return</span> <span class="va">True</span>
<span class="cf">else</span>:
<span class="cf">return</span> <span class="va">False</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="at">@mock.patch</span>(<span class="st">'requests.get'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_get_example_passing(mocked_get):
mocked_req_obj <span class="op">=</span> mock.Mock()
mocked_req_obj.status_code <span class="op">=</span> <span class="dv">200</span>
mocked_get.return_value <span class="op">=</span> mocked_req_obj
<span class="cf">assert</span> get_example()
<span class="cf">assert</span> mocked_get.called
<span class="cf">assert</span> mocked_get.call_args <span class="op">=</span> mock.call(<span class="st">'http://example.com/'</span>)</code></pre></div>
<p>Let's dive deeper into this</p>
</div>
<div id="another-example-1" class="slide section level1">
<h1>Another example</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> get_example():
r <span class="op">=</span> requests.get(<span class="st">'http://example.com/'</span>)
<span class="cf">if</span> r.status_code <span class="op">==</span> <span class="dv">200</span>:
<span class="cf">return</span> <span class="va">True</span>
<span class="cf">else</span>:
<span class="cf">return</span> <span class="va">False</span></code></pre></div>
<ul>
<li>The <code>requests</code> library is used for URL calls</li>
<li><code>requests.get</code> returns a <code>request</code> object and assigns to <code>r</code></li>
<li><code>r.status_code</code> is a property with the HTTP status code of the response</li>
</ul>
</div>
<div id="another-example-2" class="slide section level1">
<h1>Another example</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="at">@mock.patch</span>(<span class="st">'requests.get'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_get_example_passing(mocked_get):
mocked_req_obj <span class="op">=</span> mock.Mock()
mocked_req_obj.status_code <span class="op">=</span> <span class="dv">200</span>
mocked_get.return_value <span class="op">=</span> mocked_req_obj
<span class="cf">assert</span> get_example()
mocked_get.assert_called()
mocked_get.assert_called_with(<span class="st">'http://example.com/'</span>)</code></pre></div>
<ul>
<li>Just like earlier, <code>@mock.patch</code> specs & replaces <code>requests.get</code> with a mock that gets passed into <code>mocked_get</code> and give it the <code>status_code</code> property</li>
<li>We then create <code>mocked_req_obj</code> and bolt it into the <code>return_value</code> of <code>mocked_get</code></li>
<li>Now when we run <code>get_example</code> we exercise the code without calling the outside.</li>
</ul>
</div>
<div id="another-example-3" class="slide section level1">
<h1>Another example</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="at">@mock.patch</span>(<span class="st">'requests.get'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_get_example_passing(mocked_get):
mocked_req_obj <span class="op">=</span> mock.Mock()
mocked_req_obj.status_code <span class="op">=</span> <span class="dv">400</span>
mocked_get.return_value <span class="op">=</span> mocked_req_obj
<span class="cf">assert</span> get_example()
mocked_get.assert_called()
mocked_get.assert_called_with(<span class="st">'http://example.com/'</span>)</code></pre></div>
</div>
<div id="another-example-4" class="slide section level1">
<h1>Another example</h1>
<p>How do I mock something used twice?</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># yourcode.py</span>
<span class="im">from</span> some.library <span class="im">import</span> AnotherThing
<span class="kw">class</span> MyClass(<span class="bu">object</span>):
<span class="kw">def</span> <span class="fu">__init__</span>(<span class="va">self</span>, this, that):
<span class="va">self</span>.this <span class="op">=</span> AnotherThing(this)
<span class="va">self</span>.that <span class="op">=</span> AnotherThing(that)
<span class="kw">def</span> do_this(<span class="va">self</span>):
<span class="va">self</span>.this.do()
<span class="kw">def</span> do_that(<span class="va">self</span>):
<span class="va">self</span>.that.do()
<span class="kw">def</span> do_more(<span class="va">self</span>):
got_it <span class="op">=</span> <span class="va">self</span>.this.get_it()
that_too <span class="op">=</span> <span class="va">self</span>.that.do_it(got_it)
<span class="cf">return</span> that_too</code></pre></div>
<p>Patching some.library.AnotherThing doesn't help directly, because AnotherThing just becomes the same mock.</p>
</div>
<div id="another-example-5" class="slide section level1">
<h1>Another example</h1>
<p>Replace in the instance</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> test_my_class():
my_obj <span class="op">=</span> MyClass(<span class="st">"fake this"</span>, <span class="st">"fake that"</span>)
my_obj.this <span class="op">=</span> Mock(spec_set<span class="op">=</span><span class="st">'some.library.AnotherThing'</span>)
my_obj.that <span class="op">=</span> Mock(spec_set<span class="op">=</span><span class="st">'some.library.AnotherThing'</span>)
my_obj.do_this()
my_obj.this.do.assert_called()
my_obj.do_that()
my_obj.that.do.assert_called()</code></pre></div>
</div>
<div id="another-example-6" class="slide section level1">
<h1>Another example</h1>
<p>Patch the namespace</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="at">@patch</span>(<span class="st">'yourcode.AnotherThing'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_my_class(mock_thing):
<span class="kw">def</span> fake_init(<span class="op">*</span>args):
<span class="cf">return</span> Mock(args)
mock_thing.side_effect <span class="op">=</span> fake_init
my_obj <span class="op">=</span> MyClass(<span class="st">"fake this"</span>, <span class="st">"fake that"</span>)
my_obj.this.called_with(<span class="st">"fake this"</span>)
my_obj.that.called_with(<span class="st">"fake that"</span>)</code></pre></div>
</div>
<div id="when-to-use-a-mock" class="slide section level1">
<h1>When to use a mock</h1>
<p>Replace a part of your code with a mock so it pretends like it's doing something</p>
<ul>
<li>Command-line execution</li>
<li>State changes</li>
<li>External API</li>
<li>Really slow procedures</li>
<li>Already well-tested code</li>
</ul>
<p>Remember, this is for unit-testing, not acceptance/integration testing!</p>
</div>
<div id="when-to-use-a-mock-1" class="slide section level1">
<h1>When to use a mock</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># yourcode.py</span>
<span class="kw">def</span> wipe_directory(path):
p <span class="op">=</span> Popen([<span class="st">'rm'</span>, <span class="st">'-rf'</span>, path], stdout<span class="op">=</span>PIPE, stderr<span class="op">=</span>PIPE)
<span class="cf">if</span> p.wait():
<span class="cf">raise</span> <span class="pp">Exception</span>(<span class="st">'We had a fail'</span>)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># test.py</span>
<span class="at">@mock.patch</span>(<span class="st">'subprocess.Popen'</span>, spec_set<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_count_the_shells(mocked_popen):
mocked_popen.return_value.wait.return_value <span class="op">=</span> <span class="va">False</span>
wipe_directory(<span class="st">'fakepath'</span>)
<span class="cf">assert</span> mocked_popen.assert_called_with([<span class="st">'rm'</span>, <span class="st">'-rf'</span>, path], stdout<span class="op">=</span>PIPE, stderr<span class="op">=</span>PIPE)</code></pre></div>
</div>
<div id="when-to-use-a-mock-2" class="slide section level1">
<h1>When to use a mock</h1>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># yourcode.py</span>
<span class="kw">def</span> get_example():
r <span class="op">=</span> requests.post(<span class="st">'http://example.com/'</span>,
data<span class="op">=</span>{<span class="st">'delete'</span>: <span class="st">'everything'</span>, <span class="st">'autocommit'</span>: <span class="st">'true'</span>})
<span class="cf">if</span> r.status_code <span class="op">==</span> <span class="dv">200</span>:
<span class="bu">print</span>(<span class="st">'All things have been deleted'</span>)
<span class="cf">return</span> <span class="va">True</span>
<span class="cf">else</span>:
<span class="bu">print</span>(<span class="st">'Got an error: {}'</span>.<span class="bu">format</span>(r.headers))
<span class="cf">return</span> <span class="va">False</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># test.py</span>
<span class="at">@mock.patch</span>(<span class="st">'requests.post'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_get_example_passing(mocked_get):
mocked_req_obj <span class="op">=</span> mock.Mock()
mocked_req_obj.status_code <span class="op">=</span> <span class="dv">200</span>
mocked_get.return_value <span class="op">=</span> mocked_req_obj
<span class="cf">assert</span> get_example()
<span class="cf">assert</span> mocked_get.called
<span class="at">@mock.patch</span>(<span class="st">'requests.get'</span>, autospec<span class="op">=</span><span class="va">True</span>)
<span class="kw">def</span> test_get_example_failing(mocked_get):
mocked_get.return_value.status_code <span class="op">=</span> <span class="dv">400</span>
<span class="cf">assert</span> <span class="op">not</span> get_example()
<span class="cf">assert</span> mocked_get.called</code></pre></div>
</div>
<div id="when-not-to-use-a-mock" class="slide section level1">
<h1>When not to use a mock</h1>
<ul>
<li>Never mock the filesystem</li>
<li>Be judicious about mocking shared libraries (integration tests)</li>
<li>When you actually <em>want</em> to talk to an API or CLI (acceptance tests)</li>
</ul>
</div>
<div id="when-not-to-use-a-mock-1" class="slide section level1">
<h1>When not to use a mock</h1>
<p>The mock library does provide file-like objects for mocks, but the filesystem is very nuanced. It's much better to just write temporary files. Use mocks to amend how to write those files out.</p>
</div>
<div id="when-not-to-use-a-mock-2" class="slide section level1">
<h1>When not to use a mock</h1>
<p>General rules for when to use a mock:</p>
<ul>
<li>Look for where your code talks to things that are not your code. You most likely want to mock that.</li>
<li>Look for where a unit your code requires isolation from the rest of your code for a good test. You most likely want to mock that</li>
<li>Never mock the file system</li>
</ul>
</div>
<div id="summary" class="slide section level1">
<h1>Summary</h1>
<ul>
<li>Mock to isolate your code from the outside world (and vice versa)</li>
<li>Mock to inspect inner behavior</li>
<li>Mock speed up unit tests</li>
<li>Above all else, write tests!</li>
</ul>
</div>
<div id="thank-you" class="slide section level1">
<h1>Thank you!</h1>
<dl>
<dt>Author</dt>
<dd><p>Brian Weber, SRE at Twitter</p>
</dd>
<dt>Contact</dt>
<dd><p><script type="text/javascript">
<!--
h='twitter.com';a='@';n='bweber';e=n+a+h;
document.write('<a h'+'ref'+'="ma'+'ilto'+':'+e+'" clas'+'s="em' + 'ail">'+e+'<\/'+'a'+'>');
// -->
</script><noscript>bweber at twitter dot com</noscript></p>
</dd>
<dt>Twitter</dt>
<dd><p>@mistermocha</p>
</dd>
<dt>Link</dt>
<dd><p><a href="https://github.com/mistermocha/python-mock-talk/" class="uri">https://github.com/mistermocha/python-mock-talk/</a></p>
</dd>
</dl>
</div>
</body>
</html>