Repository navigation
Expand file tree
/
Copy pathIntro_to_Testing.html
More file actions
640 lines (496 loc) · 59.8 KB
/
Copy pathIntro_to_Testing.html
File metadata and controls
640 lines (496 loc) · 59.8 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
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta content="Topic: Writing tests for your code, Difficulty: Easy, Category: Section" name="description" />
<meta content="test, automated, unit, assert" name="keywords" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Introduction to Testing — Python Like You Mean It</title>
<script type="text/javascript" src="../_static/js/modernizr.min.js"></script>
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script type="text/javascript" src="https://www.googletagmanager.com/gtag/js?id=UA-115029372-1"></script>
<script type="text/javascript" src="../_static/gtag.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<script type="text/javascript" src="../_static/js/theme.js"></script>
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../_static/my_theme.css" type="text/css" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="The pytest Framework" href="Pytest.html" />
<link rel="prev" title="Module 6: Testing Our Code" href="../module_6.html" />
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search" >
<a href="../index.html" class="icon icon-home"> Python Like You Mean It
</a>
<div class="version">
1.4
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<p class="caption"><span class="caption-text">Table of Contents:</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../intro.html">Python Like You Mean It</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_1.html">Module 1: Getting Started with Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_2.html">Module 2: The Essentials of Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_2_problems.html">Module 2: Problems</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_3.html">Module 3: The Essentials of NumPy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_3_problems.html">Module 3: Problems</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_4.html">Module 4: Object Oriented Programming</a></li>
<li class="toctree-l1"><a class="reference internal" href="../module_5.html">Module 5: Odds and Ends</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../module_6.html">Module 6: Testing Our Code</a><ul class="current">
<li class="toctree-l2 current"><a class="current reference internal" href="#">Introduction to Testing</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#Why-Should-We-Write-Tests?">Why Should We Write Tests?</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Writing-Our-First-Tests">Writing Our First Tests</a><ul>
<li class="toctree-l4"><a class="reference internal" href="#Our-“Source-Code”">Our “Source Code”</a></li>
<li class="toctree-l4"><a class="reference internal" href="#The-Basic-Anatomy-of-a-Test">The Basic Anatomy of a Test</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="#The-assert-Statement">The <code class="docutils literal notranslate"><span class="pre">assert</span></code> Statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Testing-Our-Tests">Testing Our Tests</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Our-Work,-Cut-Out">Our Work, Cut Out</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Links-to-Official-Documentation">Links to Official Documentation</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Reading-Comprehension-Solutions">Reading Comprehension Solutions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="Pytest.html">The pytest Framework</a></li>
<li class="toctree-l2"><a class="reference internal" href="Hypothesis.html">Describing Data with Hypothesis</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../changes.html">Changelog</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">Python Like You Mean It</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html">Docs</a> »</li>
<li><a href="../module_6.html">Module 6: Testing Our Code</a> »</li>
<li>Introduction to Testing</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/Module6_Testing/Intro_to_Testing.md.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<style>
/* CSS overrides for sphinx_rtd_theme */
/* 24px margin */
.nbinput.nblast,
.nboutput.nblast {
margin-bottom: 19px; /* padding has already 5px */
}
/* ... except between code cells! */
.nblast + .nbinput {
margin-top: -19px;
}
.admonition > p:before {
margin-right: 4px; /* make room for the exclamation icon */
}
/* Fix math alignment, see https://github.com/rtfd/sphinx_rtd_theme/pull/686 */
.math {
text-align: unset;
}
</style>
<div class="section" id="Introduction-to-Testing">
<h1>Introduction to Testing<a class="headerlink" href="#Introduction-to-Testing" title="Permalink to this headline">¶</a></h1>
<p>This section will show us just how simple it is to write rudimentary tests. We need only recall some of Python’s basic scoping rules and introduce ourselves to the <code class="docutils literal notranslate"><span class="pre">assert</span></code> statement to write a genuine test function. That being said, we will quickly encounter some important questions to ponder. How do we know that our tests work? And, how do we know that our tests are effective? These questions will drive us deeper into the world of testing.</p>
<p>Before we hit the ground running, let’s take a moment to consider some motivations for testing out code.</p>
<div class="section" id="Why-Should-We-Write-Tests?">
<h2>Why Should We Write Tests?<a class="headerlink" href="#Why-Should-We-Write-Tests?" title="Permalink to this headline">¶</a></h2>
<p>The fact of the matter is that it is intuitive for most people to test their code to some extent. After writing, say, a new function, it is only natural to contrive an input to feed it, and to check that the function returns the output that we expected. To the extent that one would want to see evidence that their code works, we need not motivate the importance of testing.</p>
<p>Less obvious are the massive benefits that we stand to gain from automating this testing process. By “automating”, we mean taking the test scenarios that we were running our code through, and encapsulating them in their own functions that can be run from end-to-end. We will accumulate these test functions into a “test suite” that we can run quickly and repeatedly.</p>
<p>There are plenty of practical details ahead for us to learn, so let’s expedite this discussion and simply list some of the benefits that we can expect to reap from writing a robust test suite:</p>
<p><strong>It saves us lots of time</strong>:</p>
<blockquote>
<div><p>After you have devised a test scenario for your code, it may only take us a second or so to run it; perhaps we need only run a couple of Jupyter notebook cells to verify the output of our code. This, however, will quickly become unwieldy as we write more code and devise more test scenarios. Soon we will be dissuaded from running our tests, except for on rare occasions.</p>
<p>With a proper test suite, we can run all of our test scenarios with the push of a button, and a series of green check-marks (or red x’s…) will summarize the health of our project (insofar as our tests serve as good diagnostics). This, of course, also means that we will find and fix bugs much faster! In the long run, our test suite will afford us the ability to aggressively exercise (and exorcise) our code at little cost.</p>
</div></blockquote>
<p><strong>It increases the “shelf life” of our code:</strong></p>
<blockquote>
<div>If you’ve ever dusted off a project that you haven’t used for years (or perhaps only months or weeks…), you might know the tribulations of getting old code to work. Perhaps, in the interim, new versions of our project’s dependencies, like PyTorch or Matplotlib, were released and have incompatibilities with our project’s code. And perhaps <em>we can’t even remember</em> all of the ways in which our project is supposed to work. Our test suite provides us with a simple and incisive way to dive back
into our work. It will point us to any potential incompatibilities that have accumulated over time. It also provides us with a large collection of detailed use-cases of our code; we can read through our tests and remind ourselves of the inner-workings of our project.</div></blockquote>
<p><strong>It will inform the design and usability of our project for the better:</strong></p>
<blockquote>
<div>Although it may not be obvious from the outset, writing testable code leads to writing better code. This is, in part, because the process of writing tests gives us the opportunity to actually <em>use</em> our code under varied circumstances. The process of writing tests will help us suss out bad design decisions and redundancies in our code. Ultimately, if <em>we</em> find it frustrating to use our code within our tests, then surely others will find the code frustrating to use in applied settings.</div></blockquote>
<p><strong>It makes it easier for others to contribute to a project:</strong></p>
<blockquote>
<div>Having a healthy test suite lowers the barrier to entry for a project. A contributor can rely on our project’s tests to quickly check to see if their changes to our code have broken the project or changed any of its behavior in unexpected ways.</div></blockquote>
<p>This all sounds great, but where do we even start the process of writing a test suite? Let’s begin by seeing what constitutes a basic test function.</p>
</div>
<div class="section" id="Writing-Our-First-Tests">
<h2>Writing Our First Tests<a class="headerlink" href="#Writing-Our-First-Tests" title="Permalink to this headline">¶</a></h2>
<div class="section" id="Our-“Source-Code”">
<h3>Our “Source Code”<a class="headerlink" href="#Our-“Source-Code”" title="Permalink to this headline">¶</a></h3>
<p>We need some code to test. For the sake of this introduction, let’s borrow a couple of functions that may look familiar from previous modules. These will serve as our “source code”; i.e. these are functions that we have written for our project and that need to be tested.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># Defining functions that we will be testing</span>
<span class="k">def</span> <span class="nf">count_vowels</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span>
<span class="sd">"""Returns the number of vowels contained in `x`.</span>
<span class="sd"> The vowel 'y' is included optionally.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> x : str</span>
<span class="sd"> The input string</span>
<span class="sd"> include_y : bool, optional (default=False)</span>
<span class="sd"> If `True` count y's as vowels</span>
<span class="sd"> Returns</span>
<span class="sd"> -------</span>
<span class="sd"> vowel_count: int</span>
<span class="sd"> Examples</span>
<span class="sd"> --------</span>
<span class="sd"> >>> count_vowels("happy")</span>
<span class="sd"> 1</span>
<span class="sd"> >>> count_vowels("happy", include_y=True)</span>
<span class="sd"> 2</span>
<span class="sd"> """</span>
<span class="n">vowels</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s2">"aeiouAEIOU"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">include_y</span><span class="p">:</span>
<span class="n">vowels</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">"yY"</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="mi">1</span> <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">x</span> <span class="k">if</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">vowels</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">merge_max_mappings</span><span class="p">(</span><span class="n">dict1</span><span class="p">,</span> <span class="n">dict2</span><span class="p">):</span>
<span class="sd">""" Merges two dictionaries based on the largest value</span>
<span class="sd"> in a given mapping.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> dict1 : Dict[str, float]</span>
<span class="sd"> dict2 : Dict[str, float]</span>
<span class="sd"> Returns</span>
<span class="sd"> -------</span>
<span class="sd"> merged : Dict[str, float]</span>
<span class="sd"> The dictionary containing all of the keys common</span>
<span class="sd"> between `dict1` and `dict2`, retaining the largest</span>
<span class="sd"> value from common mappings.</span>
<span class="sd"> Examples</span>
<span class="sd"> --------</span>
<span class="sd"> >>> x = {"a": 1, "b": 2}</span>
<span class="sd"> >>> y = {"b": 100, "c": -1}</span>
<span class="sd"> >>> merge_max_mappings(x, y)</span>
<span class="sd"> {'a': 1, 'b': 100, 'c': -1}</span>
<span class="sd"> """</span>
<span class="c1"># `dict(dict1)` makes a copy of `dict1`. We do this</span>
<span class="c1"># so that updating `merged` doesn't also update `dict1`</span>
<span class="n">merged</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">dict1</span><span class="p">)</span>
<span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">dict2</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="k">if</span> <span class="n">key</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">merged</span> <span class="ow">or</span> <span class="n">value</span> <span class="o">></span> <span class="n">merged</span><span class="p">[</span><span class="n">key</span><span class="p">]:</span>
<span class="n">merged</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
<span class="k">return</span> <span class="n">merged</span>
</pre></div>
</div>
<p>As always, it is useful for us to follow along with this material in a Jupyter notebook. We ought to take time to define these functions and run inputs through them to make sure that we understand what they are doing. Testing code that we don’t understand is a lost cause!</p>
</div>
<div class="section" id="The-Basic-Anatomy-of-a-Test">
<h3>The Basic Anatomy of a Test<a class="headerlink" href="#The-Basic-Anatomy-of-a-Test" title="Permalink to this headline">¶</a></h3>
<p>Let’s write a test for <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code>. For our most basic test, we can simply call <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> under various contrived inputs and <em>assert</em> that it returns the expected output. The desired behavior for this test function, upon being run, is to:</p>
<ul class="simple">
<li>Raise an error if any of our assertions <em>failed</em> to hold true.</li>
<li>Complete “silently” if all of our assertions hold true (i.e. our test function will simply <a class="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#The-return-Statement">return None</a>)</li>
</ul>
<p>Here, we will be making use of Python’s <code class="docutils literal notranslate"><span class="pre">assert</span></code> statements, whose behavior will be easy to deduce from the context of this test alone. We will be formally introduced to the <code class="docutils literal notranslate"><span class="pre">assert</span></code> statement soon.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># Writing a rudimentary test function for `count_vowels`</span>
<span class="k">def</span> <span class="nf">test_count_vowels_basic</span><span class="p">():</span>
<span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">"aA bB yY"</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="o">==</span> <span class="mi">2</span>
<span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">"aA bB yY"</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="o">==</span> <span class="mi">4</span>
</pre></div>
</div>
<p>To run this test, we simply call the function:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># running our test function</span>
<span class="o">>>></span> <span class="n">test_count_vowels_basic</span><span class="p">()</span> <span class="c1"># passes: returns None | fails: raises error</span>
</pre></div>
</div>
<p>As described above, the fact our function runs and simply returns <code class="docutils literal notranslate"><span class="pre">None</span></code> (i.e. we see no output when we run this test in a console or notebook cell) means that our code has passed this test. We’ve written and run our very first test! It certainly isn’t the most robust test, but it is a good start.</p>
<p>Let’s look more carefully at the structure of <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code>. Note that this function doesn’t take in any inputs; thanks to <a class="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Scope.html">Python’s scoping rules</a>, we can reference our <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> function within our test as long as it is defined in the same “namespace” as <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code>. That is, we can either define <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> in the same .py file (or Jupyter notebook, if you are following
along with this material in a notebook) as <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code>, or we can <a class="reference external" href="https://www.pythonlikeyoumeanit.com/Module5_OddsAndEnds/Modules_and_Packages.html#Import-Statements">import</a> <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code>, from wherever it is defined, into the file containing our test. The latter scenario is by far the most common one in practice. More on this later.</p>
<div class="admonition warning">
<p class="admonition-title fa fa-exclamation-circle"><strong>Takeaway</strong>:</p>
<p>A “test function” is designed to provide an encapsulated “environment” (namespace to be more precise) in which we can exercise parts of our source code and assert that the code behaves as expected. The basic anatomy of a test function is such that it:</p>
<ul class="simple">
<li>contains one or more <code class="docutils literal notranslate"><span class="pre">assert</span></code> statements, each of which will raise an error if our source code misbehaves</li>
<li>simply returns <code class="docutils literal notranslate"><span class="pre">None</span></code> if all of the aforementioned assertions held true</li>
<li>can be run end-to-end simply by calling the test function without passing it any parameters; we rely on Python’s scoping rules to call our source code within the body of the test function without explicitly passing anything to said test function</li>
</ul>
</div>
<div class="admonition note">
<p class="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: Adding Assertions to a Test</strong></p>
<p>Add an additional assertion to the body of <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code>, which tests that <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> handles empty-string (<code class="docutils literal notranslate"><span class="pre">""</span></code>) input appropriately. Make sure to run your updated test to see if it passes.</p>
</div>
<div class="admonition note">
<p class="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: The Basic Anatomy of a Test</strong></p>
<p>Write a rudimentary test function for <code class="docutils literal notranslate"><span class="pre">merge_max_mappings</span></code>. This should adhere to the basic structure of a test function that we just laid out. See if you can think of some “edge cases” to test, which we may have overlooked when writing <code class="docutils literal notranslate"><span class="pre">merge_max_mappings</span></code>.</p>
</div>
</div>
</div>
<div class="section" id="The-assert-Statement">
<h2>The <code class="docutils literal notranslate"><span class="pre">assert</span></code> Statement<a class="headerlink" href="#The-assert-Statement" title="Permalink to this headline">¶</a></h2>
<p>With our first test functions under our belt, it is time for us to clearly understand how <code class="docutils literal notranslate"><span class="pre">assert</span></code> statements work and how they should be used.</p>
<p>Similar to <code class="docutils literal notranslate"><span class="pre">return</span></code>, <code class="docutils literal notranslate"><span class="pre">def</span></code>, or <code class="docutils literal notranslate"><span class="pre">if</span></code>, the term <code class="docutils literal notranslate"><span class="pre">assert</span></code> is a reserved term in the Python language. It has the following specialized behavior:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># demonstrating the rudimentary behavior of the `assert` statement</span>
<span class="c1"># asserting an expression whose boolean-value is `True` will complete "silently"</span>
<span class="o">>>></span> <span class="k">assert</span> <span class="mi">1</span> <span class="o"><</span> <span class="mi">2</span>
<span class="c1"># asserting an expression whose boolean-value is `False` raises an error</span>
<span class="o">>>></span> <span class="k">assert</span> <span class="mi">2</span> <span class="o"><</span> <span class="mi">1</span>
<span class="o">---------------------------------------------------------------------------</span>
<span class="ne">AssertionError</span> <span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">)</span>
<span class="o"><</span><span class="n">ipython</span><span class="o">-</span><span class="nb">input</span><span class="o">-</span><span class="mi">5</span><span class="o">-</span><span class="n">c82711d5fe4d</span><span class="o">></span> <span class="ow">in</span> <span class="o"><</span><span class="n">module</span><span class="o">></span>
<span class="o">----></span> <span class="mi">1</span> <span class="k">assert</span> <span class="mi">2</span> <span class="o"><</span> <span class="mi">1</span>
<span class="ne">AssertionError</span><span class="p">:</span>
<span class="c1"># we can include an error message with our assertion</span>
<span class="o">>>></span> <span class="k">assert</span> <span class="mi">0</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="s2">"0 is not in the list"</span>
<span class="o">---------------------------------------------------------------------------</span>
<span class="ne">AssertionError</span> <span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">)</span>
<span class="o"><</span><span class="n">ipython</span><span class="o">-</span><span class="nb">input</span><span class="o">-</span><span class="mi">8</span><span class="o">-</span><span class="n">e72fb36dc785</span><span class="o">></span> <span class="ow">in</span> <span class="o"><</span><span class="n">module</span><span class="o">></span>
<span class="o">----></span> <span class="mi">1</span> <span class="k">assert</span> <span class="mi">0</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="s2">"0 is not in the list"</span>
<span class="ne">AssertionError</span><span class="p">:</span> <span class="mi">0</span> <span class="ow">is</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">the</span> <span class="nb">list</span>
</pre></div>
</div>
<p>The general form of an assertion statement is:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">assert</span> <span class="o"><</span><span class="n">expression</span><span class="o">></span> <span class="p">[,</span> <span class="o"><</span><span class="n">error</span><span class="o">-</span><span class="n">message</span><span class="o">></span><span class="p">]</span>
</pre></div>
</div>
<p>When an assertion statement is executed, the built-in <code class="docutils literal notranslate"><span class="pre">bool</span></code> function is called on the object that is returned by <code class="docutils literal notranslate"><span class="pre"><expression></span></code>; if <code class="docutils literal notranslate"><span class="pre">bool(<expression>)</span></code> returns <code class="docutils literal notranslate"><span class="pre">False</span></code>, then an <code class="docutils literal notranslate"><span class="pre">AssertionError</span></code> is raised. If you included a string in the assertion statement - separated from <code class="docutils literal notranslate"><span class="pre"><expression></span></code> by a comma - then this string will be printed as the error message.</p>
<p>See that the assertion statement:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">assert</span> <span class="n">expression</span><span class="p">,</span> <span class="n">error_message</span>
</pre></div>
</div>
<p>is effectively shorthand for the following code (barring some additional details):</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># long-form equivalent of: `assert expression, error_message`</span>
<span class="k">if</span> <span class="nb">bool</span><span class="p">(</span><span class="n">expression</span><span class="p">)</span> <span class="ow">is</span> <span class="bp">False</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="n">error_message</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: Assertions</strong></p>
<p>Given the following objects:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">a_number</span> <span class="o">=</span> <span class="mi">22</span>
<span class="n">a_string</span> <span class="o">=</span> <span class="s2">"abcdef"</span>
</pre></div>
</div>
<p>Write two assertion statements with the respective behaviors:</p>
<ul class="simple">
<li>asserts that <code class="docutils literal notranslate"><span class="pre">a_list</span></code> is <em>not</em> empty</li>
<li>asserts that the number of vowels in <code class="docutils literal notranslate"><span class="pre">a_string</span></code> is less than <code class="docutils literal notranslate"><span class="pre">a_number</span></code>; include an error message that prints the actual number of vowels</li>
</ul>
</div>
<p>In our code, an assertion should be used as <em>a statement that is true unless there is a bug in our code</em>. It is plain to see that the assertions in <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code> fit this description. However, it can also be useful to include assertions within our source code itself. For instance, we know that <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> should always return a non-negative integer for the vowel-count, and that it is illogical for this count to exceed the number of characters in the input string. We can
explicitly assert that this is the case:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># an example of including an assertion within our source code</span>
<span class="k">def</span> <span class="nf">count_vowels</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">include_y</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="bp">False</span><span class="p">)</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span>
<span class="n">vowels</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s2">"aeiouAEIOU"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">include_y</span><span class="p">:</span>
<span class="n">vowels</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">"yY"</span><span class="p">)</span>
<span class="n">count</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="mi">1</span> <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">x</span> <span class="k">if</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">vowels</span><span class="p">)</span>
<span class="c1"># This assertion should always be true: it is asserting that</span>
<span class="c1"># the internal logic of our function is correct</span>
<span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">count</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span> <span class="ow">and</span> <span class="mi">0</span> <span class="o"><=</span> <span class="n">count</span> <span class="o"><=</span> <span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="k">return</span> <span class="n">count</span>
</pre></div>
</div>
<p>Note that this assertion <em>is not meant to check if the user passed bad inputs for</em> <code class="docutils literal notranslate"><span class="pre">x</span></code> <em>and</em> <code class="docutils literal notranslate"><span class="pre">include_y</span></code>. Rather, it is meant to assert that our own internal logic holds true.</p>
<p>Admittedly, the <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> function is simple enough that the inclusion of this assertion is rather pedantic. That being said, as we write increasingly sophisticated code, we will find that this sort of assertion will help us catch bad internal logic and oversights within our code base. We will also see that keen use of assertions can make it much easier for us to write good tests.</p>
<div class="admonition warning">
<p class="admonition-title fa fa-exclamation-circle"><strong>Disabling Assertions</strong>:</p>
<p>Python code can be run in an “optimized” mode such that <em>all assertions are skipped by the Python interpreter during execution</em>. This can be achieved by specifying the command line option <code class="docutils literal notranslate"><span class="pre">-O</span></code> (the letter “O”, not zero), e.g.:</p>
<div class="highlight-shell notranslate"><div class="highlight"><pre><span></span>python -O my_code.py
</pre></div>
</div>
<p>or by setting the <code class="docutils literal notranslate"><span class="pre">PYTHONOPTIMIZE</span></code> <a class="reference external" href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONOPTIMIZE">environment variable</a>.</p>
<p>The idea here is that we may want assertions within our source code to perform expensive checks to guarantee internal consistency within our code, and that we want the ability to forgo these checks when we are no longer debugging our code. Because they can be skipped in this way, <em>assertions should never be used for practical error handling</em>.</p>
</div>
</div>
<div class="section" id="Testing-Our-Tests">
<h2>Testing Our Tests<a class="headerlink" href="#Testing-Our-Tests" title="Permalink to this headline">¶</a></h2>
<p>It is surprisingly easy to unwittingly write a broken test: a test that always passes, or a test that simply doesn’t exercise our code in the way that we had intended. Broken tests are insidious; they are alarms that fail to sound when they are supposed to. They create misdirection in the bug-finding process and can mask problems with our code. <strong>Thus, a critical step in the test-writing process is to intentionally mutate the function of interest - to corrupt its behavior so that we can verify
that our test works.</strong> Once we confirm that our test does indeed raise an error as expected, we restore the function to its original form and re-run the test to see that it passes.</p>
<p>A practical note: we ought to mutate our function in a way that is trivial to undo. We can make use of code-comments towards this end. All <a class="reference external" href="https://www.pythonlikeyoumeanit.com/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.html">IDEs</a> have the ability to “block-comment” selected code. In order to block-comment code in a Jupyter notebook code cell, highlight the lines of code and press <code class="docutils literal notranslate"><span class="pre">CTRL</span> <span class="pre">+</span> <span class="pre">/</span></code>. The same key-combination will also un-comment a highlighted block of
commented code.</p>
<div class="admonition note">
<p class="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: Testing Your Test via Manual Mutation</strong></p>
<p>Temporarily change the body of <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> such that the second assertion in <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code> raises an error. Run the test to confirm that the second assertion raises, and then restore <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> to its original form. Finally, rerun the test to see that <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> once again passes all of the assertions.</p>
<p>Repeat this process given the test that you wrote for <code class="docutils literal notranslate"><span class="pre">merge_max_mappings</span></code>. Try breaking the function such that it always merges in values from <code class="docutils literal notranslate"><span class="pre">dict2</span></code>, even if those values are smaller.</p>
</div>
<div class="admonition warning">
<p class="admonition-title fa fa-exclamation-circle"><strong>Mutation Testing</strong>:</p>
<p>There is an entire subfield of automated testing known as <a class="reference external" href="https://en.wikipedia.org/wiki/Mutation_testing">“mutation testing”</a>, where tools like <a class="reference external" href="https://cosmic-ray.readthedocs.io/en/latest/index.html">Cosmic Ray</a> are used to make temporary, incisive mutations to your source code - like change a <code class="docutils literal notranslate"><span class="pre">+</span></code> to a <code class="docutils literal notranslate"><span class="pre">-</span></code> or change a <code class="docutils literal notranslate"><span class="pre">1</span></code> to a <code class="docutils literal notranslate"><span class="pre">-1</span></code> - and then run your test suite. The idea here is that such mutations <em>ought to cause one or more of your tests to fail</em>. A mutation that does not
trigger at least one test failure is likely an indicator that your tests could stand to be more robust.</p>
<p>Automated mutation testing tools might be a bit too “heavy duty” at this point in our testing journey, but they are great to keep in mind.</p>
</div>
</div>
<div class="section" id="Our-Work,-Cut-Out">
<h2>Our Work, Cut Out<a class="headerlink" href="#Our-Work,-Cut-Out" title="Permalink to this headline">¶</a></h2>
<p>We see now that the concept of a “test function” isn’t all that fancy. Compared to other code that we have written, writing a function that simply runs a handful of assertions is far from a heavy lift for us. Of course, we must be diligent and take care to test our tests, but we can certainly manage this as well. With this in hand, we should take stock of the work and challenges that lie in our path ahead.</p>
<p>It is necessary that we evolve beyond manual testing. There are multiple facets to this observation. First, we must learn how to organize our test functions into a test suite that can be run in one fell swoop. Next, it will become increasingly apparent that a test function often contains large amounts of redundant code shared across its litany of assertions. We will want to “parametrize” our tests to distill them down to their most concise and functional forms. Finally, and most importantly, it
may already be evident that the process of contriving known inputs and outputs to use in our tests is a highly manual and tedious process; furthermore, it is a process that will become increasingly cumbersome as our source code becomes more sophisticated. To combat this, we will seek out alternative, powerful testing methodologies, including property-based testing.</p>
</div>
<div class="section" id="Links-to-Official-Documentation">
<h2>Links to Official Documentation<a class="headerlink" href="#Links-to-Official-Documentation" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li><a class="reference external" href="https://docs.python.org/3/reference/simple_stmts.html?highlight=assert#the-assert-statement">The assert statement</a></li>
<li><a class="reference external" href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONOPTIMIZE">PYTHONOPTIMIZE environment variable</a></li>
</ul>
</div>
<div class="section" id="Reading-Comprehension-Solutions">
<h2>Reading Comprehension Solutions<a class="headerlink" href="#Reading-Comprehension-Solutions" title="Permalink to this headline">¶</a></h2>
<p><strong>Adding Assertions to a Test: Solution</strong></p>
<p>Add an additional assertion to the body of <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code>, which tests whether <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> handles the empty-string (<code class="docutils literal notranslate"><span class="pre">""</span></code>) case appropriately. Make sure to run your updated test to see if it passes.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test_count_vowels_basic</span><span class="p">():</span>
<span class="c1"># test basic strings with uppercase and lowercase letters</span>
<span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">"aA bB yY"</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="o">==</span> <span class="mi">2</span>
<span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">"aA bB yY"</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="o">==</span> <span class="mi">4</span>
<span class="c1"># test empty strings</span>
<span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">""</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>
<span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">""</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>
</pre></div>
</div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># running the test in a notebook-cell: the function should simply return</span>
<span class="c1"># `None` if all assertions hold true</span>
<span class="o">>>></span> <span class="n">test_count_vowels_basic</span><span class="p">()</span>
</pre></div>
</div>
<p><strong>The Basic Anatomy of a Test: Solution</strong></p>
<p>Write a rudimentary test function for <code class="docutils literal notranslate"><span class="pre">merge_max_mappings</span></code>.</p>
<blockquote>
<div>Let’s test the use case that is explicitly documented in the Examples section of the function’s docstring. We can also test cases where one or both of the inputs are empty dictionaries. These can often be problematic edge cases that we didn’t consider when writing our code.</div></blockquote>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test_merge_max_mappings</span><span class="p">():</span>
<span class="c1"># test documented behavior</span>
<span class="n">dict1</span> <span class="o">=</span> <span class="p">{</span><span class="s2">"a"</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">"b"</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span>
<span class="n">dict2</span> <span class="o">=</span> <span class="p">{</span><span class="s2">"b"</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span> <span class="s2">"c"</span><span class="p">:</span> <span class="o">-</span><span class="mi">1</span><span class="p">}</span>
<span class="n">expected</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'a'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">:</span> <span class="o">-</span><span class="mi">1</span><span class="p">}</span>
<span class="k">assert</span> <span class="n">merge_max_mappings</span><span class="p">(</span><span class="n">dict1</span><span class="p">,</span> <span class="n">dict2</span><span class="p">)</span> <span class="o">==</span> <span class="n">expected</span>
<span class="c1"># test empty dict1</span>
<span class="n">dict1</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">dict2</span> <span class="o">=</span> <span class="p">{</span><span class="s2">"a"</span><span class="p">:</span> <span class="mf">10.2</span><span class="p">,</span> <span class="s2">"f"</span><span class="p">:</span> <span class="o">-</span><span class="mf">1.0</span><span class="p">}</span>
<span class="n">expected</span> <span class="o">=</span> <span class="n">dict2</span>
<span class="k">assert</span> <span class="n">merge_max_mappings</span><span class="p">(</span><span class="n">dict1</span><span class="p">,</span> <span class="n">dict2</span><span class="p">)</span> <span class="o">==</span> <span class="n">expected</span>
<span class="c1"># test empty dict2</span>
<span class="n">dict1</span> <span class="o">=</span> <span class="p">{</span><span class="s2">"a"</span><span class="p">:</span> <span class="mf">10.2</span><span class="p">,</span> <span class="s2">"f"</span><span class="p">:</span> <span class="o">-</span><span class="mf">1.0</span><span class="p">}</span>
<span class="n">dict2</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">expected</span> <span class="o">=</span> <span class="n">dict1</span>
<span class="k">assert</span> <span class="n">merge_max_mappings</span><span class="p">(</span><span class="n">dict1</span><span class="p">,</span> <span class="n">dict2</span><span class="p">)</span> <span class="o">==</span> <span class="n">expected</span>
<span class="c1"># test both empty</span>
<span class="n">dict1</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">dict2</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">expected</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">assert</span> <span class="n">merge_max_mappings</span><span class="p">(</span><span class="n">dict1</span><span class="p">,</span> <span class="n">dict2</span><span class="p">)</span> <span class="o">==</span> <span class="n">expected</span>
</pre></div>
</div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># running the test (seeing no errors means the tests all passed)</span>
<span class="o">>>></span> <span class="n">test_merge_max_mappings</span><span class="p">()</span>
</pre></div>
</div>
<p><strong>Assertions: Solution</strong></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">a_number</span> <span class="o">=</span> <span class="mi">22</span>
<span class="n">a_string</span> <span class="o">=</span> <span class="s2">"abcdef"</span>
</pre></div>
</div>
<p>Assert that <code class="docutils literal notranslate"><span class="pre">a_list</span></code> is <em>not</em> empty:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">assert</span> <span class="n">a_list</span>
<span class="go">---------------------------------------------------------------------------</span>
<span class="go">AssertionError Traceback (most recent call last)</span>
<span class="go"><ipython-input-10-2eba8294859e> in <module></span>
<span class="go">----> 1 assert a_list</span>
<span class="go">AssertionError:</span>
</pre></div>
</div>
<blockquote>
<div>You may have written <code class="docutils literal notranslate"><span class="pre">assert</span> <span class="pre">len(a_list)</span> <span class="pre">></span> <span class="pre">0</span></code> - this is also correct. However, recall that calling <code class="docutils literal notranslate"><span class="pre">bool</span></code> on any sequence (list, tuple, string, etc.) will return <code class="docutils literal notranslate"><span class="pre">False</span></code> if the sequence is empty. This is a reminder that an assertion statement need not include an explicit logical statement, such as an inequality - <code class="docutils literal notranslate"><span class="pre">bool</span></code> will be called on whatever the provided expression is.</div></blockquote>
<p>Assert that the number of vowels in <code class="docutils literal notranslate"><span class="pre">a_string</span></code> is fewer than <code class="docutils literal notranslate"><span class="pre">a_number</span></code>; include an error message that prints the actual number of vowels:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="n">a_string</span><span class="p">)</span> <span class="o"><</span> <span class="n">a_number</span><span class="p">,</span> <span class="n">f</span><span class="s2">"Number of vowels, {count_vowels(a_string)}, exceeds {a_number}"</span>
</pre></div>
</div>
<blockquote>
<div>Note that we make use of an <a class="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Formatting-strings">f-string</a> as a convenient means for writing an informative error message.</div></blockquote>
<p><strong>Testing Your Test via Manual Mutation: Solution</strong></p>
<p>Temporarily change the body of <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> such that the <em>second</em> assertion in <code class="docutils literal notranslate"><span class="pre">test_count_vowels_basic</span></code> raises an error. > Let’s comment out the <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">include_y</span></code> block in our code. This should prevent us from counting y’s, and thus should violate the second assertion in our test.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># Breaking the behavior of `include_y=True`</span>
<span class="k">def</span> <span class="nf">count_vowels</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">include_y</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="bp">False</span><span class="p">)</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span>
<span class="n">vowels</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s2">"aeiouAEIOU"</span><span class="p">)</span>
<span class="c1"># if include_y:</span>
<span class="c1"># vowels.update("yY")</span>
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="mi">1</span> <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">x</span> <span class="k">if</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">vowels</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># the second assertion should raise an error</span>
<span class="o">>>></span> <span class="n">test_count_vowels_basic</span><span class="p">()</span>
<span class="o">---------------------------------------------------------------------------</span>
<span class="ne">AssertionError</span> <span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">)</span>
<span class="o"><</span><span class="n">ipython</span><span class="o">-</span><span class="nb">input</span><span class="o">-</span><span class="mi">5</span><span class="o">-</span><span class="mi">32301</span><span class="n">ff829e9</span><span class="o">></span> <span class="ow">in</span> <span class="o"><</span><span class="n">module</span><span class="o">></span>
<span class="o">----></span> <span class="mi">1</span> <span class="n">test_count_vowels_basic</span><span class="p">()</span>
<span class="o"><</span><span class="n">ipython</span><span class="o">-</span><span class="nb">input</span><span class="o">-</span><span class="mi">4</span><span class="o">-</span><span class="mi">99</span><span class="n">ef0ca3d859</span><span class="o">></span> <span class="ow">in</span> <span class="n">test_count_vowels_basic</span><span class="p">()</span>
<span class="mi">1</span> <span class="k">def</span> <span class="nf">test_count_vowels_basic</span><span class="p">():</span>
<span class="mi">2</span> <span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">"aA bB yY"</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="o">==</span> <span class="mi">2</span>
<span class="o">----></span> <span class="mi">3</span> <span class="k">assert</span> <span class="n">count_vowels</span><span class="p">(</span><span class="s2">"aA bB yY"</span><span class="p">,</span> <span class="n">include_y</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="o">==</span> <span class="mi">4</span>
<span class="ne">AssertionError</span><span class="p">:</span>
</pre></div>
</div>
<blockquote>
<div>See that the error output, which is called a “stack trace”, indicates with an ASCII-arrow that our second assertion is the one that is failing. Thus, we can be confident that that assertion really does help to ensure that we are counting y’s correctly.</div></blockquote>
<p>Restore <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> to its original form and rerun the test to see that <code class="docutils literal notranslate"><span class="pre">count_vowels</span></code> once again passes all of the assertions.</p>
<blockquote>
<div>We simply un-comment the block of code and rerun our test.</div></blockquote>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># Restore the behavior of `include_y=True`</span>
<span class="k">def</span> <span class="nf">count_vowels</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">include_y</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="bp">False</span><span class="p">)</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span>
<span class="n">vowels</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s2">"aeiouAEIOU"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">include_y</span><span class="p">:</span>
<span class="n">vowels</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">"yY"</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="mi">1</span> <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">x</span> <span class="k">if</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">vowels</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># confirming that we restored the proper behavior in `count_vowels`</span>
<span class="o">>>></span> <span class="n">test_count_vowels_basic</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="Pytest.html" class="btn btn-neutral float-right" title="The pytest Framework" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="../module_6.html" class="btn btn-neutral float-left" title="Module 6: Testing Our Code" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2019, Ryan Soklaski
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html>