-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathDIP-unit-testing.html
More file actions
1341 lines (1187 loc) · 82.2 KB
/
DIP-unit-testing.html
File metadata and controls
1341 lines (1187 loc) · 82.2 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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!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 name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unit Testing — Python 210 6.0 documentation</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 src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></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="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.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 210
</a>
<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">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../class_schedule/index.html">Python 210 Class Schedule</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="dev_environment/index.html">Installing Python and core tools</a></li>
<li class="toctree-l1"><a class="reference internal" href="index.html">Py210: Introduction to Python: Topic Notes</a></li>
<li class="toctree-l1"><a class="reference internal" href="../exercises/index.html">Python 210: Exercises</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 210</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>Unit Testing</li>
<li class="wy-breadcrumbs-aside">
<a href="../_sources/modules/DIP-unit-testing.rst.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">
<p>Unit testing - Dive Into Python 3</p>
<p>You are here: <a class="reference external" href="index.html">Home</a> ‣ <a class="reference external" href="table-of-contents.html#unit-testing">Dive Into Python
3</a> ‣</p>
<div class="section" id="unit-testing">
<h1>Unit Testing<a class="headerlink" href="#unit-testing" title="Permalink to this headline">¶</a></h1>
<blockquote>
<div><div class="line-block">
<div class="line">❝ Certitude is not the test of certainty. We have been cocksure of
many things that were not so. ❞</div>
<div class="line">— <a class="reference external" href="http://en.wikiquote.org/wiki/Oliver_Wendell_Holmes,_Jr.">Oliver Wendell Holmes,
Jr.</a></div>
</div>
</div></blockquote>
<div class="section" id="not-diving-in">
<span id="divingin"></span><h2>(Not) Diving In<a class="headerlink" href="#not-diving-in" title="Permalink to this headline">¶</a></h2>
<p>Kids today. So spoiled by these fast computers and fancy “dynamic”
languages. Write first, ship second, debug third (if ever). In my day,
we had discipline. Discipline, I say! We had to write programs by
<em>hand</em>, on <em>paper</em>, and feed them to the computer on <em>punchcards</em>. And
we <em>liked it!</em></p>
<p>In this chapter, you’re going to write and debug a set of utility
functions to convert to and from Roman numerals. You saw the mechanics
of constructing and validating Roman numerals in <a class="reference external" href="regular-expressions.html#romannumerals">“Case study: roman
numerals”</a>. Now step back and
consider what it would take to expand that into a two-way utility.</p>
<p><a class="reference external" href="regular-expressions.html#romannumerals">The rules for Roman
numerals</a> lead to a number of
interesting observations:</p>
<ol class="arabic simple">
<li><p>There is only one correct way to represent a particular number as a
Roman numeral.</p></li>
<li><p>The converse is also true: if a string of characters is a valid Roman
numeral, it represents only one number (that is, it can only be
interpreted one way).</p></li>
<li><p>There is a limited range of numbers that can be expressed as Roman
numerals, specifically <code class="docutils literal notranslate"><span class="pre">1</span></code> through <code class="docutils literal notranslate"><span class="pre">3999</span></code>. The Romans did have
several ways of expressing larger numbers, for instance by having a
bar over a numeral to represent that its normal value should be
multiplied by <code class="docutils literal notranslate"><span class="pre">1000</span></code>. For the purposes of this chapter, let’s
stipulate that Roman numerals go from <code class="docutils literal notranslate"><span class="pre">1</span></code> to <code class="docutils literal notranslate"><span class="pre">3999</span></code>.</p></li>
<li><p>There is no way to represent 0 in Roman numerals.</p></li>
<li><p>There is no way to represent negative numbers in Roman numerals.</p></li>
<li><p>There is no way to represent fractions or non-integer numbers in
Roman numerals.</p></li>
</ol>
<p>Let’s start mapping out what a <code class="docutils literal notranslate"><span class="pre">roman.py</span></code> module should do. It will
have two main functions, <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> and <code class="docutils literal notranslate"><span class="pre">from_roman()</span></code>. The
<code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function should take an integer from <code class="docutils literal notranslate"><span class="pre">1</span></code> to <code class="docutils literal notranslate"><span class="pre">3999</span></code>
and return the Roman numeral representation as a string…</p>
<p>Stop right there. Now let’s do something a little unexpected: write a
test case that checks whether the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function does what you
want it to. You read that right: you’re going to write code that tests
code that you haven’t written yet.</p>
<p>This is called <em>test-driven development</em>, or TDD. The set of two
conversion functions — <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code>, and later <code class="docutils literal notranslate"><span class="pre">from_roman()</span></code> — can
be written and tested as a unit, separate from any larger program that
imports them. Python has a framework for unit testing, the
appropriately-named <code class="docutils literal notranslate"><span class="pre">unittest</span></code> module.</p>
<p>Unit testing is an important part of an overall testing-centric
development strategy. If you write unit tests, it is important to write
them early and to keep them updated as code and requirements change.
Many people advocate writing tests before they write the code they’re
testing, and that’s the style I’m going to demonstrate in this chapter.
But unit tests are beneficial no matter when you write them.</p>
<ul class="simple">
<li><p>Before writing code, writing unit tests forces you to detail your
requirements in a useful fashion.</p></li>
<li><p>While writing code, unit tests keep you from over-coding. When all
the test cases pass, the function is complete.</p></li>
<li><p>When refactoring code, they can help prove that the new version
behaves the same way as the old version.</p></li>
<li><p>When maintaining code, having tests will help you cover your ass when
someone comes screaming that your latest change broke their old code.
(“But <em>sir</em>, all the unit tests passed when I checked it in…”)</p></li>
<li><p>When writing code in a team, having a comprehensive test suite
dramatically decreases the chances that your code will break someone
else’s code, because you can run their unit tests first. (I’ve seen
this sort of thing in code sprints. A team breaks up the assignment,
everybody takes the specs for their task, writes unit tests for it,
then shares their unit tests with the rest of the team. That way,
nobody goes off too far into developing code that doesn’t play well
with others.)</p></li>
</ul>
<p>⁂</p>
</div>
<div class="section" id="a-single-question">
<span id="romantest1"></span><h2>A Single Question<a class="headerlink" href="#a-single-question" title="Permalink to this headline">¶</a></h2>
<p>Every test is an island.</p>
<p>A test case answers a single question about the code it is testing. A
test case should be able to…</p>
<ul class="simple">
<li><p>…run completely by itself, without any human input. Unit testing is
about automation.</p></li>
<li><p>…determine by itself whether the function it is testing has passed
or failed, without a human interpreting the results.</p></li>
<li><p>…run in isolation, separate from any other test cases (even if they
test the same functions). Each test case is an island.</p></li>
</ul>
<p>Given that, let’s build a test case for the first requirement:</p>
<ol class="arabic simple">
<li><p>The <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function should return the Roman numeral
representation for all integers <code class="docutils literal notranslate"><span class="pre">1</span></code> to <code class="docutils literal notranslate"><span class="pre">3999</span></code>.</p></li>
</ol>
<p>It is not immediately obvious how this code does… well, <em>anything</em>. It
defines a class which has no <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> method. The class <em>does</em>
have another method, but it is never called. The entire script has a
<code class="docutils literal notranslate"><span class="pre">__main__</span></code> block, but it doesn’t reference the class or its method.
But it does do something, I promise.</p>
<p>[<cite>download ``romantest1.py`</cite> <examples/romantest1.py>`__]</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>import roman1
import unittest
class KnownValues(unittest.TestCase): ①
known_values = ( (1, 'I'),
(2, 'II'),
(3, 'III'),
(4, 'IV'),
(5, 'V'),
(6, 'VI'),
(7, 'VII'),
(8, 'VIII'),
(9, 'IX'),
(10, 'X'),
(50, 'L'),
(100, 'C'),
(500, 'D'),
(1000, 'M'),
(31, 'XXXI'),
(148, 'CXLVIII'),
(294, 'CCXCIV'),
(312, 'CCCXII'),
(421, 'CDXXI'),
(528, 'DXXVIII'),
(621, 'DCXXI'),
(782, 'DCCLXXXII'),
(870, 'DCCCLXX'),
(941, 'CMXLI'),
(1043, 'MXLIII'),
(1110, 'MCX'),
(1226, 'MCCXXVI'),
(1301, 'MCCCI'),
(1485, 'MCDLXXXV'),
(1509, 'MDIX'),
(1607, 'MDCVII'),
(1754, 'MDCCLIV'),
(1832, 'MDCCCXXXII'),
(1993, 'MCMXCIII'),
(2074, 'MMLXXIV'),
(2152, 'MMCLII'),
(2212, 'MMCCXII'),
(2343, 'MMCCCXLIII'),
(2499, 'MMCDXCIX'),
(2574, 'MMDLXXIV'),
(2646, 'MMDCXLVI'),
(2723, 'MMDCCXXIII'),
(2892, 'MMDCCCXCII'),
(2975, 'MMCMLXXV'),
(3051, 'MMMLI'),
(3185, 'MMMCLXXXV'),
(3250, 'MMMCCL'),
(3313, 'MMMCCCXIII'),
(3408, 'MMMCDVIII'),
(3501, 'MMMDI'),
(3610, 'MMMDCX'),
(3743, 'MMMDCCXLIII'),
(3844, 'MMMDCCCXLIV'),
(3888, 'MMMDCCCLXXXVIII'),
(3940, 'MMMCMXL'),
(3999, 'MMMCMXCIX')) ②
def test_to_roman_known_values(self): ③
'''to_roman should give known result with known input'''
for integer, numeral in self.known_values:
result = roman1.to_roman(integer) ④
self.assertEqual(numeral, result) ⑤
if __name__ == '__main__':
unittest.main()
</pre></div>
</div>
<ol class="arabic simple">
<li><p>To write a test case, first subclass the <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> class of the
<code class="docutils literal notranslate"><span class="pre">unittest</span></code> module. This class provides many useful methods which
you can use in your test case to test specific conditions.</p></li>
<li><p>This is a tuple of integer/numeral pairs that I verified manually. It
includes the lowest ten numbers, the highest number, every number
that translates to a single-character Roman numeral, and a random
sampling of other valid numbers. You don’t need to test every
possible input, but you should try to test all the obvious edge
cases.</p></li>
<li><p>Every individual test is its own method. A test method takes no
parameters, returns no value, and must have a name beginning with the
four letters <code class="docutils literal notranslate"><span class="pre">test</span></code>. If a test method exits normally without
raising an exception, the test is considered passed; if the method
raises an exception, the test is considered failed.</p></li>
<li><p>Here you call the actual <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function. (Well, the function
hasn’t been written yet, but once it is, this is the line that will
call it.) Notice that you have now defined the API for the
<code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function: it must take an integer (the number to
convert) and return a string (the Roman numeral representation). If
the API is different than that, this test is considered failed. Also
notice that you are not trapping any exceptions when you call
<code class="docutils literal notranslate"><span class="pre">to_roman()</span></code>. This is intentional. <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> shouldn’t raise
an exception when you call it with valid input, and these input
values are all valid. If <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> raises an exception, this
test is considered failed.</p></li>
<li><p>Assuming the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function was defined correctly, called
correctly, completed successfully, and returned a value, the last
step is to check whether it returned the <em>right</em> value. This is a
common question, and the <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> class provides a method,
<code class="docutils literal notranslate"><span class="pre">assertEqual</span></code>, to check whether two values are equal. If the result
returned from <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> (<code class="docutils literal notranslate"><span class="pre">result</span></code>) does not match the known
value you were expecting (<code class="docutils literal notranslate"><span class="pre">numeral</span></code>), <code class="docutils literal notranslate"><span class="pre">assertEqual</span></code> will raise an
exception and the test will fail. If the two values are equal,
<code class="docutils literal notranslate"><span class="pre">assertEqual</span></code> will do nothing. If every value returned from
<code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> matches the known value you expect, <code class="docutils literal notranslate"><span class="pre">assertEqual</span></code>
never raises an exception, so <code class="docutils literal notranslate"><span class="pre">test_to_roman_known_values</span></code>
eventually exits normally, which means <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> has passed this
test.</p></li>
</ol>
<p>Write a test that fails, then code until it passes.</p>
<p>Once you have a test case, you can start coding the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code>
function. First, you should stub it out as an empty function and make
sure the tests fail. If the tests succeed before you’ve written any
code, your tests aren’t testing your code at all! Unit testing is a
dance: tests lead, code follows. Write a test that fails, then code
until it passes.</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span># roman1.py
def to_roman(n):
'''convert integer to Roman numeral'''
pass ①
</pre></div>
</div>
<ol class="arabic simple">
<li><p>At this stage, you want to define the API of the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code>
function, but you don’t want to code it yet. (Your test needs to fail
first.) To stub it out, use the Python reserved word <code class="docutils literal notranslate"><span class="pre">pass</span></code>, which
does precisely nothing.</p></li>
</ol>
<p>Execute <code class="docutils literal notranslate"><span class="pre">romantest1.py</span></code> on the command line to run the test. If you
call it with the <code class="docutils literal notranslate"><span class="pre">-v</span></code> command-line option, it will give more verbose
output so you can see exactly what’s going on as each test case runs.
With any luck, your output should look like this:</p>
<div class="highlight-screen notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest1.py -v
test_to_roman_known_values (__main__.KnownValues) ①
to_roman should give known result with known input ... FAIL ②
======================================================================
FAIL: to_roman should give known result with known input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest1.py", line 73, in test_to_roman_known_values
self.assertEqual(numeral, result)
AssertionError: 'I' != None ③
----------------------------------------------------------------------
Ran 1 test in 0.016s ④
FAILED (failures=1) ⑤
</pre></div>
</div>
<ol class="arabic simple">
<li><p>Running the script runs <code class="docutils literal notranslate"><span class="pre">unittest.main()</span></code>, which runs each test
case. Each test case is a method within a class in <code class="docutils literal notranslate"><span class="pre">romantest.py</span></code>.
There is no required organization of these test classes; they can
each contain a single test method, or you can have one class that
contains multiple test methods. The only requirement is that each
test class must inherit from <code class="docutils literal notranslate"><span class="pre">unittest.TestCase</span></code>.</p></li>
<li><p>For each test case, the <code class="docutils literal notranslate"><span class="pre">unittest</span></code> module will print out the
<code class="docutils literal notranslate"><span class="pre">docstring</span></code> of the method and whether that test passed or failed.
As expected, this test case fails.</p></li>
<li><p>For each failed test case, <code class="docutils literal notranslate"><span class="pre">unittest</span></code> displays the trace
information showing exactly what happened. In this case, the call to
<code class="docutils literal notranslate"><span class="pre">assertEqual()</span></code> raised an <code class="docutils literal notranslate"><span class="pre">AssertionError</span></code> because it was
expecting <code class="docutils literal notranslate"><span class="pre">to_roman(1)</span></code> to return <code class="docutils literal notranslate"><span class="pre">'I'</span></code>, but it didn’t. (Since
there was no explicit return statement, the function returned
<code class="docutils literal notranslate"><span class="pre">None</span></code>, the Python null value.)</p></li>
<li><p>After the detail of each test, <code class="docutils literal notranslate"><span class="pre">unittest</span></code> displays a summary of how
many tests were performed and how long it took.</p></li>
<li><p>Overall, the test run failed because at least one test case did not
pass. When a test case doesn’t pass, <code class="docutils literal notranslate"><span class="pre">unittest</span></code> distinguishes
between failures and errors. A failure is a call to an <code class="docutils literal notranslate"><span class="pre">assertXYZ</span></code>
method, like <code class="docutils literal notranslate"><span class="pre">assertEqual</span></code> or <code class="docutils literal notranslate"><span class="pre">assertRaises</span></code>, that fails because
the asserted condition is not true or the expected exception was not
raised. An error is any other sort of exception raised in the code
you’re testing or the unit test case itself.</p></li>
</ol>
<p><em>Now</em>, finally, you can write the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function.</p>
<p>[<cite>download ``roman1.py`</cite> <examples/roman1.py>`__]</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>roman_numeral_map = (('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1)) ①
def to_roman(n):
'''convert integer to Roman numeral'''
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer: ②
result += numeral
n -= integer
return result
</pre></div>
</div>
<ol class="arabic simple">
<li><p><code class="docutils literal notranslate"><span class="pre">roman_numeral_map</span></code> is a tuple of tuples which defines three
things: the character representations of the most basic Roman
numerals; the order of the Roman numerals (in descending value order,
from <code class="docutils literal notranslate"><span class="pre">M</span></code> all the way down to <code class="docutils literal notranslate"><span class="pre">I</span></code>); the value of each Roman
numeral. Each inner tuple is a pair of <code class="docutils literal notranslate"><span class="pre">(numeral,</span> <span class="pre">value)</span></code>. It’s not
just single-character Roman numerals; it also defines two-character
pairs like <code class="docutils literal notranslate"><span class="pre">CM</span></code> (“one hundred less than one thousand”). This makes
the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function code simpler.</p></li>
<li><p>Here’s where the rich data structure of <code class="docutils literal notranslate"><span class="pre">roman_numeral_map</span></code> pays
off, because you don’t need any special logic to handle the
subtraction rule. To convert to Roman numerals, simply iterate
through <code class="docutils literal notranslate"><span class="pre">roman_numeral_map</span></code> looking for the largest integer value
less than or equal to the input. Once found, add the Roman numeral
representation to the end of the output, subtract the corresponding
integer value from the input, lather, rinse, repeat.</p></li>
</ol>
<p>If you’re still not clear how the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function works, add a
<code class="docutils literal notranslate"><span class="pre">print()</span></code> call to the end of the <code class="docutils literal notranslate"><span class="pre">while</span></code> loop:</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>while n >= integer:
result += numeral
n -= integer
print('subtracting {0} from input, adding {1} to output'.format(integer, numeral))
</pre></div>
</div>
<p>With the debug <code class="docutils literal notranslate"><span class="pre">print()</span></code> statements, the output looks like this:</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>>>> import roman1
>>> roman1.to_roman(1424)
subtracting 1000 from input, adding M to output
subtracting 400 from input, adding CD to output
subtracting 10 from input, adding X to output
subtracting 10 from input, adding X to output
subtracting 4 from input, adding IV to output
'MCDXXIV'
</pre></div>
</div>
<p>So the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function appears to work, at least in this manual
spot check. But will it pass the test case you wrote?</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest1.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok ①
----------------------------------------------------------------------
Ran 1 test in 0.016s
OK
</pre></div>
</div>
<ol class="arabic simple">
<li><p>Hooray! The <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function passes the “known values” test
case. It’s not comprehensive, but it does put the function through
its paces with a variety of inputs, including inputs that produce
every single-character Roman numeral, the largest possible input
(<code class="docutils literal notranslate"><span class="pre">3999</span></code>), and the input that produces the longest possible Roman
numeral (<code class="docutils literal notranslate"><span class="pre">3888</span></code>). At this point, you can be reasonably confident
that the function works for any good input value you could throw at
it.</p></li>
</ol>
<p>“Good” input? Hmm. What about bad input?</p>
<p>⁂</p>
</div>
<div class="section" id="halt-and-catch-fire">
<span id="romantest2"></span><h2>“Halt And Catch Fire”<a class="headerlink" href="#halt-and-catch-fire" title="Permalink to this headline">¶</a></h2>
<p>The Pythonic way to halt and catch fire is to raise an exception.</p>
<p>It is not enough to test that functions succeed when given good input;
you must also test that they fail when given bad input. And not just any
sort of failure; they must fail in the way you expect.</p>
<div class="highlight-screen notranslate"><div class="highlight"><pre><span></span>>>> import roman1
>>> roman1.to_roman(4000)
'MMMM'
>>> roman1.to_roman(5000)
'MMMMM'
>>> roman1.to_roman(9000) ①
'MMMMMMMMM'
</pre></div>
</div>
<ol class="arabic simple">
<li><p>That’s definitely not what you wanted — that’s not even a valid Roman
numeral! In fact, each of these numbers is outside the range of
acceptable input, but the function returns a bogus value anyway.
Silently returning bad values is <em>baaaaaaad</em>; if a program is going
to fail, it is far better if it fails quickly and noisily. “Halt and
catch fire,” as the saying goes. The Pythonic way to halt and catch
fire is to raise an exception.</p></li>
</ol>
<p>The question to ask yourself is, “How can I express this as a testable
requirement?” How’s this for starters:</p>
<blockquote>
<div><p>The <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function should raise an <code class="docutils literal notranslate"><span class="pre">OutOfRangeError</span></code> when
given an integer greater than <code class="docutils literal notranslate"><span class="pre">3999</span></code>.</p>
</div></blockquote>
<p>What would that test look like?</p>
<p>[<cite>download ``romantest2.py`</cite> <examples/romantest2.py>`__]</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>import unittest, roman2
class ToRomanBadInput(unittest.TestCase): ①
def test_too_large(self): ②
'''to_roman should fail with large input'''
self.assertRaises(roman2.OutOfRangeError, roman2.to_roman, 4000) ③
</pre></div>
</div>
<ol class="arabic simple">
<li><p>Like the previous test case, you create a class that inherits from
<code class="docutils literal notranslate"><span class="pre">unittest.TestCase</span></code>. You can have more than one test per class (as
you’ll see later in this chapter), but I chose to create a new class
here because this test is something different than the last one.
We’ll keep all the good input tests together in one class, and all
the bad input tests together in another.</p></li>
<li><p>Like the previous test case, the test itself is a method of the
class, with a name starting with <code class="docutils literal notranslate"><span class="pre">test</span></code>.</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">unittest.TestCase</span></code> class provides the <code class="docutils literal notranslate"><span class="pre">assertRaises</span></code> method,
which takes the following arguments: the exception you’re expecting,
the function you’re testing, and the arguments you’re passing to that
function. (If the function you’re testing takes more than one
argument, pass them all to <code class="docutils literal notranslate"><span class="pre">assertRaises</span></code>, in order, and it will
pass them right along to the function you’re testing.)</p></li>
</ol>
<p>Pay close attention to this last line of code. Instead of calling
<code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> directly and manually checking that it raises a
particular exception (by wrapping it in <cite>a ``try…except`</cite>
block <your-first-python-program.html#exceptions>`__), the
<code class="docutils literal notranslate"><span class="pre">assertRaises</span></code> method has encapsulated all of that for us. All you do
is tell it what exception you’re expecting (<code class="docutils literal notranslate"><span class="pre">roman2.OutOfRangeError</span></code>),
the function (<code class="docutils literal notranslate"><span class="pre">to_roman()</span></code>), and the function’s arguments (<code class="docutils literal notranslate"><span class="pre">4000</span></code>).
The <code class="docutils literal notranslate"><span class="pre">assertRaises</span></code> method takes care of calling <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> and
checking that it raises <code class="docutils literal notranslate"><span class="pre">roman2.OutOfRangeError</span></code>.</p>
<p>Also note that you’re passing the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function itself as an
argument; you’re not calling it, and you’re not passing the name of it
as a string. Have I mentioned recently how handy it is that <a class="reference external" href="your-first-python-program.html#everythingisanobject">everything
in Python is an
object</a>?</p>
<p>So what happens when you run the test suite with this new test?</p>
<div class="highlight-screen notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest2.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_too_large (__main__.ToRomanBadInput)
to_roman should fail with large input ... ERROR ①
======================================================================
ERROR: to_roman should fail with large input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest2.py", line 78, in test_too_large
self.assertRaises(roman2.OutOfRangeError, roman2.to_roman, 4000)
AttributeError: 'module' object has no attribute 'OutOfRangeError' ②
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (errors=1)
</pre></div>
</div>
<ol class="arabic simple">
<li><p>You should have expected this to fail (since you haven’t written any
code to pass it yet), but… it didn’t actually “fail,” it had an
“error” instead. This is a subtle but important distinction. A unit
test actually has <em>three</em> return values: pass, fail, and error. Pass,
of course, means that the test passed — the code did what you
expected. “Fail” is what the previous test case did (until you wrote
code to make it pass) — it executed the code but the result was not
what you expected. “Error” means that the code didn’t even execute
properly.</p></li>
<li><p>Why didn’t the code execute properly? The traceback tells all. The
module you’re testing doesn’t have an exception called
<code class="docutils literal notranslate"><span class="pre">OutOfRangeError</span></code>. Remember, you passed this exception to the
<code class="docutils literal notranslate"><span class="pre">assertRaises()</span></code> method, because it’s the exception you want the
function to raise given an out-of-range input. But the exception
doesn’t exist, so the call to the <code class="docutils literal notranslate"><span class="pre">assertRaises()</span></code> method failed.
It never got a chance to test the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function; it didn’t
get that far.</p></li>
</ol>
<p>To solve this problem, you need to define the <code class="docutils literal notranslate"><span class="pre">OutOfRangeError</span></code>
exception in <code class="docutils literal notranslate"><span class="pre">roman2.py</span></code>.</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>class OutOfRangeError(ValueError): ①
pass ②
</pre></div>
</div>
<ol class="arabic simple">
<li><p>Exceptions are classes. An “out of range” error is a kind of value
error — the argument value is out of its acceptable range. So this
exception inherits from the built-in <code class="docutils literal notranslate"><span class="pre">ValueError</span></code> exception. This
is not strictly necessary (it could just inherit from the base
<code class="docutils literal notranslate"><span class="pre">Exception</span></code> class), but it feels right.</p></li>
<li><p>Exceptions don’t actually do anything, but you need at least one line
of code to make a class. Calling <code class="docutils literal notranslate"><span class="pre">pass</span></code> does precisely nothing, but
it’s a line of Python code, so that makes it a class.</p></li>
</ol>
<p>Now run the test suite again.</p>
<div class="highlight-screen notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest2.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_too_large (__main__.ToRomanBadInput)
to_roman should fail with large input ... FAIL ①
======================================================================
FAIL: to_roman should fail with large input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest2.py", line 78, in test_too_large
self.assertRaises(roman2.OutOfRangeError, roman2.to_roman, 4000)
AssertionError: OutOfRangeError not raised by to_roman ②
----------------------------------------------------------------------
Ran 2 tests in 0.016s
FAILED (failures=1)
</pre></div>
</div>
<ol class="arabic simple">
<li><p>The new test is still not passing, but it’s not returning an error
either. Instead, the test is failing. That’s progress! It means the
call to the <code class="docutils literal notranslate"><span class="pre">assertRaises()</span></code> method succeeded this time, and the
unit test framework actually tested the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function.</p></li>
<li><p>Of course, the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function isn’t raising the
<code class="docutils literal notranslate"><span class="pre">OutOfRangeError</span></code> exception you just defined, because you haven’t
told it to do that yet. That’s excellent news! It means this is a
valid test case — it fails before you write the code to make it pass.</p></li>
</ol>
<p>Now you can write the code to make this test pass.</p>
<p>[<cite>download ``roman2.py`</cite> <examples/roman2.py>`__]</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>def to_roman(n):
'''convert integer to Roman numeral'''
if n > 3999:
raise OutOfRangeError('number out of range (must be less than 4000)') ①
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer:
result += numeral
n -= integer
return result
</pre></div>
</div>
<ol class="arabic simple">
<li><p>This is straightforward: if the given input (<code class="docutils literal notranslate"><span class="pre">n</span></code>) is greater than
<code class="docutils literal notranslate"><span class="pre">3999</span></code>, raise an <code class="docutils literal notranslate"><span class="pre">OutOfRangeError</span></code> exception. The unit test does
not check the human-readable string that accompanies the exception,
although you could write another test that did check it (but watch
out for internationalization issues for strings that vary by the
user’s language or environment).</p></li>
</ol>
<p>Does this make the test pass? Let’s find out.</p>
<div class="highlight-screen notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest2.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_too_large (__main__.ToRomanBadInput)
to_roman should fail with large input ... ok ①
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
</pre></div>
</div>
<ol class="arabic simple">
<li><p>Hooray! Both tests pass. Because you worked iteratively, bouncing
back and forth between testing and coding, you can be sure that the
two lines of code you just wrote were the cause of that one test
going from “fail” to “pass.” That kind of confidence doesn’t come
cheap, but it will pay for itself over the lifetime of your code.</p></li>
</ol>
<p>⁂</p>
</div>
<div class="section" id="more-halting-more-fire">
<span id="romantest3"></span><h2>More Halting, More Fire<a class="headerlink" href="#more-halting-more-fire" title="Permalink to this headline">¶</a></h2>
<p>Along with testing numbers that are too large, you need to test numbers
that are too small. As <a class="reference external" href="#divingin">we noted in our functional
requirements</a>, Roman numerals cannot express 0 or negative
numbers.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>>>> import roman2
>>> roman2.to_roman(0)
''
>>> roman2.to_roman(-1)
''
</pre></div>
</div>
<p>Well <em>that’s</em> not good. Let’s add tests for each of these conditions.</p>
<p>[<cite>download ``romantest3.py`</cite> <examples/romantest3.py>`__]</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>class ToRomanBadInput(unittest.TestCase):
def test_too_large(self):
'''to_roman should fail with large input'''
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, 4000) ①
def test_zero(self):
'''to_roman should fail with 0 input'''
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, 0) ②
def test_negative(self):
'''to_roman should fail with negative input'''
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, -1) ③
</pre></div>
</div>
<ol class="arabic simple">
<li><p>The <code class="docutils literal notranslate"><span class="pre">test_too_large()</span></code> method has not changed since the previous
step. I’m including it here to show where the new code fits.</p></li>
<li><p>Here’s a new test: the <code class="docutils literal notranslate"><span class="pre">test_zero()</span></code> method. Like the
<code class="docutils literal notranslate"><span class="pre">test_too_large()</span></code> method, it tells the <code class="docutils literal notranslate"><span class="pre">assertRaises()</span></code> method
defined in <code class="docutils literal notranslate"><span class="pre">unittest.TestCase</span></code> to call our <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function
with a parameter of 0, and check that it raises the appropriate
exception, <code class="docutils literal notranslate"><span class="pre">OutOfRangeError</span></code>.</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">test_negative()</span></code> method is almost identical, except it passes
<code class="docutils literal notranslate"><span class="pre">-1</span></code> to the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function. If either of these new tests
does <em>not</em> raise an <code class="docutils literal notranslate"><span class="pre">OutOfRangeError</span></code> (either because the function
returns an actual value, or because it raises some other exception),
the test is considered failed.</p></li>
</ol>
<p>Now check that the tests fail:</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest3.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_negative (__main__.ToRomanBadInput)
to_roman should fail with negative input ... FAIL
test_too_large (__main__.ToRomanBadInput)
to_roman should fail with large input ... ok
test_zero (__main__.ToRomanBadInput)
to_roman should fail with 0 input ... FAIL
======================================================================
FAIL: to_roman should fail with negative input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest3.py", line 86, in test_negative
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, -1)
AssertionError: OutOfRangeError not raised by to_roman
======================================================================
FAIL: to_roman should fail with 0 input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest3.py", line 82, in test_zero
self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, 0)
AssertionError: OutOfRangeError not raised by to_roman
----------------------------------------------------------------------
Ran 4 tests in 0.000s
FAILED (failures=2)
</pre></div>
</div>
<p>Excellent. Both tests failed, as expected. Now let’s switch over to the
code and see what we can do to make them pass.</p>
<p>[<cite>download ``roman3.py`</cite> <examples/roman3.py>`__]</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>def to_roman(n):
'''convert integer to Roman numeral'''
if not (0 < n < 4000): ①
raise OutOfRangeError('number out of range (must be 1..3999)') ②
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer:
result += numeral
n -= integer
return result
</pre></div>
</div>
<ol class="arabic simple">
<li><p>This is a nice Pythonic shortcut: multiple comparisons at once. This
is equivalent to <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">not</span> <span class="pre">((0</span> <span class="pre"><</span> <span class="pre">n)</span> <span class="pre">and</span> <span class="pre">(n</span> <span class="pre"><</span> <span class="pre">4000))</span></code>, but it’s much
easier to read. This one line of code should catch inputs that are
too large, negative, or zero.</p></li>
<li><p>If you change your conditions, make sure to update your
human-readable error strings to match. The <code class="docutils literal notranslate"><span class="pre">unittest</span></code> framework
won’t care, but it’ll make it difficult to do manual debugging if
your code is throwing incorrectly-described exceptions.</p></li>
</ol>
<p>I could show you a whole series of unrelated examples to show that the
multiple-comparisons-at-once shortcut works, but instead I’ll just run
the unit tests and prove it.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest3.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_negative (__main__.ToRomanBadInput)
to_roman should fail with negative input ... ok
test_too_large (__main__.ToRomanBadInput)
to_roman should fail with large input ... ok
test_zero (__main__.ToRomanBadInput)
to_roman should fail with 0 input ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.016s
OK
</pre></div>
</div>
<p>⁂</p>
</div>
<div class="section" id="and-one-more-thing">
<span id="romantest4"></span><h2>And One More Thing…<a class="headerlink" href="#and-one-more-thing" title="Permalink to this headline">¶</a></h2>
<p>There was one more <a class="reference external" href="#divingin">functional requirement</a> for converting
numbers to Roman numerals: dealing with non-integers.</p>
<div class="highlight-screen notranslate"><div class="highlight"><pre><span></span>>>> import roman3
>>> roman3.to_roman(0.5) ①
''
>>> roman3.to_roman(1.0) ②
'I'
</pre></div>
</div>
<ol class="arabic simple">
<li><p>Oh, that’s bad.</p></li>
<li><p>Oh, that’s even worse. Both of these cases should raise an exception.
Instead, they give bogus results.</p></li>
</ol>
<p>Testing for non-integers is not difficult. First, define a
<code class="docutils literal notranslate"><span class="pre">NotIntegerError</span></code> exception.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span># roman4.py
class OutOfRangeError(ValueError): pass
class NotIntegerError(ValueError): pass
</pre></div>
</div>
<p>Next, write a test case that checks for the <code class="docutils literal notranslate"><span class="pre">NotIntegerError</span></code>
exception.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>class ToRomanBadInput(unittest.TestCase):
.
.
.
def test_non_integer(self):
'''to_roman should fail with non-integer input'''
self.assertRaises(roman4.NotIntegerError, roman4.to_roman, 0.5)
</pre></div>
</div>
<p>Now check that the test fails properly.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest4.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_negative (__main__.ToRomanBadInput)
to_roman should fail with negative input ... ok
test_non_integer (__main__.ToRomanBadInput)
to_roman should fail with non-integer input ... FAIL
test_too_large (__main__.ToRomanBadInput)
to_roman should fail with large input ... ok
test_zero (__main__.ToRomanBadInput)
to_roman should fail with 0 input ... ok
======================================================================
FAIL: to_roman should fail with non-integer input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest4.py", line 90, in test_non_integer
self.assertRaises(roman4.NotIntegerError, roman4.to_roman, 0.5)
AssertionError: NotIntegerError not raised by to_roman
----------------------------------------------------------------------
Ran 5 tests in 0.000s
FAILED (failures=1)
</pre></div>
</div>
<p>Write the code that makes the test pass.</p>
<div class="highlight-pp notranslate"><div class="highlight"><pre><span></span>def to_roman(n):
'''convert integer to Roman numeral'''
if not (0 < n < 4000):
raise OutOfRangeError('number out of range (must be 1..3999)')
if not isinstance(n, int): ①
raise NotIntegerError('non-integers can not be converted') ②
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer:
result += numeral
n -= integer
return result
</pre></div>
</div>
<ol class="arabic simple">
<li><p>The built-in <code class="docutils literal notranslate"><span class="pre">isinstance()</span></code> function tests whether a variable is a
particular type (or, technically, any descendant type).</p></li>
<li><p>If the argument <code class="docutils literal notranslate"><span class="pre">n</span></code> is not an <code class="docutils literal notranslate"><span class="pre">int</span></code>, raise our newly minted
<code class="docutils literal notranslate"><span class="pre">NotIntegerError</span></code> exception.</p></li>
</ol>
<p>Finally, check that the code does indeed make the test pass.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>you@localhost:~/diveintopython3/examples$ python3 romantest4.py -v
test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_negative (__main__.ToRomanBadInput)
to_roman should fail with negative input ... ok
test_non_integer (__main__.ToRomanBadInput)
to_roman should fail with non-integer input ... ok
test_too_large (__main__.ToRomanBadInput)
to_roman should fail with large input ... ok
test_zero (__main__.ToRomanBadInput)
to_roman should fail with 0 input ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.000s
OK
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function passes all of its tests, and I can’t think
of any more tests, so it’s time to move on to <code class="docutils literal notranslate"><span class="pre">from_roman()</span></code>.</p>
<p>⁂</p>
</div>
<div class="section" id="a-pleasing-symmetry">
<span id="romantest5"></span><h2>A Pleasing Symmetry<a class="headerlink" href="#a-pleasing-symmetry" title="Permalink to this headline">¶</a></h2>
<p>Converting a string from a Roman numeral to an integer sounds more
difficult than converting an integer to a Roman numeral. Certainly there
is the issue of validation. It’s easy to check if an integer is greater
than 0, but a bit harder to check whether a string is a valid Roman
numeral. But we already constructed <a class="reference external" href="regular-expressions.html#romannumerals">a regular expression to check for
Roman numerals</a>, so that part
is done.</p>
<p>That leaves the problem of converting the string itself. As we’ll see in
a minute, thanks to the rich data structure we defined to map individual
Roman numerals to integer values, the nitty-gritty of the
<code class="docutils literal notranslate"><span class="pre">from_roman()</span></code> function is as straightforward as the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code>
function.</p>
<p>But first, the tests. We’ll need a “known values” test to spot-check for
accuracy. Our test suite already contains <a class="reference external" href="#romantest1">a mapping of known
values</a>; let’s reuse that.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>def test_from_roman_known_values(self):
'''from_roman should give known result with known input'''
for integer, numeral in self.known_values:
result = roman5.from_roman(numeral)
self.assertEqual(integer, result)
</pre></div>
</div>
<p>There’s a pleasing symmetry here. The <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> and
<code class="docutils literal notranslate"><span class="pre">from_roman()</span></code> functions are inverses of each other. The first
converts integers to specially-formatted strings, the second converts
specially-formated strings to integers. In theory, we should be able to
“round-trip” a number by passing to the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function to get a
string, then passing that string to the <code class="docutils literal notranslate"><span class="pre">from_roman()</span></code> function to get
an integer, and end up with the same number.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>n = from_roman(to_roman(n)) for all values of n
</pre></div>
</div>
<p>In this case, “all values” means any number between <code class="docutils literal notranslate"><span class="pre">1..3999</span></code>, since
that is the valid range of inputs to the <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code> function. We can
express this symmetry in a test case that runs through all the values
<code class="docutils literal notranslate"><span class="pre">1..3999</span></code>, calls <code class="docutils literal notranslate"><span class="pre">to_roman()</span></code>, calls <code class="docutils literal notranslate"><span class="pre">from_roman()</span></code>, and checks
that the output is the same as the original input.</p>
<div class="highlight-nd notranslate"><div class="highlight"><pre><span></span>class RoundtripCheck(unittest.TestCase):
def test_roundtrip(self):
'''from_roman(to_roman(n))==n for all n'''
for integer in range(1, 4000):