This repository has been archived by the owner on Dec 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathunit-testing.html
683 lines (595 loc) · 56 KB
/
unit-testing.html
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
<!DOCTYPE html>
<meta charset=utf-8>
<title>单元测试 —— 深入 Python 3</title><!--[if IE]><script src=j/html5.js></script><![endif]-->
<link rel=stylesheet href="dip3.css">
<style>
body{counter-reset:h1 9}
</style>
<link rel=stylesheet media='only screen and (max-device-width: 480px)' href="http://woodpecker.org.cn/diveintopython3/mobile.css">
<link rel=stylesheet media=print href="http://woodpecker.org.cn/diveintopython3/print.css">
<meta name=viewport content='initial-scale=1.0'>
<form action=http://www.google.com/cse><div><input type=hidden name=cx value=014021643941856155761:l5eihuescdw><input type=hidden name=ie value=UTF-8> <input type=search name=q size=25 placeholder="powered by Google™"> <input type=submit name=root value=搜索></div></form>
<p>当前位置: <a href="index.html">首页</a> <span class=u>‣</span> <a href="table-of-contents.html#unit-testing">深入 Python 3</a> <span class=u>‣</span>
<p id=level>难度级别: <span class=u title=初学者>♦♦♢♢♢</span>
<h1>单元测试</h1>
<blockquote class=q>
<p><span class=u>❝</span> Certitude is not the test of certainty. We have been cocksure of many things that were not so. <span class=u>❞</span><br>— <a href=http://en.wikiquote.org/wiki/Oliver_Wendell_Holmes,_Jr.>Oliver Wendell Holmes, Jr.</a>
</blockquote>
<p id=toc>
<h2 id=divingin>(不要)深入</h2>
<p class=f>在此章节中,你将要编写及调试一系列用于阿拉伯数字与罗马数字相互转换的方法。你阅读了在<a href="regular-expressions.html#romannumerals">“案例学习:罗马数字”</a>中关于构建及校验罗马数字的机制。那么,现在考虑扩展该机制为一个双向的方法。<p><a href="regular-expressions.html#romannumerals">罗马数字的规则</a>引出很多有意思的结果:<ol>
<li>只有一种正确的途径用阿拉伯数字表示罗马数字。</li><li>反过来一样,一个字符串类型的有效的罗马数字也仅可以表示一个阿拉伯数字(即,这种转换方式也是只有一种)。</li><li>只有有限范围的阿拉伯数字可以以罗马数字表示,那就是1-3999。而罗马数字表示大数字却有几种方式。例如,为了表示一个数字连续出现时正确的值则需要乘以<code>1000</code>。为了达到本节的目的,限定罗马数字在 1 到 3999 之间。</li><li>无法用罗马数字来表示 0 。</li><li>无法用罗马数字来表示负数 。</li><li>无法用罗马数字来表示分数或非整数 。</li></ol>
<p>现在,开始设计 <code>roman.py</code> 模块。它有两个主要的方法:<code>to_roman()</code> 及 <code>from_roman()</code>。<code>to_roman()</code> 方法接收一个从 <code>1</code> 到 <code>3999</code> 之间的整型数字,然后返回一个字符串类型的罗马数字。<p>在这里停下来。现在让我们进行一些意想不到的操作:编写一个测试用例来检测 <code>to_roman</code> 函数是否实现了你想要的功能。你想得没错:你正在编写测试尚未编写代码的代码。<p>这就是所谓的<i>测试驱动开发</i> 或 <abbr>TDD</abbr>。那两个转换方法( <code>to_roman()</code> 及之后的 <code>from_roman()</code>)可以独立于任何使用它们的大程序而作为一个单元来被编写及测试。Python 自带一个单元测试框架,被恰当地命名为 <code>unittest</code> 模块。<p>单元测试是整个以测试为中心的开发策略中的一个重要部分。编写单元测试应该安排在项目的早期,同时要让它随同代码及需求变更一起更新。很多人都坚持测试代码应该先于被测试代码的,而这种风格也是我在本节中所主张的。但是,不管你何时编写,单元测试都是有好处的。<ul>
<li>在编写代码之前,通过编写单元测试来强迫你使用有用的方式细化你的需求。</li><li>在编写代码时,单元测试可以使你避免过度编码。当所有测试用例通过时,实现的方法就完成了。</li><li>重构代码时,单元测试用例有助于证明新版本的代码跟老版本功能是一致的。</li><li>在维护代码期间,如果有人对你大喊:你最新的代码修改破坏了原有代码的状态,那么此时单元测试可以帮助你反驳(“<em>先生</em>,所有单元测试用例通过了我才提交代码的...”)。</li><li>在团队编码中,缜密的测试套件可以降低你的代码影响别人代码的机会,这是因为你需要优先执行别人的单元测试用例。(我曾经在代码冲刺见过这种实践。一个团队把任务分解,每个人领取其中一小部分任务,同时为其编写单元测试;然后,团队相互分享他们的单元测试用例。这样,所有人都可以在编码过程中提前发现谁的代码与其他人的不可以良好工作。)</li></ul>
<p class=a>⁂
<h2 id=romantest1>一个简单的问题</h2>
<aside>每个测试都是一个孤岛。</aside>
<p>一个测试用例仅回答一个关于它正在测试的代码问题。一个测试用例应该可以:<ul>
<li>……完全自动运行,而不需要人工干预。单元测试几乎是全自动的。</li><li>……自主判断被测试的方法是通过还是失败,而不需要人工解释结果。</li><li>……独立运行,而不依赖其它测试用例(即使测试的是同样的方法)。即,每一个测试用例都是一个孤岛。</li></ul>
<p>让我们据此为第一个需求建立一个测试用例:<ol>
<li><code>to_roman()</code> 方法应该返回代表<code>1</code>-<code>3999</code>的罗马数字。</li></ol>
<p>这些代码功效如何并不那么显而易见。它定义了一个没有<code>__init__</code> 方法的类。而该类<em>当然</em>有其它方法,但是这些方法都不会被调用。在整个脚本中,有一个__main__ 块,但它并不引用该类及它的方法。但我承诺,它做别的事情了。<p class=d>[<a href="examples/romantest1.py">download <code>romantest1.py</code></a>]
<pre class=pp><code>import roman1
import unittest
<a>class KnownValues(unittest.TestCase): <span class=u>①</span></a>
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'),
<a> (3999, 'MMMCMXCIX')) <span class=u>②</span></a>
<a> def test_to_roman_known_values(self): <span class=u>③</span></a>
'''to_roman should give known result with known input'''
for integer, numeral in self.known_values:
<a> result = roman1.to_roman(integer) <span class=u>④</span></a>
<a> self.assertEqual(numeral, result) <span class=u>⑤</span></a>
if __name__ == '__main__':
unittest.main()</code></pre>
<ol>
<li>为了编写测试用例,首先使该测试用例类成为<code>unittest</code> 模块的<code>TestCase</code> 类的子类。TestCase 提供了很多你可以用于测试特定条件的测试用例的有用的方法。</li><li>这是一张我手工核实过的整型数字-罗马数字对的列表。它包括最小的十个数字、最大数字、每一个有唯一一个字符串格式的罗马数字的数字以及一个有其它有效数字产生的随机数。你没有必要测试每一个可能的输入,而需要测试所有明显的边界用例。</li><li>每一个独立的测试都有它自己的不含参数及没有返回值的方法。如果方法不抛出异常而正常退出则认为测试通过;否则,测试失败。</li><li>这里调用了真实的 <code>to_roman()</code> 方法. (当然,该方法还没编写;但一旦该方法被实现,这就是调用它的行号)。注意,现在你已经为 <code>to_roman()</code> 方法定义了 <abbr>接口</abbr>:它必须包含一个整型(被转换的数字)及返回一个字符串(罗马数字的表示形式)。如果 <abbr>接口</abbr> 实现与这些定义不一致,那么测试就会被视为失败。同样,当你调用 <code>to_roman()</code> 时,不要捕获任何异常。这些都是unittest 故意设计的。当你以有效的输入调用 <code>to_roman()</code> 时它不会抛出异常。如果 <code>to_roman()</code> 抛出了异常,则测试被视为失败。</li><li>假设 <code>to_roman()</code> 方法已经被正确定义,正确调用,成功实现以及返回了一个值,那么最后一步就是去检查它的返回值是否 <em>right</em> 。这是测试中一个普遍的问题。<code>TestCase</code> 类提供了一个方法 <code>assertEqual</code> 来检查两个值是否相等。如果 <code>to_roman()</code> (<var>result</var>) 的返回值跟已知的期望值g (<var>numeral</var>)不一致,则抛出异常,并且测试失败。如果两值相等, <code>assertEqual</code> 不会做任何事情。如果 <code>to_roman()</code> 的所有返回值均与已知的期望值一致,则 <code>assertEqual</code> 不会抛出任何异常,于是,<code>test_to_roman_known_values</code> 最终会会正常退出,这就意味着 <code>to_roman()</code> 通过此次测试。</li></ol>
<aside>编写一个失败的测试,然后进行编码直到该测试通过。</aside>
<p>一旦你有了测试用例,你就可以开始编写 <code>to_roman()</code> 方法。首先,你应该用一个空方法作为存根,同时确认该测试失败。因为如果在编写任何代码之前测试已经通过,那么你的测试对你的代码是完全不会有效果的!单元测试就像跳舞:测试先行,编码跟随。编写一个失败的测试,然后进行编码直到该测试通过。<pre class=pp><code># roman1.py
def to_roman(n):
'''convert integer to Roman numeral'''
<a> pass <span class=u>①</span></a></code></pre>
<ol>
<li>在此阶段,你想定义to_roman()方法的 <abbr>API</abbr> ,但是你还不想编写(首先,你的测试需要失败)。为了存根,需要使用Python 保留关键字<code>pass</code>,它恰恰什么都没做。</li></ol>
<p>在命令行上运行 <code>romantest1.py</code> 来执行该测试。如果使用-v命令行参数的话,会有更详细的输出来帮助你精确地查看每一条用例的执行过程。幸运的话,你的输出应该如下:<pre class=screen>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest1.py -v</kbd>
<a><samp>test_to_roman_known_values (__main__.KnownValues)</samp> <span class=u>①</span></a>
<a><samp>to_roman should give known result with known input ... FAIL</samp> <span class=u>②</span></a>
<samp>
======================================================================
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)
<a>AssertionError: 'I' != None <span class=u>③</span></a>
----------------------------------------------------------------------
<a>Ran 1 test in 0.016s <span class=u>④</span></a>
<a>FAILED (failures=1) <span class=u>⑤</span></a></samp></pre>
<ol>
<li>运行脚本就会执行 <code>unittest.main()</code> , 该方法执行了每一条测试用例。而每一条测试用例都是 <code>romantest.py</code> 中的类方法。这些测试类没有必要的组织要求;它们每一个都包括一个独立的测试方法,或者你也可以编写一个含有多个测试方法的类。唯一的要求就是每一个测试类都必须继承 <code>unittest.TestCase</code>。</li><li>对于每一个测试用例, <code>unittest</code> 模块会打印出测试方法的 <code>docstring</code> ,并且说明该测试失败还是成功。正如预期那样,该测试用例失败了。</li><li>对于每一个失败的测试用例, <code>unittest</code> 模块会打印出详细的跟踪信息。在该用例中, <code>assertEqual()</code> 的调用抛出了一个 <code>AssertionError</code> 的异常,这是因为 <code>to_roman(1)</code> 本应该返回 <code>'I'</code> 的,但是它没有。(因为没有显示的返回值,故方法返回了 Python 的空值 <code>None</code>)</li><li>在说明每个用例的详细执行结果之后, <code>unittest</code> 打印出一个简述来说明“多少用例被执行了”和“测试执行了多长时间”。</li><li>从整体上说,该测试执行失败,因为至少有一条用例没有成功。如果测试用例没有通过的话, <code>unittest</code> 可以区别用例执行失败跟程序错误的。像 <code>assertXYZ</code> 、<code>assertRaises</code> 这样的 <code>assertEqual</code> 方法的失败是因为被声明的条件不是为真,或者预期的异常没有抛出。错误,则是另一种异常,它是因为被测试的代码或者单元测试用例本身的代码问题而引起的。</li></ol>
<p><em>至此</em>,你可以实现 <code>to_roman()</code> 方法了。<p class=d>[<a href="examples/roman1.py">download <code>roman1.py</code></a>]
<pre class=pp><code>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),
<a> ('I', 1)) <span class=u>①</span></a>
def to_roman(n):
'''convert integer to Roman numeral'''
result = ''
for numeral, integer in roman_numeral_map:
<a> while n >= integer: <span class=u>②</span></a>
result += numeral
n -= integer
return result</code></pre>
<ol>
<li><var>roman_numeral_map</var> 是一个由元组组成的元组,它定义了三样东西:代表最基本的罗马数字的字符、罗马数字的顺序(逆序,从 <code>M</code> 到 <code>I</code>)、每一个罗马数字的阿拉伯数值。每一个内部的元组都是一个<code>(<var>数</var>,<var>值</var>)</code>对。它不但定义了单字符罗马数字,也定义了双字符罗马数字,如<code>CM</code>(“比一千小一百”)。该元组使得 <code>to_roman()</code> 方法实现起来更简单。</li><li>这里得益于 <var>roman_numeral_map</var> 的数据结构,因为你不需要任何特别得逻辑去处理减法。为了转化成罗马数字,通过查找等于或者小于输入值的最大值来简化对 <var>roman_numeral_map</var> 的迭代。一旦找到,就把罗马数字的字符串追加至输出值(result)末段,同时输入值要减去相应的数值,如此重复。</li></ol>
<p>如果你仍然不清楚 <code>to_roman()</code> 如何工作,可以在 <code>while</code> 循环末段添加 <code>print()</code> 调用:
<pre class='nd pp'><code>
while n >= integer:
result += numeral
n -= integer
print('subtracting {0} from input, adding {1} to output'.format(integer, numeral))</code></pre>
<p>因为用于调试的 <code>print()</code> 声明,输出会如下:<pre class='nd screen'>
<samp class=p>>>> </samp><kbd class=pp>import roman1</kbd>
<samp class=p>>>> </samp><kbd class=pp>roman1.to_roman(1424)</kbd>
<samp>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'</samp></pre>
<p>这样, <code>to_roman()</code> 至少在手工检查下是工作正常的。但它会通过你编写的测试用例么?<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest1.py -v</kbd>
<samp>test_to_roman_known_values (__main__.KnownValues)
<a>to_roman should give known result with known input ... ok <span class=u>①</span></a>
----------------------------------------------------------------------
Ran 1 test in 0.016s
OK</samp></pre>
<ol>
<li>万岁!<code>to_roman()</code> 函数通过了“known values” 测试用例。该测试用例并不复杂,但是它的确使该方法按着输入值的变化而执行,其中的输入值包括:每一个单字符罗马数字、最大值数字(<code>3999</code>)、最长字符串数字(<code>3888</code>)。通过这些,你就可以有理由对“该方法接收任何正常的输入值都工作正常”充满信心了。</li></ol>
<p>“正常”输入?”嗯。那“非法”输入呢?<p class=a>⁂
<h2 id=romantest2>“停止然后着火”</h2>
<aside>Python 方式的停止并点火实际是引发一个例外。</aside>
<p>仅仅在“正常”值时证明方法通过的测试是不够的;你同样需要测试当输入“非法”值时方法失败。但并不是说要枚举所有的失败类型,而是说必要在你预期的范围内失败。<pre class=screen>
<samp class=p>>>> </samp><kbd class=pp>import roman1</kbd>
<samp class=p>>>> </samp><kbd class=pp>roman1.to_roman(4000)</kbd>
<samp class=pp>'MMMM'</samp>
<samp class=p>>>> </samp><kbd class=pp>roman1.to_roman(5000)</kbd>
<samp class=pp>'MMMMM'</samp>
<a><samp class=p>>>> </samp><kbd class=pp>roman1.to_roman(9000)</kbd> <span class=u>①</span></a>
<samp class=pp>'MMMMMMMMM'</samp></pre>
<ol>
<li>这明显不是你所期望的──那也不是一个合法的罗马数字!事实上,这些输入值都超过了允许的范围,但该函数却返回了假值。悄悄返回的错误值是 <em>很糟糕</em> 的,因为如果一个程序要挂掉的话,迅速且引人注目地挂掉会好很多。正如谚语“停止然后着火”。Python 方式的停止并点火实际是引发一个例外。</li></ol>
<p>那问题是:我该如何表达这些内容为可测试需求呢?下面就是一个开始:<blockquote>
<p>当输入值大于 <code>3999</code> 时, <code>to_roman()</code> 函数应该抛出一个 <code>OutOfRangeError</code> 异常。</blockquote>
<p>具体测试代码如下:<p class=d>[<a href="examples/romantest2.py">download <code>romantest2.py</code></a>]
<pre class=pp><code><a>class ToRomanBadInput(unittest.TestCase): <span class=u>①</span></a>
<a> def test_too_large(self): <span class=u>②</span></a>
'''to_roman should fail with large input'''
<a> self.assertRaises(roman2.OutOfRangeError, roman2.to_roman, 4000) <span class=u>③</span></a></code></pre>
<ol>
<li>如前一个测试用例,创建一个继承于 <code>unittest.TestCase</code> 的类。你可以在每个类中实现多个测试(正如你在本节中将会看到的一样),但是我却选择了创建一个新类,因为该测试与上一个有点不同。这样,我们可以把正常输入的测试跟非法输入的测试分别放入不同的两个类中。</li><li>如前一个测试用例,测试本身是类一个方法,并且该方法以 <code>test</code> 开头命名。</li><li> <code>unittest.TestCase</code> 类提供e <code>assertRaises</code> 方法,该方法需要以下参数:你期望的异常、你要测试的方法及传入给方法的参数。(如果被测试的方法需要多个参数的话,则把所有参数依次传入 <code>assertRaises</code>, assertRaises 会正确地把参数传递给被测方法的。)</li></ol>
<p>请关注代码的最后一行。这里并不需要直接调用 <code>to_roman()</code> ,同时也不需要手动检查它抛出的异常类型(通过 <a href="your-first-python-program.html#exceptions">一个 <code>try...except</code> 块</a>来包装),而这些 <code>assertRaises</code> 方法都给我们完成了。你要做的所有事情就是告诉assertRaises你期望的异常类型( <code>roman2.OutOfRangeError</code>)、被测方法(<code>to_roman()</code>)以及方法的参数(<code>4000</code>)。<code>assertRaises</code> 方法负责调用 <code>to_roman()</code> 和检查方法抛出 <code>roman2.OutOfRangeError</code> 的异常。<p>另外,注意你是把 <code>to_roman()</code> 方法作为参数传递;你没有调用被测方法,也不是把被测方法作为一个字符串名字传递进去。我是否在之前提到过 <a href="your-first-python-program.html#everythingisanobject">Python 中万物皆对象</a>有多么轻便?<p>那么,当你执行该含有新测试的测试套件时,结果如下:<pre class=screen>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest2.py -v</kbd>
<samp>test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_too_large (__main__.ToRomanBadInput)
<a>to_roman should fail with large input ... ERROR <span class=u>①</span></a>
======================================================================
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)
<a>AttributeError: 'module' object has no attribute 'OutOfRangeError' <span class=u>②</span></a>
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (errors=1)</samp></pre>
<ol>
<li>测试本应该是失败的(因为并没有任何代码使它通过),但是它没有真正的“失败”,而是出现了“错误”。这里有些微妙但是重要的区别。单元测试事实上有 <em>三种</em> 返回值:通过、失败以及错误。“通过”,但当然就是说测试成功了──被测代码符合你的预期。“失败”就是就如之前的测试用例一样(直到你编写代码令它通过)──执行了被测试的代码但返回值并不是所期望的。“错误”就是被测试的代码甚至没有正确执行。</li><li>为什么代码没有正确执行呢?回溯说明了一切。你正在测试的模块没有叫 <code>OutOfRangeError</code> 的异常。回忆一下,该异常是你传递给 <code>assertRaises()</code> 方法的,因为你期望当传递给被测试方法一个超大值时可以抛出该异常。但是,该异常并不存在,因此 <code>assertRaises()</code> 的调用会失败。事实上测试代码并没有机会测试 <code>to_roman()</code> 方法,因为它还没有到达那一步。</li></ol>
<p>为了解决该问题,你需要在 <code>roman2.py</code> 中定义 <code>OutOfRangeError</code> 。<pre class=pp><code><a>class OutOfRangeError(ValueError): <span class=u>①</span></a>
<a> pass <span class=u>②</span></a></code></pre>
<ol>
<li>异常也是类。“越界”错误是值错误的一类──参数值超出了可接受的范围。所以,该异常继承了内建的 <code>ValueError</code> 异常类。这并不是严格的要求(它同样也可以继承于基类 <code>Exception</code>),只要它正确就行了。</li><li>事实上,异常类可以不做任何事情,但是至少添加一行代码使其成为一个类。 <code>pass</code> 的真正意思是什么都不做,但是它是一行Python代码,所以可以使其成为类。</li></ol>
<p>再次执行该测试套件。<pre class=screen>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest2.py -v</kbd>
<samp>test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_too_large (__main__.ToRomanBadInput)
<a>to_roman should fail with large input ... FAIL <span class=u>①</span></a>
======================================================================
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)
<a>AssertionError: OutOfRangeError not raised by to_roman <span class=u>②</span></a>
----------------------------------------------------------------------
Ran 2 tests in 0.016s
FAILED (failures=1)</samp></pre>
<ol>
<li>新的测试仍然没有通过,但是它并没有返回错误而是失败。相反,测试失败了。这就是进步!它意味着这回 <code>assertRaises()</code> 方法的调用是成功的,同时,单元测试框架事实上也测试了 <code>to_roman()</code> 函数。</li><li>当然 <code>to_roman()</code> 方法没有引发你所定义的 <code>OutOfRangeError</code> 异常,因为你并没有让它这么做。这真是个好消息!因为它意味着这是个合格的测试案例——在编写代码使之通过之前它将会以失败为结果。</li></ol>
<p>现在可以编写代码使其通过了。<p class=d>[<a href="examples/roman2.py">download <code>roman2.py</code></a>]
<pre class=pp><code>def to_roman(n):
'''convert integer to Roman numeral'''
if n > 3999:
<a> raise OutOfRangeError('number out of range (must be less than 4000)') <span class=u>①</span></a>
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer:
result += numeral
n -= integer
return result</code></pre>
<ol>
<li>非常直观:如果给定的输入 (<var>n</var>) 大于<code>3999</code>,引发一个 <code>OutOfRangeError</code> 例外。本单元测试并不检测那些与例外相伴的人类可读的字符串,但你可以编写另一个测试来检查它(但请注意用户的语言或环境导致的不同国际化问题)。</li></ol>
<p>这样能让测试通过吗?让我们来寻找答案。<pre class=screen>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest2.py -v</kbd>
<samp>test_to_roman_known_values (__main__.KnownValues)
to_roman should give known result with known input ... ok
test_too_large (__main__.ToRomanBadInput)
<a>to_roman should fail with large input ... ok <span class=u>①</span></a>
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK</samp></pre>
<ol>
<li>万岁!两个测试都通过了。因为你是在测试与编码之间来回反复开发的,所以你可以肯定使得其中一个测试从“失败”转变为“通过”的原因就是你刚才新添的两行代码。虽然这种信心来得并不简单,但是这种代价会在你代码的生命周期中得到回报。</li></ol>
<p class=a>⁂
<h2 id=romantest3>More Halting, More Fire</h2>
<p>与测试超大值一样,也必须测试超小值。<a href="unit-testing.html#divingin">正如我们在功能需求中提到的那样</a>,罗马数字无法表达 0 或负数。<pre class='nd screen'>
<samp class=p>>>> </samp><kbd class=pp>import roman2</kbd>
<samp class=p>>>> </samp><kbd class=pp>roman2.to_roman(0)</kbd>
<samp class=pp>''</samp>
<samp class=p>>>> </samp><kbd class=pp>roman2.to_roman(-1)</kbd>
<samp class=pp>''</samp></pre>
<p>显然,<em>这不是</em>好的结果。让我们为这些条件逐条添加测试。<p class=d>[<a href="examples/romantest3.py">download <code>romantest3.py</code></a>]
<pre class=pp><code>class ToRomanBadInput(unittest.TestCase):
def test_too_large(self):
'''to_roman should fail with large input'''
<a> self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, 4000) <span class=u>①</span></a>
def test_zero(self):
'''to_roman should fail with 0 input'''
<a> self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, 0) <span class=u>②</span></a>
def test_negative(self):
'''to_roman should fail with negative input'''
<a> self.assertRaises(roman3.OutOfRangeError, roman3.to_roman, -1) <span class=u>③</span></a></code></pre>
<ol>
<li> <code>test_too_large()</code> 方法跟之前的步骤一样。我把它包含进来是为了说明新代码的位置。</li><li>这里是新的测试方法: <code>test_zero()</code> 。如 <code>test_too_large()</code> 一样,它调用了在n <code>unittest.TestCase</code> 中定义的 <code>assertRaises()</code> 方法,并且以参数值 0 传入给 <code>to_roman()</code>,最后检查它抛出相应的异常:<code>OutOfRangeError</code>。</li><li> <code>test_negative()</code> 也几乎类似,除了它给 <code>to_roman()</code> 函数传入 <code>-1</code> 。如果新的测试中 <em>没有</em> 任何一个抛出了异常 <code>OutOfRangeError</code> (或者由于该函数返回了实际的值,或者由于它抛出了其他类型的异常),那么测试就被视为失败。</li></ol>
<p>检查测试是否失败:<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest3.py -v</kbd>
<samp>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)</samp></pre>
<p>太棒了!两个测试都如期地失败了。接着转入被测试的代码并且思考如何才能使得测试通过。<p class=d>[<a href="examples/roman3.py">download <code>roman3.py</code></a>]
<pre class=pp><code>def to_roman(n):
'''convert integer to Roman numeral'''
<a> if not (0 < n < 4000): <span class=u>①</span></a>
<a> raise OutOfRangeError('number out of range (must be 1..3999)') <span class=u>②</span></a>
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer:
result += numeral
n -= integer
return result</code></pre>
<ol>
<li>这是Python优雅的快捷方法:一次性的多比较。它等价于 <code>if not ((0 < n) and (n < 4000))</code>,但前者更适合阅读。这一行代码应该捕获那些超大的、负值的或者为 0 的输入。</li><li>当你改变条件的时候,要确保同步更新那些提示错误信息的可读字符串。<code>unittest</code> 框架并不关心这些,但是如果你的代码抛出描述不正确的异常信息的话会使得手工调试代码变得困难。</li></ol>
<p>我本应该给你展示完整的一系列与本章节不相关的例子来说明一次性多比较的快捷方式是有效的,但是我将仅仅运行本测试用例来证明它的有效性。<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest3.py -v</kbd>
<samp>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</samp></pre>
<p class=a>⁂
<h2 id=romantest4>还有一件事情……</h2>
<p>还有一个把阿拉伯数字转换成罗马数字的 <a href="unit-testing.html#divingin">功能性需求</a> :处理非整型数字。
<pre class=screen>
<samp class=p>>>> </samp><kbd class=pp>import roman3</kbd>
<a><samp class=p>>>> </samp><kbd class=pp>roman3.to_roman(0.5)</kbd> <span class=u>①</span></a>
<samp class=pp>''</samp>
<a><samp class=p>>>> </samp><kbd class=pp>roman3.to_roman(1.0)</kbd> <span class=u>②</span></a>
<samp class=pp>'I'</samp></pre>
<ol>
<li>喔,糟糕了。</li><li>喔,更糟糕了。两个用例都本该抛出异常的。但却返回了假的结果。</li></ol>
<p>测试非整数并不困难。首先,定义一个 <code>NotIntegerError</code> 例外。<pre class='nd pp'><code># roman4.py
class OutOfRangeError(ValueError): pass
<mark>class NotIntegerError(ValueError): pass</mark></code></pre>
<p>然后,编写一个检查 <code>NotIntegerError</code> 例外的案例。<pre class='nd pp'><code>class ToRomanBadInput(unittest.TestCase):
.
.
.
def test_non_integer(self):
'''to_roman should fail with non-integer input'''
<mark> self.assertRaises(roman4.NotIntegerError, roman4.to_roman, 0.5)</mark></code></pre>
<p>然后,检查该测试是否可以正确地失败。<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest4.py -v</kbd>
<samp>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)
<mark>AssertionError: NotIntegerError not raised by to_roman</mark>
----------------------------------------------------------------------
Ran 5 tests in 0.000s
FAILED (failures=1)</samp></pre>
<p>编修代码,使得该测试可以通过。<pre class=pp><code>def to_roman(n):
'''convert integer to Roman numeral'''
if not (0 < n < 4000):
raise OutOfRangeError('number out of range (must be 1..3999)')
<a> if not isinstance(n, int): <span class=u>①</span></a>
<a> raise NotIntegerError('non-integers can not be converted') <span class=u>②</span></a>
result = ''
for numeral, integer in roman_numeral_map:
while n >= integer:
result += numeral
n -= integer
return result</code></pre>
<ol>
<li>内建的 <code>isinstance()</code> 方法可以检查一个变量是否属于某一类型(或者,技术上的任何派生类型)。</li><li>如果参数 <var>n</var> 不是 <code>int</code>,则抛出新定义的 <code>NotIntegerError</code> 异常。
</li></ol>
<p>最后,验证修改后的代码的确通过测试。<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest4.py -v</kbd>
<samp>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</samp></pre>
<p><code>to_roman()</code> 方法通过了所有的测试,而且我也想不出别的测试了,因此,下面着手 <code>from_roman()</code>吧!<p class=a>⁂
<h2 id=romantest5>可喜的对称性</h2>
<p>转换罗马数字为阿拉伯数字的实现难度听起来比反向转换要困难。当然,这种想法不无道理。例如,检查数值是否比0大容易,而检查一个字符串是否为有效的罗马数字则要困难些。但是,我们已经构造了<a href="regular-expressions.html#romannumerals">一个用于检查罗马数字的规则表</a>,因此规则表的工作可以免了。<p>现在剩余的工作就是转换字符串了。正如我们将要看到的一样,多亏我们定义的用于单个罗马数字映射至阿拉伯数字的良好的数据结构,<code>from_roman()</code> 的实现本质上与 <code>to_roman()</code> 一样简单。<p>不过,测试先行!为了证明其准确性,我们将需要一个对“已知取值”进行的测试。我们的测试套件已经包含了<a href="unit-testing.html#romantest1">一个已知取值的映射表</a>,那么,我们就重用它。<pre class='nd pp'><code> 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)</code></pre>
<p>这里看到了令人高兴的对称性。<code>to_roman()</code> 与 <code>from_roman()</code> 函数是互逆的。前者把整型数字转换为特殊格式化的字符串,而后者则把特殊格式化的字符串转换为整型数字。理论上,我们应该可以使一个数字“绕一圈”,即把数字传递给 <code>to_roman()</code> 方法,得到一个字符串;然后把该字符串传入 <code>from_roman()</code> 方法,得到一个整型数字,并且跟传给to_roman()方法的数字是一样的。<pre class='nd pp'><code>n = from_roman(to_roman(n)) for all values of n</code></pre>
<p>在本用例中,“全有取值”是说 <code>从1到3999</code> 的所有数值,因为这是 <code>to_roman()</code> 方法的有效输入范围。为了表达这两个方法之间的对称性,我们可以设计这样的测试用例,它的测试数据集是从<code>1到3999之间</code>(包括1和3999)的所有数值,首先调用 <code>to_roman()</code> ,然后调用 <code>from_roman()</code>,最后检查输出是否与原始输入一致。<pre class='nd pp'><code>class RoundtripCheck(unittest.TestCase):
def test_roundtrip(self):
'''from_roman(to_roman(n))==n for all n'''
for integer in range(1, 4000):
numeral = roman5.to_roman(integer)
result = roman5.from_roman(numeral)
self.assertEqual(integer, result)</code></pre>
<p>这些测试连失败的机会都没有。因为我们根本还没定义 <code>from_roman()</code> 函数,所以它们仅仅会抛出错误的结果。<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest5.py</kbd>
<samp>E.E....
======================================================================
ERROR: test_from_roman_known_values (__main__.KnownValues)
from_roman should give known result with known input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest5.py", line 78, in test_from_roman_known_values
result = roman5.from_roman(numeral)
AttributeError: 'module' object has no attribute 'from_roman'
======================================================================
ERROR: test_roundtrip (__main__.RoundtripCheck)
from_roman(to_roman(n))==n for all n
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest5.py", line 103, in test_roundtrip
result = roman5.from_roman(numeral)
AttributeError: 'module' object has no attribute 'from_roman'
----------------------------------------------------------------------
Ran 7 tests in 0.019s
FAILED (errors=2)</samp></pre>
<p>一个简易的留空函数可以解决此问题。<pre class='nd pp'><code># roman5.py
def from_roman(s):
'''convert Roman numeral to integer'''</code></pre>
<p>(嘿,你注意到了么?我定义了一个除了 <a href="your-first-python-program.html#docstrings">docstring</a> 之外没有任何东西的方法。这是合法的 Python 代码。事实上,一些程序员喜欢这样做。“不要留空;写点文档!”)<p>现在测试用力将会失败。<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest5.py</kbd>
<samp>F.F....
======================================================================
FAIL: test_from_roman_known_values (__main__.KnownValues)
from_roman should give known result with known input
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest5.py", line 79, in test_from_roman_known_values
self.assertEqual(integer, result)
AssertionError: 1 != None
======================================================================
FAIL: test_roundtrip (__main__.RoundtripCheck)
from_roman(to_roman(n))==n for all n
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest5.py", line 104, in test_roundtrip
self.assertEqual(integer, result)
AssertionError: 1 != None
----------------------------------------------------------------------
Ran 7 tests in 0.002s
FAILED (failures=2)</samp></pre>
<p>现在是时候编写 <code>from_roman()</code> 函数了。<pre class=pp><code>def from_roman(s):
"""convert Roman numeral to integer"""
result = 0
index = 0
for numeral, integer in roman_numeral_map:
<a> while s[index:index+len(numeral)] == numeral: <span class=u>①</span></a>
result += integer
index += len(numeral)
return result</code></pre>
<ol>
<li>此处的匹配模式与 <a href="unit-testing.html#romantest1"><code>to_roman()</code></a> 完全相同。遍历整个罗马数字数据结构 (一个元组的元组),与前面不同的是不去一个个地搜索最大的整数,而是搜寻 “最大的”罗马数字字符串。</li></ol>
<p>如果不清楚 <code>from_roman()</code> 如何工作,在 <code>while</code> 结尾处添加一个 <code>print</code> 语句:
<pre><code>def from_roman(s):
"""convert Roman numeral to integer"""
result = 0
index = 0
for numeral, integer in roman_numeral_map:
while s[index:index+len(numeral)] == numeral:
result += integer
index += len(numeral)
<mark> print('found', numeral, 'of length', len(numeral), ', adding', integer)</mark></code></pre>
<pre class='nd screen'>
<samp class=p>>>> </samp><kbd class=pp>import roman5</kbd>
<samp class=p>>>> </samp><kbd class=pp>roman5.from_roman('MCMLXXII')</kbd>
<samp class=pp>found M of length 1, adding 1000
found CM of length 2, adding 900
found L of length 1, adding 50
found X of length 1, adding 10
found X of length 1, adding 10
found I of length 1, adding 1
found I of length 1, adding 1
1972</samp></pre>
<p>重新执行一遍测试。<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest5.py</kbd>
<samp>.......
----------------------------------------------------------------------
Ran 7 tests in 0.060s
OK</samp></pre>
<p>这儿有两个令人激动的消息。一个是 <code>from_roman()</code> 对于所有有效输入运转正常,至少对于你测试的已知值是这样。第二个好消息是,完备性测试也通过了。与已知值测试的通过一起来看,你有理由相信 <code>to_roman()</code> 和 <code>from_roman()</code> 对于所有有效输入值工作正常。(尚不能完全相信,理论上存在这种可能性: <code>to_roman()</code> 存在错误而导致一些特定输入会产生错误的罗马数字表示,<em>and</em> <code>from_roman()</code> 也存在相应的错误,把 <code>to_roman()</code> 错误产生的这些罗马数字错误地转换为最初的整数。取决于你的应用程序和你的要求,你或许需要考虑这个可能性;如果是这样,编写更全面的测试用例直到解决这个问题。)<p class=a>⁂
<h2 id=romantest6>更多错误输入</h2>
<p>现在 <code>from_roman()</code> 对于有效输入能够正常工作了,是揭开最后一个谜底的时候了:使它正常工作于无效输入的情况下。这意味着要找出一个方法检查一个字符串是不是有效的罗马数字。这比中<a href="unit-testing.html#romantest3">验证有效的数字输入</a>困难,但是你可以使用一个强大的工具:正则表达式。(如果你不熟悉正则表达式,现在是该好好读读<a href="regular-expressions.html">正则表达式</a>那一章节的时候了。)<p>如你在 <a href="regular-expressions.html#romannumerals">个案研究:罗马字母s</a>中所见到的,构建罗马数字有几个简单的规则:使用的字母<code>M</code> , <code>D</code> , <code>C</code> , <code>L</code> , <code>X</code> , <code>V</code>和<code>I</code> 。让我们回顾一下:<ul>
<li>有时字符是叠加组合的。<code>I</code> 是 <code>1</code>, <code>II</code> 是 <code>2</code>,而<code>III</code> 是 <code>3</code>.
<code>VI</code> 是 <code>6</code> (从字面上理解, “<code>5</code> 和 <code>1</code>”), <code>VII</code> 是 <code>7</code>, 而 <code>VIII</code> 是 <code>8</code>。
</li><li>十位的字符 (<code>I</code>、 <code>X</code>、 <code>C</code> 和 <code>M</code>) 可以被重复最多三次。对于 <code>4</code>,你则需要利用下一个能够被5整除的字符进行减操作得到。你不能把 <code>4</code> 表示为<code>IIII</code>,而应该表示为<code>IV</code> (“比 <code>5</code> 小 <code>1</code> ”)。<code>40</code> 则被写作 <code>XL</code> (“比 <code>50</code> 小 <code>10</code>”),<code>41</code> 表示为 <code>XLI</code>,<code>42</code> 表示为 <code>XLII</code>,<code>43</code> 表示为 <code>XLIII</code>, <code>44</code> 表示为 <code>XLIV</code> (“比 <code>50</code> 小 <code>10</code>,加上 <code>5</code> 小 <code>1</code>”)。</li><li>有时,字符串是……加法的对立面。通过将某些字符串放的其他一些之前,可以从最终值中相减。例如,对于 <code>9</code>,你需要从下一个最高十位字符串中减去一个值:<code>8</code> 是 <code>VIII</code>,但 <code>9</code> 是 <code>IX</code>(“ 比 <code>10</code> 小 <code>1</code>”),而不是<code>VIIII</code> (由于 <code>I</code> 字符不能重复四次)。<code>90</code> 是 <code>XC</code>, <code>900</code> 是 <code>CM</code>。
</li><li>表示 5 的字符不能重复。<code>10</code> 总是表示为 <code>X</code>,而决不能是 <code>VV</code>。
<code>100</code> 总是 <code>C</code>,决不能是 <code>LL</code>。
</li><li>罗马数字从左向右读,因此字符的顺序非常重要。<code>DC</code> 是 <code>600</code>; <code>CD</code> 则是完全不同的数字 (<code>400</code>, “比 <code>500</code> 小 <code>100</code> ”)。
<code>CI</code> 是 <code>101</code>; <code>IC</code> 甚至不是合法的罗马数字(因为你不能直接从 <code>100</code> 减 <code>1</code>;你将不得不将它表示为 <code>XCIX</code>,“比 <code>100</code> 小<code>10</code> ,然后比 <code>10</code>” 小 <code>1</code>)。</li></ul>
<p>因此,有用的测试将会确保 <code>from_roman()</code> 函数应当在传入太多重复数字时失败。“太多”是多少取决于数字。<pre class='nd pp'><code>class FromRomanBadInput(unittest.TestCase):
def test_too_many_repeated_numerals(self):
'''from_roman should fail with too many repeated numerals'''
for s in ('MMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):
self.assertRaises(roman6.InvalidRomanNumeralError, roman6.from_roman, s)</code></pre>
<p>另一有效测试是检查某些未被重复的模式。例如,<code>IX</code> 代表 <code>9</code>,但 <code>IXIX</code> 绝不会合法。<pre class='nd pp'><code> def test_repeated_pairs(self):
'''from_roman should fail with repeated pairs of numerals'''
for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):
self.assertRaises(roman6.InvalidRomanNumeralError, roman6.from_roman, s)</code></pre>
<p>第三个测试应当检测数字是否以正确顺序出现,从最高到最低位。例如,<code>CL</code> 是 <code>150</code>,而 <code>LC</code> 永远是非法的,因为代表 <code>50</code> 的数字永远不能在 <code>100</code> 数字之前出现。
该测试包括一个随机的可选项:<code>I</code> 在 <code>M</code> 之前, <code>V</code> 在 <code>X</code> 之前,等等。<pre class='nd pp'><code> def test_malformed_antecedents(self):
'''from_roman should fail with malformed antecedents'''
for s in ('IIMXCC', 'VX', 'DCM', 'CMM', 'IXIV',
'MCMC', 'XCX', 'IVI', 'LM', 'LD', 'LC'):
self.assertRaises(roman6.InvalidRomanNumeralError, roman6.from_roman, s)</code></pre>
<p>这些测试中的每个都依赖于 <code>from_roman()</code> 引发一个新的例外 <code>InvalidRomanNumeralError</code>,而该例外尚未定义。<pre class='nd pp'><code># roman6.py
class InvalidRomanNumeralError(ValueError): pass</code></pre>
<p>所有的测试都应该是失败的,因为 <code>from_roman()</code> 方法还没有任何有效性检查。
(如果没有失败,它们在测什么呢?)<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest6.py</kbd>
<samp>FFF.......
======================================================================
FAIL: test_malformed_antecedents (__main__.FromRomanBadInput)
from_roman should fail with malformed antecedents
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest6.py", line 113, in test_malformed_antecedents
self.assertRaises(roman6.InvalidRomanNumeralError, roman6.from_roman, s)
AssertionError: InvalidRomanNumeralError not raised by from_roman
======================================================================
FAIL: test_repeated_pairs (__main__.FromRomanBadInput)
from_roman should fail with repeated pairs of numerals
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest6.py", line 107, in test_repeated_pairs
self.assertRaises(roman6.InvalidRomanNumeralError, roman6.from_roman, s)
AssertionError: InvalidRomanNumeralError not raised by from_roman
======================================================================
FAIL: test_too_many_repeated_numerals (__main__.FromRomanBadInput)
from_roman should fail with too many repeated numerals
----------------------------------------------------------------------
Traceback (most recent call last):
File "romantest6.py", line 102, in test_too_many_repeated_numerals
self.assertRaises(roman6.InvalidRomanNumeralError, roman6.from_roman, s)
AssertionError: InvalidRomanNumeralError not raised by from_roman
----------------------------------------------------------------------
Ran 10 tests in 0.058s
FAILED (failures=3)</samp></pre>
<p>好!现在,我们要做的所有事情就是添加<a href="regular-expressions.html#romannumerals">正则表达式</a>到 <code>from_roman()</code> 中以测试有效的罗马数字。<pre class='nd pp'><code>roman_numeral_pattern = re.compile('''
^ # beginning of string
M{0,3} # thousands - 0 to 3 Ms
(CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs),
# or 500-800 (D, followed by 0 to 3 Cs)
(XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs),
# or 50-80 (L, followed by 0 to 3 Xs)
(IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is),
# or 5-8 (V, followed by 0 to 3 Is)
$ # end of string
''', re.VERBOSE)
def from_roman(s):
'''convert Roman numeral to integer'''
<mark> if not roman_numeral_pattern.search(s):
raise InvalidRomanNumeralError('Invalid Roman numeral: {0}'.format(s))</mark>
result = 0
index = 0
for numeral, integer in roman_numeral_map:
while s[index : index + len(numeral)] == numeral:
result += integer
index += len(numeral)
return result</code></pre>
<p>再运行一遍测试……<pre class='nd screen'>
<samp class=p>you@localhost:~/diveintopython3/examples$ </samp><kbd>python3 romantest7.py</kbd>
<samp>..........
----------------------------------------------------------------------
Ran 10 tests in 0.066s
OK</samp></pre>
<p>本年度的虎头蛇尾奖颁发给……单词“OK”,在所有测试通过时,它由 <code>unittest</code> 模块输出。<p class=v><a href="advanced-iterators.html" rel=prev title="back to “Advanced Iterators”"><span class=u>☜</span></a> <a href="refactoring.html" rel=next title="onward to “Refactoring”"><span class=u>☞</span></a>
<p class=c>© 2001–9 <a href="about.html">Mark Pilgrim</a>
<script src="j/jquery.js"></script>
<script src="j/prettify.js"></script>
<script src="j/dip3.js"></script>