Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active April 3, 2016 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/1833320ab55ae5ea660ce0c635483d26 to your computer and use it in GitHub Desktop.
Save Cartman0/1833320ab55ae5ea660ce0c635483d26 to your computer and use it in GitHub Desktop.
Dive Into Python3 9章メモ ユニットテスト
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"toc": "true"
},
"cell_type": "markdown",
"source": "# Table of Contents\n <p><div class=\"lev1\"><a href=\"#ユニットテスト-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>ユニットテスト</a></div><div class=\"lev2\"><a href=\"#飛び込(まない)-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>飛び込(まない)</a></div><div class=\"lev2\"><a href=\"#一つの問い-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>一つの問い</a></div><div class=\"lev3\"><a href=\"#コマンドラインでテスト-1.2.1\"><span class=\"toc-item-num\">1.2.1&nbsp;&nbsp;</span>コマンドラインでテスト</a></div><div class=\"lev3\"><a href=\"#Jupyter-でテストする場合-1.2.2\"><span class=\"toc-item-num\">1.2.2&nbsp;&nbsp;</span>Jupyter でテストする場合</a></div><div class=\"lev3\"><a href=\"#インポートしてる場合-1.2.3\"><span class=\"toc-item-num\">1.2.3&nbsp;&nbsp;</span>インポートしてる場合</a></div><div class=\"lev4\"><a href=\"#ソースコードの出力-1.2.3.1\"><span class=\"toc-item-num\">1.2.3.1&nbsp;&nbsp;</span>ソースコードの出力</a></div><div class=\"lev3\"><a href=\"#to_roman()関数を書いていく-1.2.4\"><span class=\"toc-item-num\">1.2.4&nbsp;&nbsp;</span>to_roman()関数を書いていく</a></div><div class=\"lev2\"><a href=\"#“Halt-And-Catch-Fire”-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>“Halt And Catch Fire”</a></div><div class=\"lev2\"><a href=\"#もっと中断させて、もっと発火させる-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>もっと中断させて、もっと発火させる</a></div><div class=\"lev2\"><a href=\"#さらにもう一つ……-1.5\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>さらにもう一つ……</a></div><div class=\"lev2\"><a href=\"#すばらしき対称性-1.6\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;</span>すばらしき対称性</a></div><div class=\"lev2\"><a href=\"#不適切な入力値-1.7\"><span class=\"toc-item-num\">1.7&nbsp;&nbsp;</span>不適切な入力値</a></div><div class=\"lev2\"><a href=\"#参考リンク-1.8\"><span class=\"toc-item-num\">1.8&nbsp;&nbsp;</span>参考リンク</a></div>"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- [Dive Into Python3 1章メモ](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/d54093a99b9254c81bf1123adacbc48a/raw/eedc90bbbfc14e259854f2e739fffeec4cb4d8f7/DiveIntoPython3_01.ipynb)\n- [Dive Into Python3 2章メモ(ネイティブデータ型)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/988b51d8482ad9ade835bb07efdffb38/raw/784cf276b7cebe254e59f09dcea6f09eea760d38/DiveIntoPython3_02.ipynb)\n- [Dive Into Python3 3章メモ(内包表記)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/183ec6f6c835f621106f7c27d215290a/raw/bd7677946d6400bbe6acd257df7fb9c5976c3320/DiveIntoPython3_03.ipynb)\n- [Dive Into Python3 4章メモ(文字列)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/bb974f82e8a3fc74ac82c3c2a5b1a4f9/raw/63a80011c9391b451108c1a4dc804ec5ff125f34/DiveIntoPython3_04.ipynb)\n- [Dive Into Python3 5章メモ(正規表現)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/b834807a0dabb1c458b87be2f333a5ca/raw/37d6f25f67e017a569e1f0b60a9fcbe49d50515f/DiveIntoPython3_05.ipynb?flush_cache=true)\n- [Dive Into Python3 6章メモ(クロージャとジェネレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/a8998f8f88c5578271495ada56cc4809/raw/4e9b8ef3543016a710f905215693694acd703549/DiveIntoPython3_06.ipynb?flush_cache=true)\n- [Dive Into Python3 7章メモ(クラスとイテレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/8eb511c3b2aa6cadad6f6d49666c9db2/raw/60863d1ce1c1e9e4cb336ad79a0e252807beb87c/DiveIntoPython3_07.ipynb?flush_cache=true)\n- [Dive Into Python3 8章メモ(高度なイテレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/9ed3037cbdac59af53c20c125aed806e/raw/46ee3c71d72ab7ee665cf0c10f8717734632b462/DiveIntoPython3_08.ipynb?flush_cache=true)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "# ユニットテスト"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 飛び込(まない)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この章では、整数とローマ数字を相互変換する一組のユーティリティ関数を書いて、\nそれをデバッグする。\nローマ数字の組み立て方とその有効性の検証法については、\n「ケーススタディ: ローマ数字」で学んだ。\n\nでは一度そこに立ち返って、どうやったらそこから双方向なユーティリティを作れるかを考える。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ローマ数字の規則を見ると、興味深い洞察がいくつか得られる:\n\n- ある特定の数をローマ数字で表現する方法は一つしかない。\n- 逆もまた真なり。ある文字列が有効なローマ数字ならば、それは特定の一つの数を表している(つまり、ローマ数字は一通りにしか解釈できない)。\n- ローマ数字で表しうる数の範囲には限りがある。具体的に言えば1から3999までの数だ。実際には、ローマ数字でもっと大きな数を表す方法はいくつかあって、例えば数字の上に棒線を引くことでその数字の1000倍の数を表すことができた。だがまあ、とりあえずこの章ではローマ数字は1から3999までの数しか表せないものとしよう。\n- ローマ数字でゼロを表すことはできない。\n- ローマ数字で負の数を表すことはできない。\n- ローマ数字で分数や整数でない数を表すことはできない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "では、`roman.py`モジュールに何が必要なのかを考えていこう。\n主たる関数として `to_roman()` と\n`from_roman()` の二つがいる。\n`to_roman()`関数は1から3999までの整数を引数にとり、\n対応するローマ数字を文字列として返す。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`to_roman()`関数が望み通りの動きをするかをチェックするテストケースを書く。\n大丈夫、読み間違えでもなんでもない。\n実際にこれから、まだ書かれてもいないコードをテストするコードを書く。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これは **テスト駆動開発 (TDD)** と呼ばれている手法。\n\n変換を行うこの二つの関数 — `to_roman()` と後で出てくる `from_roman()` は、\nこれらをインポートする他のもっと大規模なプログラムとは独立に、一つの構成単位として書いたりテストしたりできる。\n\nPythonには、**ユニットテストのためのフレームワーク `unittest`モジュール** がある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "**ユニットテスト** は、テストを中心に据える開発手法全般のかなめといえる存在。\nユニットテストを書くなら、早い段階で書きあげた上で、コードや要件の変更に合わせてアップデートしていくことが重要になる。\n多くの人はコードを書く前にテストを書くやり方を推奨していて、\n実際にこの章でもこのスタイルを用いるが、\nユニットテスト自体はいつ書いても有益なものである。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- コードを書く前: \nユニットテストを書こうとすれば、要件を実用的な形で練り上げざるをえなくなる。\n\n- コードを書いている最中: \nユニットテストがあれば過剰なコーディングを避けることができる。\nすべてのテストケースに通ったなら、その関数はもう完成。\n\n- リファクタリングする時: \n新しいコードが古いバージョンのコードと同じように動くかどうかを確認するのに役立つ。\n\n- コードを保守する時: \n誰かがあなたの所にやって来て「お前が加えた変更のせいで古いコードが壊れたじゃないか」とわめいた時に、ユニットテストがあれば言い逃れができる。\n\n- チームでコードを書く時: \n包括的なテストスイートがあれば、\nあなたのコードが別の誰かのコードを壊してしまうといったことが非常に少なくなる。\n事前に他の人のユニットテストを走らせることができる。\n(コードスプリントでこういうやり方をしているのを見たことがある。\nチームに割り当てられた仕事を分割した上で、\n各々が仕様書に目を通してユニットテストを書き、\nそれをチームで共有する。\nこうすると、他の部分とうまくかみ合わないようなコードが早いうちに直されるようになる)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 一つの問い"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "一つのテストケースは、そのコードに関するただ一つの問いのみに答える。\nまた、テストケースというものは"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- 単独で完全に機能し、人の入力を必要としないものでなくてはならない。\nユニットテストの本質は自動化にある。\n\n- ある関数がテストをパスしたかどうかを、人の解釈によらず、自ら判定するものでなくてはならない。\n\n- (同じ関数をテストしているテストケースも含む)\n他のいかなるテストケースからも独立し、\n単体で動作するものでなくてはならない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "以上のことを前提に、一番最初の要件に対するテストケースを書いてみる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- `to_roman()` は、1から3999までのすべての整数に対応するローマ数字を返せなくてはならない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "一見すると、「このコードって本当に何かの役に立つの?」と思われるかもしれない。\n一つのクラスが定義されているが、\n中には `__init__`メソッドが入っていない。\n別のメソッドもあることはあるのだが、\nこのメソッドは一度も呼び出されていない。\nこのスクリプトの `__main__`ブロックにしても、\nこのクラスやメソッドを参照してすらいない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストケースを書くには、\nまず`unittest`モジュールの`TestCase`クラスをサブクラス化(継承)する。\nこのクラスには、テストケースで特定の条件をテストする時に便利なメソッドがたくさん入っている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`known_values` は、整数/数字のペアのリスト。\nこのリストには、最も小さい10個の数、最も大きい数、一文字のローマ数字で表される数すべて、さらにこれら以外の有効な数字からランダムに抽出された数が含まれている。\nありとあらゆる入力値を試す必要はないが、\n境界事例だと分かっているものについてはすべてテストするべき。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import unittest\nunittest",
"execution_count": 1,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<module 'unittest' from 'C:\\\\Miniconda3\\\\lib\\\\unittest\\\\__init__.py'>"
},
"metadata": {},
"execution_count": 1
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\nimport roman1\nimport unittest\n\nclass KnownValues(unittest.TestCase):\n known_values = ( (1, 'I'),\n (2, 'II'),\n (3, 'III'),\n (4, 'IV'),\n (5, 'V'),\n (6, 'VI'),\n (7, 'VII'),\n (8, 'VIII'),\n (9, 'IX'),\n (10, 'X'),\n (50, 'L'),\n (100, 'C'),\n (500, 'D'),\n (1000, 'M'),\n (31, 'XXXI'),\n (148, 'CXLVIII'),\n (294, 'CCXCIV'),\n (312, 'CCCXII'),\n (421, 'CDXXI'),\n (528, 'DXXVIII'),\n (621, 'DCXXI'),\n (782, 'DCCLXXXII'),\n (870, 'DCCCLXX'),\n (941, 'CMXLI'),\n (1043, 'MXLIII'),\n (1110, 'MCX'),\n (1226, 'MCCXXVI'),\n (1301, 'MCCCI'),\n (1485, 'MCDLXXXV'),\n (1509, 'MDIX'),\n (1607, 'MDCVII'),\n (1754, 'MDCCLIV'),\n (1832, 'MDCCCXXXII'),\n (1993, 'MCMXCIII'),\n (2074, 'MMLXXIV'),\n (2152, 'MMCLII'),\n (2212, 'MMCCXII'),\n (2343, 'MMCCCXLIII'),\n (2499, 'MMCDXCIX'),\n (2574, 'MMDLXXIV'),\n (2646, 'MMDCXLVI'),\n (2723, 'MMDCCXXIII'),\n (2892, 'MMDCCCXCII'),\n (2975, 'MMCMLXXV'),\n (3051, 'MMMLI'),\n (3185, 'MMMCLXXXV'),\n (3250, 'MMMCCL'),\n (3313, 'MMMCCCXIII'),\n (3408, 'MMMCDVIII'),\n (3501, 'MMMDI'),\n (3610, 'MMMDCX'),\n (3743, 'MMMDCCXLIII'),\n (3844, 'MMMDCCCXLIV'),\n (3888, 'MMMDCCCLXXXVIII'),\n (3940, 'MMMCMXL'),\n (3999, 'MMMCMXCIX')\n )\n \n def test_to_roman_known_values(self):\n '''to_roman should give known result with known input'''\n for integer, numeral in self.known_values:\n result = roman1.to_roman(integer)\n self.assertEqual(numeral, result)\n\nif __name__ == '__main__':\n unittest.main()\n\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "個々のテストはそれぞれメソッド(`def test_to_roman_known_values()`)として表される。\nメソッドは引数を取らなければ値も返さないようなものであり、\n**メソッド名は4文字のtestで始まっていなければならない**。\n\nもし、メソッドが\n- 例外を送出することなく普通に終了したならば、テストをパスしたものとみなされる。\n- 例外が送出された場合には、テストは失敗したとみなされる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`def test_to_roman_known_values()` の中:\n\n最後に残ったステップは、\n正しい値が返されているかどうかチェックすること。\n\nこれはテストケース一般でチェックされる項目なので、TestCaseクラスに二つの値が等しいかどうかを調べる`assertEqual` メソッドが用意されている。\nto_roman()が返した値(result)が、\n- 返されるべき既知の値(numeral)と一致しなかったなら、assertEqualは例外を送出し、テストは失敗する。\n\n- 二つの値が等しければ、assertEqualは何もしない。だから、to_roman()のすべての戻り値が、返されるべき既知の値と一致したならば、assertEqualは一度も例外を送出せず、test_to_roman_known_valuesは正常に終了する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストケースができたら、\nto_roman()関数のコードを書き始めることができる。\nだが、まずは最初に中身が空のto_roman()関数を作って、\nテストが失敗することを確かめなくてはならない。\n\nもし、何も書いていないのにパスできてしまうようなら、\n何のテストにもならない。\n通らないようなテストを書いて、パスするまでコーディングする。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この段階では、`to_roman()` のAPIを定義するだけで、\n中身をコーディングしようとは思ってはいない\n(まずはテストを失敗させなくてはならない)。\nこの場合にはPythonの予約語のpassを使えばいい。\nこれは実行されても、全く何の処理も行わない。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "# roman1.py\n\ndef to_roman(n):\n '''convert integer to Roman numeral'''\n pass\n",
"execution_count": 2,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### コマンドラインでテスト"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "コマンドラインでromantest1.py を起動してテストを実行する。\nコマンドラインのオプションとして`-v` をつければ、それぞれのテストケースが実行される際の処理の状況が詳しく出力されるようになる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\n> python3 romantest1.py -v\n\ntest_to_roman_known_values (__main__.KnownValues) ①\nto_roman should give known result with known input ... FAIL ②\n\n======================================================================\nFAIL: to_roman should give known result with known input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"romantest1.py\", line 73, in test_to_roman_known_values\n self.assertEqual(numeral, result)\nAssertionError: 'I' != None ③\n\n----------------------------------------------------------------------\nRan 1 test in 0.016s ④\n\nFAILED (failures=1) ⑤\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このスクリプトを走らせると`unittest.main()` が呼び出され、\nそれぞれのテストケースが実行される。\n\n各々のテストケースはromantest.pyの中のクラスに入っているメソッド。\nこのテストクラスはどのような構成をしていてもよい。いくつかのクラスがあって、それぞれにテストメソッドが一つずつ入っているというのでもよいし、複数のメソッドが入ったクラスが一つあるというのでも構わない。ただすべてのテストクラスが `unittest.TestCase` を継承してさえいればいい。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "2行目に、各々のテストについて、`unittest`モジュールはそのメソッドの `docstring` とテストの成否を出力する。予想通り、このテストケースは失敗している。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "失敗したテストケースについては、`unittest` は何が起こったのかをトレースして表示してくれる。\nこのケースでは、`assertEqual()` を呼び出した際に `AssertionError` が送出されている。`to_roman(1)` は 'I' を返すものとされていたのに、\nそうならなかったから\n(この関数にはreturn文が置かれて無いので、Python のNull値にあたるNone が返されている)。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "それぞれのテストの詳細を出力した後で、`unittest` はいくつのテストが実行され、それにどれくらいの時間がかかったのかを表示する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "まとめると、少なくとも一つのテストケースをパスしなかったので、\nこのテストは失敗したことになる。\n\nなお、テストケースにパスしなかったという場合について、\nunittestは\n- Failure\n- Error\n\nを区別する。\n\n**Failure** とは、assertEqualやassertRaisesといったassertXYZメソッドを呼びだしたが、表明された条件が真でなかったり、期待通りに例外が送出されなかったせいで失敗してしまった場合を指す。\n\nこれ以外の、テストしているコードやユニットテストのテストケース自体から送出された例外はすべてErrorとされる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### Jupyter でテストする場合"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import unittest\n\nclass KnownValues(unittest.TestCase):\n known_values = ( (1, 'I'),\n (2, 'II'),\n (3, 'III'),\n (4, 'IV'),\n (5, 'V'),\n (6, 'VI'),\n (7, 'VII'),\n (8, 'VIII'),\n (9, 'IX'),\n (10, 'X'),\n (50, 'L'),\n (100, 'C'),\n (500, 'D'),\n (1000, 'M'),\n (31, 'XXXI'),\n (148, 'CXLVIII'),\n (294, 'CCXCIV'),\n (312, 'CCCXII'),\n (421, 'CDXXI'),\n (528, 'DXXVIII'),\n (621, 'DCXXI'),\n (782, 'DCCLXXXII'),\n (870, 'DCCCLXX'),\n (941, 'CMXLI'),\n (1043, 'MXLIII'),\n (1110, 'MCX'),\n (1226, 'MCCXXVI'),\n (1301, 'MCCCI'),\n (1485, 'MCDLXXXV'),\n (1509, 'MDIX'),\n (1607, 'MDCVII'),\n (1754, 'MDCCLIV'),\n (1832, 'MDCCCXXXII'),\n (1993, 'MCMXCIII'),\n (2074, 'MMLXXIV'),\n (2152, 'MMCLII'),\n (2212, 'MMCCXII'),\n (2343, 'MMCCCXLIII'),\n (2499, 'MMCDXCIX'),\n (2574, 'MMDLXXIV'),\n (2646, 'MMDCXLVI'),\n (2723, 'MMDCCXXIII'),\n (2892, 'MMDCCCXCII'),\n (2975, 'MMCMLXXV'),\n (3051, 'MMMLI'),\n (3185, 'MMMCLXXXV'),\n (3250, 'MMMCCL'),\n (3313, 'MMMCCCXIII'),\n (3408, 'MMMCDVIII'),\n (3501, 'MMMDI'),\n (3610, 'MMMDCX'),\n (3743, 'MMMDCCXLIII'),\n (3844, 'MMMDCCCXLIV'),\n (3888, 'MMMDCCCLXXXVIII'),\n (3940, 'MMMCMXL'),\n (3999, 'MMMCMXCIX')\n )\n\n def test_to_roman_known_values(self):\n '''to_roman should give known result with known input'''\n for integer, numeral in self.known_values:\n result = to_roman(integer)\n self.assertEqual(numeral, result)\n \n \n",
"execution_count": 3,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`TestLoader` と `TextTestRunner` を使う。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test)",
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\nF\n======================================================================\nFAIL: test_to_roman_known_values (__main__.KnownValues)\nto_roman should give known result with known input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-3-f4de237d18b0>\", line 66, in test_to_roman_known_values\n self.assertEqual(numeral, result)\nAssertionError: 'I' != None\n\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nFAILED (failures=1)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=1>"
},
"metadata": {},
"execution_count": 4
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### インポートしてる場合"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import roman1\nimport unittest\n\nclass KnownValues(unittest.TestCase):\n known_values = ( (1, 'I'),\n (2, 'II'),\n (3, 'III'),\n (4, 'IV'),\n (5, 'V'),\n (6, 'VI'),\n (7, 'VII'),\n (8, 'VIII'),\n (9, 'IX'),\n (10, 'X'),\n (50, 'L'),\n (100, 'C'),\n (500, 'D'),\n (1000, 'M'),\n (31, 'XXXI'),\n (148, 'CXLVIII'),\n (294, 'CCXCIV'),\n (312, 'CCCXII'),\n (421, 'CDXXI'),\n (528, 'DXXVIII'),\n (621, 'DCXXI'),\n (782, 'DCCLXXXII'),\n (870, 'DCCCLXX'),\n (941, 'CMXLI'),\n (1043, 'MXLIII'),\n (1110, 'MCX'),\n (1226, 'MCCXXVI'),\n (1301, 'MCCCI'),\n (1485, 'MCDLXXXV'),\n (1509, 'MDIX'),\n (1607, 'MDCVII'),\n (1754, 'MDCCLIV'),\n (1832, 'MDCCCXXXII'),\n (1993, 'MCMXCIII'),\n (2074, 'MMLXXIV'),\n (2152, 'MMCLII'),\n (2212, 'MMCCXII'),\n (2343, 'MMCCCXLIII'),\n (2499, 'MMCDXCIX'),\n (2574, 'MMDLXXIV'),\n (2646, 'MMDCXLVI'),\n (2723, 'MMDCCXXIII'),\n (2892, 'MMDCCCXCII'),\n (2975, 'MMCMLXXV'),\n (3051, 'MMMLI'),\n (3185, 'MMMCLXXXV'),\n (3250, 'MMMCCL'),\n (3313, 'MMMCCCXIII'),\n (3408, 'MMMCDVIII'),\n (3501, 'MMMDI'),\n (3610, 'MMMDCX'),\n (3743, 'MMMDCCXLIII'),\n (3844, 'MMMDCCCXLIV'),\n (3888, 'MMMDCCCLXXXVIII'),\n (3940, 'MMMCMXL'),\n (3999, 'MMMCMXCIX')\n )\n\n def test_to_roman_known_values(self):\n '''to_roman should give known result with known input'''\n for integer, numeral in self.known_values:\n result = roman1.to_roman(integer)\n self.assertEqual(numeral, result)\n \n",
"execution_count": 5,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "各々のテストについて、unittestモジュールはそのメソッドのdocstringとテストの成否を出力する。予想通り、このテストケースは失敗している。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test)",
"execution_count": 6,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\nF\n======================================================================\nFAIL: test_to_roman_known_values (__main__.KnownValues)\nto_roman should give known result with known input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-5-6f3417485f53>\", line 67, in test_to_roman_known_values\n self.assertEqual(numeral, result)\nAssertionError: 'I' != None\n\n----------------------------------------------------------------------\nRan 1 test in 0.001s\n\nFAILED (failures=1)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=1>"
},
"metadata": {},
"execution_count": 6
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "#### ソースコードの出力"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "%psource roman1.to_roman",
"execution_count": 7,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import inspect\ninspect",
"execution_count": 8,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<module 'inspect' from 'C:\\\\Miniconda3\\\\lib\\\\inspect.py'>"
},
"metadata": {},
"execution_count": 8
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print(inspect.getsource(roman1.to_roman))",
"execution_count": 9,
"outputs": [
{
"output_type": "stream",
"text": "def to_roman(n):\n '''convert integer to Roman numeral'''\n pass \n\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### to_roman()関数を書いていく"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`roman_numeral_map` はタプルのタプルで、次の三つのものを定めている。\nすなわち、\n- 最も基本的なローマ数字の文字表記、\n- ローマ数字の順番(MからIまで、数が大きい順に並べてある)、\n- それぞれのローマ数字が表す値。\n\nこの内側のタプルはすべて`(numeral, value)` というペアからなっている。\nちなみに、ここでは一文字のローマ数字だけではなく、\nCM(「1000引く100」)など二文字のものについても定めている。\nこうすることで、`to_roman()`関数のコードがより簡潔なものになる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "roman_numeral_map = (\n ('M', 1000),\n ('CM', 900),\n ('D', 500),\n ('CD', 400),\n ('C', 100),\n ('XC', 90),\n ('L', 50),\n ('XL', 40),\n ('X', 10),\n ('IX', 9),\n ('V', 5),\n ('IV', 4),\n ('I', 1)\n)\n\ndef to_roman(n):\n '''convert integer to Roman numeral'''\n \n result = ''\n for numeral, integer in roman_numeral_map:\n while n >= integer:\n result += numeral\n n -= integer\n return result",
"execution_count": 10,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`roman_numeral_map` にデータを詰め込んだことが功を奏していて、\n引き算を用いて数を表すルールを扱うための特別なロジックを組む必要がなくなっている。\nつまり、ローマ数字に変換するには次のようにすればいいのだ。\nまず、単純に `roman_numeral_map` をイテレートして、\n入力値以下の数の中で最大の整数値を探す。\n\n次に、そのような数が見つかったら、\n対応するローマ数字を出力値の末尾に付け加え、\nさらに入力値からその数を引く。\n後はこれを繰り返し、また繰り返してさらに繰り返せばいい。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "to_roman()関数がどのように動くのかまだよく分からないのなら、print()をwhileループの末尾につけてみるといい:"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "def to_roman(n):\n '''convert integer to Roman numeral'''\n \n result = ''\n for numeral, integer in roman_numeral_map:\n while n >= integer:\n result += numeral\n n -= integer\n print('subtracting {0} from input, adding [{1}] to output, at least n:{2}'.format(integer, numeral, n))\n return result",
"execution_count": 11,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "デバッグ用のprint()文をつけると、次のように出力されるようになる:"
},
{
"metadata": {
"scrolled": true,
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(1424)",
"execution_count": 12,
"outputs": [
{
"output_type": "stream",
"text": "subtracting 1000 from input, adding [M] to output, at least n:424\nsubtracting 400 from input, adding [CD] to output, at least n:24\nsubtracting 10 from input, adding [X] to output, at least n:14\nsubtracting 10 from input, adding [X] to output, at least n:4\nsubtracting 4 from input, adding [IV] to output, at least n:0\n",
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "'MCDXXIV'"
},
"metadata": {},
"execution_count": 12
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "少なくとも、この手作業の抜き取り検査ではうまくやっているように見える。だが、さっき書いたテストケースはパスするだろうか?"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "def to_roman(n):\n '''convert integer to Roman numeral'''\n \n result = ''\n for numeral, integer in roman_numeral_map:\n while n >= integer:\n result += numeral\n n -= integer\n \n return result\n\n\nimport unittest\n\nclass KnownValues(unittest.TestCase):\n known_values = ( (1, 'I'),\n (2, 'II'),\n (3, 'III'),\n (4, 'IV'),\n (5, 'V'),\n (6, 'VI'),\n (7, 'VII'),\n (8, 'VIII'),\n (9, 'IX'),\n (10, 'X'),\n (50, 'L'),\n (100, 'C'),\n (500, 'D'),\n (1000, 'M'),\n (31, 'XXXI'),\n (148, 'CXLVIII'),\n (294, 'CCXCIV'),\n (312, 'CCCXII'),\n (421, 'CDXXI'),\n (528, 'DXXVIII'),\n (621, 'DCXXI'),\n (782, 'DCCLXXXII'),\n (870, 'DCCCLXX'),\n (941, 'CMXLI'),\n (1043, 'MXLIII'),\n (1110, 'MCX'),\n (1226, 'MCCXXVI'),\n (1301, 'MCCCI'),\n (1485, 'MCDLXXXV'),\n (1509, 'MDIX'),\n (1607, 'MDCVII'),\n (1754, 'MDCCLIV'),\n (1832, 'MDCCCXXXII'),\n (1993, 'MCMXCIII'),\n (2074, 'MMLXXIV'),\n (2152, 'MMCLII'),\n (2212, 'MMCCXII'),\n (2343, 'MMCCCXLIII'),\n (2499, 'MMCDXCIX'),\n (2574, 'MMDLXXIV'),\n (2646, 'MMDCXLVI'),\n (2723, 'MMDCCXXIII'),\n (2892, 'MMDCCCXCII'),\n (2975, 'MMCMLXXV'),\n (3051, 'MMMLI'),\n (3185, 'MMMCLXXXV'),\n (3250, 'MMMCCL'),\n (3313, 'MMMCCCXIII'),\n (3408, 'MMMCDVIII'),\n (3501, 'MMMDI'),\n (3610, 'MMMDCX'),\n (3743, 'MMMDCCXLIII'),\n (3844, 'MMMDCCCXLIV'),\n (3888, 'MMMDCCCLXXXVIII'),\n (3940, 'MMMCMXL'),\n (3999, 'MMMCMXCIX')\n )\n\n def test_to_roman_known_values(self):\n '''to_roman should give known result with known input'''\n for integer, numeral in self.known_values:\n result = to_roman(integer)\n self.assertEqual(numeral, result)\n ",
"execution_count": 13,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) ",
"execution_count": 14,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n.\n----------------------------------------------------------------------\nRan 1 test in 0.003s\n\nOK\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=0>"
},
"metadata": {},
"execution_count": 14
}
]
},
{
"metadata": {
"collapsed": true
},
"cell_type": "markdown",
"source": "`to_roman()`関数は「既知の値」のテストケースに通った。\n\nこのテストはありうるケースすべてを試しているわけではないが、この関数を多様な入力値、例えば、一文字のローマ数字に対応するすべての数、最大の数(3999)、最も長いローマ数字に対応する数(3888)などでテストしている。\n\nだから、この関数は適切な入力値ならどれでもうまく処理できると考えても差し支えないだろう。\nじゃあ「不適切な値」を入力したらどうなるのか。"
},
{
"metadata": {
"collapsed": true
},
"cell_type": "markdown",
"source": "## “Halt And Catch Fire”"
},
{
"metadata": {
"collapsed": true
},
"cell_type": "markdown",
"source": "適切な入力を与えて成功するかをテストするだけでは十分ではなく、\n適切でない入力を与えられた時に失敗することも検証しなくてはならない。\nそれもどんな失敗でも良いというわけではなく、狙った通りに失敗しなくてはならない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "明らかにこれは意図していない戻り値.\nそもそも、ちゃんとしたローマ数字ですらない!\n実を言うと、ここにある数はすべて入力値の制限範囲を越えているのだが、それでも関数はとりあえず戻り値をでっちあげている。\n\nこっそり不適当な値を返すというのはものすごーく悪いことだ。\nどうせ落ちるプログラムなら、早いうちに騒々しく落ちてくれた方がずっと良い。\n言い習わされているように「**Halt and catch fire**」(中断の後、発火せよ)というやつだ。\nPythonでは、例外の送出が **Halt and Catch Fire** の役目を果たす。"
},
{
"metadata": {
"scrolled": true,
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(4000)",
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'MMMM'"
},
"metadata": {},
"execution_count": 15
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(5000)",
"execution_count": 16,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'MMMMM'"
},
"metadata": {},
"execution_count": 16
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(9000)",
"execution_count": 17,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'MMMMMMMMM'"
},
"metadata": {},
"execution_count": 17
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "考えるべき問題は「どうやったらこれをテストできる条件として表せられるのだろう?」ということ。取っ掛かりとして、まず、:\n\n`to_roman()`関数は、3999より大きい整数を与えられたら `OutOfRangeError` を送出しなければならない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "前のテストケースと同じように、`unittest.TestCase` を継承したクラスを作る。\n一つのクラスに複数のテストを入れてもいいのだが、\nここでは新しいクラスを作ることにする。\nこのテストは先ほどのテストとは性質が異なったもの。\n\n**適切な入力値に対するテストを一つのクラスにまとめて、\n不適切な入力値に対するテストはまた別のクラスにまとめる**。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`unittest.TestCase`クラスには、\n`assertRaises`メソッドが用意されているが、これは次のような引数をとるもの。\nすなわち、送出されるべき例外、テスト対象の関数、そして関数に渡す引数\n(テスト対象の関数が複数の引数をとる場合には、それらの引数を順に並べてassertRaisesに渡せばいい。そうすれば、そのまま関数に渡してくれる)。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "def to_roman(n):\n '''convert integer to Roman numeral'''\n \n result = ''\n for numeral, integer in roman_numeral_map:\n while n >= integer:\n result += numeral\n n -= integer\n \n return result\n",
"execution_count": 18,
"outputs": []
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class ToRomanBadInput(unittest.TestCase):\n \n def test_too_large(self):\n '''to_roman should fail with large input'''\n self.assertRaises(OutOfRangeError, to_roman, 4000)\n \n",
"execution_count": 19,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`to_roman()` を直接呼び出して、特定の例外を送出しているかどうかを\n(`try...except`ブロックを使って)自ら調べなくても、\n`assertRaises`メソッドがこの処理を全部カプセル化してくれている。\nだから、どんな例外が送出されるべきなのか(roman2.OutOfRangeError)と、対象となる関数(`to_roman()`)、そして関数がとる引数(4000)を渡すだけでよい。\n\n後は、`assertRaises`メソッドが`to_roman()` を呼び出して、\n`OutOfRangeError` が送出されるかどうかをチェックしてくれる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) ",
"execution_count": 20,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\nE\n======================================================================\nERROR: test_too_large (__main__.ToRomanBadInput)\nto_roman should fail with large input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-19-4ae99e2f06fb>\", line 5, in test_too_large\n self.assertRaises(OutOfRangeError, to_roman, 4000)\nNameError: name 'OutOfRangeError' is not defined\n\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nFAILED (errors=1)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=1 failures=0>"
},
"metadata": {},
"execution_count": 20
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "「Fail」ではなく、代わりに「Error」が返ってくる。\nこれは微妙な差だが、違いは大きい。\n\n実は、ユニットテストには\n- Pass\n- Fail\n- Error\n\nの三つの戻り値がある。\n\n- Pass:というのはもちろん、テストをパスしたことを意味する — 関数が期待通り動いてくれたということだ。\n- 「Fail」:一つ前のテストケースが(そのためのコードを書き上げる直前まで)返していたものだ — つまり、コードを実行したが、予期した結果が出なかった場合を表す。\n- 「Error」: というのは、そもそもコードを正しく実行できなかったことを示している。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストしたモジュールの中に `OutOfRangeError` という名前の例外が存在しなかった。\n思い出して欲しいのだが、この例外は範囲外の入力値が渡された時に送出されるべき例外として`assertRaises()`メソッドに渡したものだった。\nしかし、そもそもこの例外は存在しなかったので、`assertRaises()`メソッドの呼び出しが失敗してしまったのだ。\nここでは結局、`to_roman()`関数がテストされることはなかった。そこに行き着きさえしなかった。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この問題を解決するためには、`OutOfRangeError`例外を定義する必要がある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "例外とはクラスでできている。\n「`Out of Range`」エラーは、`Value Error` の一種だと言える \n— 引数の値が受け取ることのできる範囲を越えている。\nだから、この例外は組み込みの`ValueError`例外を継承している。\nこれは絶対に必要というわけではない(基底クラスのExceptionを継承してもいい)"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class OutOfRangeError(ValueError):\n pass\n",
"execution_count": 21,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) ",
"execution_count": 22,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\nF\n======================================================================\nFAIL: test_too_large (__main__.ToRomanBadInput)\nto_roman should fail with large input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-19-4ae99e2f06fb>\", line 5, in test_too_large\n self.assertRaises(OutOfRangeError, to_roman, 4000)\nAssertionError: OutOfRangeError not raised by to_roman\n\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nFAILED (failures=1)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=1>"
},
"metadata": {},
"execution_count": 22
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`Error` が返されることもなく、その代わりにテストは失敗(`Failure`)している。\nこれは、`assertRaises()`メソッドが正しく呼び出され、\n実際に`to_roman()`関数がこのユニットテストフレームワークにテストされたということを意味している。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これで、このテストをパスするためのコードを書くことができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "与えられた入力値(n)が3999より大きければ、\n`OutOfRangeError`例外を送出する。\n\nちなみに、このユニットテストは、例外と一緒に出力されるエラー文字列については何もチェックしていないが、これ用のテストはまた別に書くことができる\n(ただし、文字列の多言語化の問題に注意すること。\nこの問題はユーザーの言語や環境に依存する)。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "class OutOfRangeError(ValueError):\n pass \n\n\ndef to_roman(n):\n '''convert integer to Roman numeral'''\n if n > 3999:\n raise OutOfRangeError('number out of range (must be less than 4000)')\n \n result = ''\n for numeral, integer in roman_numeral_map:\n while n >= integer:\n result += numeral\n n -= integer\n return result\n",
"execution_count": 23,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これでテストをパスするようになっただろうか?"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) ",
"execution_count": 24,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n.\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nOK\n.\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nOK\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=0>"
},
"metadata": {},
"execution_count": 24
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストを二つともパスした。\nテストとコーディングの間を行ったり来たりしながら、繰り返し作業したので、\nテストが「Fail」から「Pass」になったのは、さっき書いた二行のコードのおかげだと確信できる。\nこの種の確信を得るのは大変だが、そのコードが使われる年月を総じれば、\nきっとその元はとれる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## もっと中断させて、もっと発火させる"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ローマ数字は0や負の数を表すことはできない"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(0)",
"execution_count": 25,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "''"
},
"metadata": {},
"execution_count": 25
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(-1)",
"execution_count": 26,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "''"
},
"metadata": {},
"execution_count": 26
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "それぞれの条件に対するテストを付け加える。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "新しいテストの`test_zero()`メソッド:\n\n`unittest.TestCase` の中に定められている`assertRaises()` メソッドを用いて、\n`to_roman()` を0を引数として呼び出し、\n適切な例外(`OutOfRangeError`)が送出されるかどうかを確認している。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`test_negative()`メソッド:\n\n`-1` を`to_roman()` に渡しているというだけの違いしかない。\nこの新しいテストのいずれかにおいてOutOfRangeErrorが送出されなかった場合(その原因としては、関数が実際の値を返したか別の例外を返したかのどちらか)には、\nテストは失敗したものとみなされる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "class ToRomanBadInput(unittest.TestCase):\n def test_too_large(self):\n '''to_roman should fail with large input'''\n self.assertRaises(OutOfRangeError, to_roman, 4000)\n \n def test_zero(self):\n '''to_roman should fail with 0 input'''\n self.assertRaises(OutOfRangeError, to_roman, 0)\n \n def test_negative(self):\n '''to_roman should fail with negative input'''\n self.assertRaises(OutOfRangeError, to_roman, -1)\n \n",
"execution_count": 27,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストが失敗することを確かめよう:"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) ",
"execution_count": 28,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n.\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nOK\nF.F\n======================================================================\nFAIL: test_negative (__main__.ToRomanBadInput)\nto_roman should fail with negative input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-27-1ea3a47efc08>\", line 12, in test_negative\n self.assertRaises(OutOfRangeError, to_roman, -1)\nAssertionError: OutOfRangeError not raised by to_roman\n\n======================================================================\nFAIL: test_zero (__main__.ToRomanBadInput)\nto_roman should fail with 0 input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-27-1ea3a47efc08>\", line 8, in test_zero\n self.assertRaises(OutOfRangeError, to_roman, 0)\nAssertionError: OutOfRangeError not raised by to_roman\n\n----------------------------------------------------------------------\nRan 3 tests in 0.005s\n\nFAILED (failures=2)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=3 errors=0 failures=2>"
},
"metadata": {},
"execution_count": 28
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "予想通りどちらのテストも失敗している。さて、今度はコードに戻って、どうすればテストをパスできるようになるのかを考えてみよう。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この部分ではPython流のショートカットが上手に使われていて、\n複数の比較演算子が同時に評価されている。\n意味的には\n`if not ((0 < n) and (n < 4000))` と同じだが、\nこちらの方が読みやすい。\nこの一行のコードで、大きすぎる数、負の数、ゼロの三種類の入力値すべてが補足される。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "条件を変えたら、人が読む用のエラー文字列も修正するのを忘れないように。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "def to_roman(n):\n '''convert integer to Roman numeral'''\n if not (0 < n < 4000):\n raise OutOfRangeError('number out of range (must be 1..3999)')\n \n result = ''\n for numeral, integer in roman_numeral_map:\n while n >= integer:\n result += numeral\n n -= integer\n return result",
"execution_count": 29,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) ",
"execution_count": 30,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n.\n----------------------------------------------------------------------\nRan 1 test in 0.003s\n\nOK\n...\n----------------------------------------------------------------------\nRan 3 tests in 0.004s\n\nOK\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=3 errors=0 failures=0>"
},
"metadata": {},
"execution_count": 30
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## さらにもう一つ……"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "数字をローマ数字に変換する際の機能要件にはもう一つ、整数以外の数の扱いがある。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(0.5) ",
"execution_count": 31,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "''"
},
"metadata": {},
"execution_count": 31
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "値をでっちあげて返してしまっている。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "to_roman(1.0)",
"execution_count": 32,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'I'"
},
"metadata": {},
"execution_count": 32
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "整数でない数をテストするのは難しいことではない。\nまず、NotIntegerError例外を定義する。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class NotIntegerError(ValueError): \n pass",
"execution_count": 33,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "次に、`NotIntegerError`例外が送出されるかどうかをチェックするテストケースを書く。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class ToRomanBadInput(unittest.TestCase):\n def test_too_large(self):\n '''to_roman should fail with large input'''\n self.assertRaises(OutOfRangeError, to_roman, 4000)\n \n def test_zero(self):\n '''to_roman should fail with 0 input'''\n self.assertRaises(OutOfRangeError, to_roman, 0)\n \n def test_negative(self):\n '''to_roman should fail with negative input'''\n self.assertRaises(OutOfRangeError, to_roman, -1)\n \n def test_non_integer(self):\n '''to_roman should fail with non-integer input'''\n self.assertRaises(NotIntegerError, to_roman, 0.5)\n \n",
"execution_count": 34,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストがちゃんと失敗するか確かめる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) ",
"execution_count": 35,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n.\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nOK\n.F..\n======================================================================\nFAIL: test_non_integer (__main__.ToRomanBadInput)\nto_roman should fail with non-integer input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-34-7868efa3e185>\", line 16, in test_non_integer\n self.assertRaises(NotIntegerError, to_roman, 0.5)\nAssertionError: NotIntegerError not raised by to_roman\n\n----------------------------------------------------------------------\nRan 4 tests in 0.006s\n\nFAILED (failures=1)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=4 errors=0 failures=1>"
},
"metadata": {},
"execution_count": 35
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストをパスするようなコードを書く。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "組み込みの `isinstance()`関数は、\n変数が特定の型(厳密に言えば、ここにはその型を継承した型も含む)かどうかを調べる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "引数のnが `int` でなかったら、さっき新しく作った\n `NotIntegerError` を送出する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "def to_roman(n):\n '''convert integer to Roman numeral'''\n \n if not (0 < n < 4000):\n raise OutOfRangeError('number out of range (must be 1..3999)')\n if not isinstance(n, int):\n raise NotIntegerError('non-integers can not be converted')\n \n result = ''\n for numeral, integer in roman_numeral_map:\n while n >= integer:\n result += numeral\n n -= integer\n return result\n",
"execution_count": 36,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "最後に、このコードで本当にテストにパスするようになったかをチェックする。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) ",
"execution_count": 37,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n.\n----------------------------------------------------------------------\nRan 1 test in 0.003s\n\nOK\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.007s\n\nOK\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=4 errors=0 failures=0>"
},
"metadata": {},
"execution_count": 37
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## すばらしき対称性"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ローマ数字の文字列を整数に直すのは、整数をローマ数字に直すことよりも難しいように見える。\n\nもちろん、ここには有効なローマ数字かどうかのチェックの問題が存在する。\nある整数が0より大きいかどうかをチェックするのは簡単だが、\nある文字列が有効なローマ数字かどうかをチェックするのは少し難しいことだ。\nしかし、私たちは既にローマ数字をチェックする正規表現を作成している。\nだから、この部分はもう完成している。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列をどう変換するかという問題自体はまだ残っているが、すぐ後で見るように、\nローマ数字と整数値との対応関係を詰め込んだデータ構造があるおかげで、`from_roman()`関数のコードの核は `to_roman()`関数と同じくらい単純なものになる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "最初はテスト。\nここでは正確に変換されているかどうかを抜き取り検査する「既知の値」のテストが必要だろう。\nテストスイートには既に既知の値の対応表が入っているので、こいつを再利用する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import unittest\n\nclass KnownValues(unittest.TestCase):\n known_values = ( (1, 'I'),\n (2, 'II'),\n (3, 'III'),\n (4, 'IV'),\n (5, 'V'),\n (6, 'VI'),\n (7, 'VII'),\n (8, 'VIII'),\n (9, 'IX'),\n (10, 'X'),\n (50, 'L'),\n (100, 'C'),\n (500, 'D'),\n (1000, 'M'),\n (31, 'XXXI'),\n (148, 'CXLVIII'),\n (294, 'CCXCIV'),\n (312, 'CCCXII'),\n (421, 'CDXXI'),\n (528, 'DXXVIII'),\n (621, 'DCXXI'),\n (782, 'DCCLXXXII'),\n (870, 'DCCCLXX'),\n (941, 'CMXLI'),\n (1043, 'MXLIII'),\n (1110, 'MCX'),\n (1226, 'MCCXXVI'),\n (1301, 'MCCCI'),\n (1485, 'MCDLXXXV'),\n (1509, 'MDIX'),\n (1607, 'MDCVII'),\n (1754, 'MDCCLIV'),\n (1832, 'MDCCCXXXII'),\n (1993, 'MCMXCIII'),\n (2074, 'MMLXXIV'),\n (2152, 'MMCLII'),\n (2212, 'MMCCXII'),\n (2343, 'MMCCCXLIII'),\n (2499, 'MMCDXCIX'),\n (2574, 'MMDLXXIV'),\n (2646, 'MMDCXLVI'),\n (2723, 'MMDCCXXIII'),\n (2892, 'MMDCCCXCII'),\n (2975, 'MMCMLXXV'),\n (3051, 'MMMLI'),\n (3185, 'MMMCLXXXV'),\n (3250, 'MMMCCL'),\n (3313, 'MMMCCCXIII'),\n (3408, 'MMMCDVIII'),\n (3501, 'MMMDI'),\n (3610, 'MMMDCX'),\n (3743, 'MMMDCCXLIII'),\n (3844, 'MMMDCCCXLIV'),\n (3888, 'MMMDCCCLXXXVIII'),\n (3940, 'MMMCMXL'),\n (3999, 'MMMCMXCIX')\n )\n\n def test_to_roman_known_values(self):\n '''to_roman should give known result with known input'''\n \n for integer, numeral in self.known_values:\n result = to_roman(integer)\n self.assertEqual(numeral, result)\n \n \n def test_from_roman_known_values(self):\n '''from_roman should give known result with known input'''\n \n for integer, numeral in self.known_values:\n result = from_roman(numeral)\n self.assertEqual(integer, result)\n \n \n",
"execution_count": 38,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ここにはすばらしい対称性がある。\n\n`to_roman()`関数と `from_roman()`関数は互いを逆にしたもので、\n前者は整数を特定の形式の文字列に変換し、後者は特定の形式の文字列を整数に変換する。\n\n理論的には、数を「往復」させることができなくてはならない。\nつまり、`to_roman()`関数に渡して文字列に直し、\n\n続いてその文字列を`from_roman()`関数に渡して整数に直した場合に、\n最初の数が戻ってこなくてはならない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "対称性を用いて、`1..3999` のすべての値に対して `to_roman()` を呼び出し、\nさらに `to_roman()` で変換を施して、\n出力された値が元の入力値と同じかをチェックするテストケースを作ることができる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class RoundtripCheck(unittest.TestCase):\n \n def test_roundtrip(self):\n '''from_roman(to_roman(n))==n for all n'''\n \n for integer in range(1, 4000):\n numeral = to_roman(integer)\n result = from_roman(numeral)\n self.assertEqual(integer, result)\n \n \n",
"execution_count": 39,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`from_roman()` をまったく定義していないので、実行してもエラーが送出されるだけ。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test) ",
"execution_count": 40,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\nE.\n======================================================================\nERROR: test_from_roman_known_values (__main__.KnownValues)\nfrom_roman should give known result with known input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-38-fbe19e69e68a>\", line 74, in test_from_roman_known_values\n result = from_roman(numeral)\nNameError: name 'from_roman' is not defined\n\n----------------------------------------------------------------------\nRan 2 tests in 0.004s\n\nFAILED (errors=1)\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.006s\n\nOK\nE\n======================================================================\nERROR: test_roundtrip (__main__.RoundtripCheck)\nfrom_roman(to_roman(n))==n for all n\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-39-15de0fba6e80>\", line 8, in test_roundtrip\n result = from_roman(numeral)\nNameError: name 'from_roman' is not defined\n\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nFAILED (errors=1)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=1 failures=0>"
},
"metadata": {},
"execution_count": 40
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "とりあえず空の関数を定義すれば、この問題は解決する。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "def from_roman(s):\n '''convert Roman numeral to integer'''\n",
"execution_count": 41,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この関数はドキュメンテーション文字列のみで定義されているのだ。これはPythonでは正式に認められていることだ。実際に、これを推奨しているプログラマもいる。「スタブするな、ドキュメントせよ!」)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このテストケースはこれで実際に失敗するようになったはずだ。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test)",
"execution_count": 42,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\nF.\n======================================================================\nFAIL: test_from_roman_known_values (__main__.KnownValues)\nfrom_roman should give known result with known input\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-38-fbe19e69e68a>\", line 75, in test_from_roman_known_values\n self.assertEqual(integer, result)\nAssertionError: 1 != None\n\n----------------------------------------------------------------------\nRan 2 tests in 0.007s\n\nFAILED (failures=1)\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.005s\n\nOK\nF\n======================================================================\nFAIL: test_roundtrip (__main__.RoundtripCheck)\nfrom_roman(to_roman(n))==n for all n\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-39-15de0fba6e80>\", line 9, in test_roundtrip\n self.assertEqual(integer, result)\nAssertionError: 1 != None\n\n----------------------------------------------------------------------\nRan 1 test in 0.002s\n\nFAILED (failures=1)\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=1>"
},
"metadata": {},
"execution_count": 42
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "それではfrom_roman()関数を書く。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "def from_roman(s):\n \"\"\"convert Roman numeral to integer\"\"\"\n \n result = 0\n index = 0\n for numeral, integer in roman_numeral_map:\n # M\n # 1000:M\n # s[0:0+1]\n while s[index:index+len(numeral)] == numeral:\n result += integer\n index += len(numeral)\n return result",
"execution_count": 43,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\nwhile s[index:index+len(numeral)] == numeral:\n```\n\nこの部分のパターンは `to_roman()` と同じで、\nローマ数字のデータ構造(タプルからなるタプル)をイテレートしていっている。\n\nただし、前のコードではできる限り大きな整数値にマッチするようにしていたが、ここではできる限り「最大の」ローマ数字の文字列にマッチするようにしている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`from_roman()`関数がどのように動いているのかよく分からなかったら、\n`print`文をwhileループの末尾につけてみるといい:"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "def from_roman(s):\n \"\"\"convert Roman numeral to integer\"\"\"\n \n result = 0\n index = 0\n for numeral, integer in roman_numeral_map:\n while s[index:index+len(numeral)] == numeral:\n result += integer\n index += len(numeral)\n print('found', numeral, 'of length', len(numeral), ', adding', integer)\n \n return result\n",
"execution_count": 44,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "from_roman('MCMLXXII')",
"execution_count": 45,
"outputs": [
{
"output_type": "stream",
"text": "found M of length 1 , adding 1000\nfound CM of length 2 , adding 900\nfound L of length 1 , adding 50\nfound X of length 1 , adding 10\nfound X of length 1 , adding 10\nfound I of length 1 , adding 1\nfound I of length 1 , adding 1\n",
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "1972"
},
"metadata": {},
"execution_count": 45
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テストをもう一度実行する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "def from_roman(s):\n \"\"\"convert Roman numeral to integer\"\"\"\n \n result = 0\n index = 0\n for numeral, integer in roman_numeral_map:\n while s[index:index+len(numeral)] == numeral:\n result += integer\n index += len(numeral)\n # print('found', numeral, 'of length', len(numeral), ', adding', integer)\n return result\n\n%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test)",
"execution_count": 46,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n..\n----------------------------------------------------------------------\nRan 2 tests in 0.006s\n\nOK\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.007s\n\nOK\n.\n----------------------------------------------------------------------\nRan 1 test in 0.140s\n\nOK\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=0>"
},
"metadata": {},
"execution_count": 46
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ここから興味深いことが二つ分かる。\n- `from_roman()` は適切な入力値に関しては(少なくとも全ての既知の値については)うまく動くということ。\n\n- この関数が「往復」テストもパスしている。\n既知の値に関するテスト結果と合わせると、to_roman()とfrom_roman()は適切な値ならどんなものについても正しく処理できると考えてもよさそうだ。\n\n(ただし絶対ではない。\n理論上は、特定の入力値を間違ったローマ数字に変換するバグがto_roman()に存在していて、かつ `from_roman()` にも対応するバグが存在し、\n`to_roman()` が誤って生成したローマ数字を元の入力値に誤変換しているということもありうる。アプリケーションや要件によってはこの可能性が問題になるかもしれないが、\nその場合には問題が解決するまでテストケースをより包括的なものにしていけばよい)。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 不適切な入力値"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これで `from_roman()` は適切な入力値をうまく処理できるようになった。\nそれでは最後のパズルのピース — 不適切な入力値の処理の問題—に取り組むとしようか。\n\nこの問題は結局のところ、\n文字列を調べて有効なローマ数字かどうかを判断する方法を見つけ出すことに帰着する。これは `to_roman()`関数の数字の入力値をチェックする処理よりも本質的に難しいものだ。\nしかし、私たちには意のままに使える強力なツールがある。\nそう、正規表現だ(正規表現になじみがないなら、この折に正規表現の章を読んでおいて欲しい)。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "M、 D、 C、 L、 X、 V、Iの文字を使ってローマ数字を組み立てる場合には、いくつかの単純なルールがある。ルールを見直してみよう:\n\n- 時に文字は足し算のように働く。Iは1、IIは2、そしてIIIは3だ。VIは6で(文字通り「5と1」だ)、VIIは7、VIIIは8。\n\n- 10の文字(I、X、C、M)は三回まで繰り返せる。4については、次の5の文字から引いて表さなければならない。つまり、4をIIIIと表すことはできず、代わりにIVとしなければならないのだ(「5引く1」)。40はXLと書かれ(「50引く10」)、41はXLI、42はXLII、43はXLIII、そして44はXLIVと表せられる(「50引く10と5引く1」)。\n\n- 時に文字は……足し算とは逆の役割を果たす。ある文字を他の文字の前に置くと、後の文字から値を引いたことになるのだ。例えば、9を作るには、次の10の数から引き算をしなければならない。つまり、8はVIIIだが、9はIXとなり(「10引く1」)、VIIIIとは書けないのだ(なぜならIの文字を4回繰り返すことはできないから)。90はXC、900はCMとなる。\n\n- 5の文字は繰り返すことができない。10は必ずXと表し、VVとすることはできない。100もCであって、LLとはならない。\n\n- ローマ数字は左から右に読むので、文字の並べ方が非常に重要になる。DCは600だが、CDはそれとは全く異なる数を表すのだ(400、「500引く100」)。また、CIは101だがICは適切なローマ数字ですらない(1を直接100から引くことはできないからだ。代わりにXCIXと書かなくてはならない、「100引く10、加えて10引く1」)。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "使えそうなテストとしては、ある数字が繰り返し使われすぎているような文字列を`from_roman()` に渡した場合に例外が送出されるかどうか確かめるというのがあるだろう。\nどれぐらい繰り返されていれば多すぎると言えるのかは、その数字によって異なる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class ToRomanBadInput(unittest.TestCase):\n def test_too_large(self):\n '''to_roman should fail with large input'''\n self.assertRaises(OutOfRangeError, to_roman, 4000)\n \n def test_zero(self):\n '''to_roman should fail with 0 input'''\n self.assertRaises(OutOfRangeError, to_roman, 0)\n \n def test_negative(self):\n '''to_roman should fail with negative input'''\n self.assertRaises(OutOfRangeError, to_roman, -1)\n \n def test_non_integer(self):\n '''to_roman should fail with non-integer input'''\n self.assertRaises(NotIntegerError, to_roman, 0.5)\n\n def test_too_many_repeated_numerals(self):\n '''from_roman should fail with too many repeated numerals'''\n\n for s in ('MMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):\n self.assertRaises(InvalidRomanNumeralError, roman6.from_roman, s)\n \n \n",
"execution_count": 47,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "他にも、繰り返すことのできない特定のパターンをチェックするのもテストとして有用だろう。例えば、IXは9だがIXIXはローマ数字として有効ではない。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class ToRomanBadInput(unittest.TestCase):\n def test_too_large(self):\n '''to_roman should fail with large input'''\n self.assertRaises(OutOfRangeError, to_roman, 4000)\n \n def test_zero(self):\n '''to_roman should fail with 0 input'''\n self.assertRaises(OutOfRangeError, to_roman, 0)\n \n def test_negative(self):\n '''to_roman should fail with negative input'''\n self.assertRaises(OutOfRangeError, to_roman, -1)\n \n def test_non_integer(self):\n '''to_roman should fail with non-integer input'''\n self.assertRaises(NotIntegerError, to_roman, 0.5)\n\n def test_too_many_repeated_numerals(self):\n '''from_roman should fail with too many repeated numerals'''\n\n for s in ('MMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):\n self.assertRaises(InvalidRomanNumeralError, roman6.from_roman, s)\n \n def test_repeated_pairs(self):\n '''from_roman should fail with repeated pairs of numerals'''\n \n for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):\n self.assertRaises(InvalidRomanNumeralError, roman6.from_roman, s)\n \n \n",
"execution_count": 48,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "三つ目のテストでは、数字が正しい順番、つまり大きいものから小さいものへと並んでいるかでチェックしよう。\n\n例えば、CLは150を表すが、LCは有効な数字ではない。\n50を表す数字が100を表す数字の前にくることはないからだ。このテストには不適切な数字が前に来ているパターンをランダムに選んで入れるとしよう。Mの前にIがあるとか、Xの前にVがあるとかいう場合だ。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class ToRomanBadInput(unittest.TestCase):\n def test_too_large(self):\n '''to_roman should fail with large input'''\n self.assertRaises(OutOfRangeError, to_roman, 4000)\n \n def test_zero(self):\n '''to_roman should fail with 0 input'''\n self.assertRaises(OutOfRangeError, to_roman, 0)\n \n def test_negative(self):\n '''to_roman should fail with negative input'''\n self.assertRaises(OutOfRangeError, to_roman, -1)\n \n def test_non_integer(self):\n '''to_roman should fail with non-integer input'''\n self.assertRaises(NotIntegerError, to_roman, 0.5)\n\n def test_too_many_repeated_numerals(self):\n '''from_roman should fail with too many repeated numerals'''\n\n for s in ('MMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n def test_repeated_pairs(self):\n '''from_roman should fail with repeated pairs of numerals'''\n \n for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n def test_malformed_antecedents(self):\n '''from_roman should fail with malformed antecedents'''\n \n for s in ('IIMXCC', 'VX', 'DCM', 'CMM', 'IXIV', 'MCMC', 'XCX', 'IVI',\n 'LM', 'LD', 'LC'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n",
"execution_count": 49,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これら三つのテストはすべてfrom_roman()がInvalidRomanNumeralErrorという新しい例外を送出することを前提としているが、この例外はまだ定義されていない。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "class InvalidRomanNumeralError(ValueError): \n pass\n",
"execution_count": 50,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test)",
"execution_count": 51,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n..\n----------------------------------------------------------------------\nRan 2 tests in 0.004s\n\nOK\nF..F.F.\n======================================================================\nFAIL: test_malformed_antecedents (__main__.ToRomanBadInput)\nfrom_roman should fail with malformed antecedents\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-49-096381ac8b39>\", line 35, in test_malformed_antecedents\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\nAssertionError: InvalidRomanNumeralError not raised by from_roman\n\n======================================================================\nFAIL: test_repeated_pairs (__main__.ToRomanBadInput)\nfrom_roman should fail with repeated pairs of numerals\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-49-096381ac8b39>\", line 28, in test_repeated_pairs\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\nAssertionError: InvalidRomanNumeralError not raised by from_roman\n\n======================================================================\nFAIL: test_too_many_repeated_numerals (__main__.ToRomanBadInput)\nfrom_roman should fail with too many repeated numerals\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-49-096381ac8b39>\", line 22, in test_too_many_repeated_numerals\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\nAssertionError: InvalidRomanNumeralError not raised by from_roman\n\n----------------------------------------------------------------------\nRan 7 tests in 0.011s\n\nFAILED (failures=3)\n.\n----------------------------------------------------------------------\nRan 1 test in 0.118s\n\nOK\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=0>"
},
"metadata": {},
"execution_count": 51
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "後は有効なローマ数字かをチェックする正規表現をfrom_roman()関数に組み込めばいい。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "import re\n\nroman_numeral_pattern = re.compile('''\n ^ # beginning of string\n M{0,3} # thousands - 0 to 3 Ms\n (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs),\n # or 500-800 (D, followed by 0 to 3 Cs)\n (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs),\n # or 50-80 (L, followed by 0 to 3 Xs)\n (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is),\n # or 5-8 (V, followed by 0 to 3 Is)\n $ # end of string\n ''', re.VERBOSE)\n\ndef from_roman(s):\n '''convert Roman numeral to integer'''\n \n if not roman_numeral_pattern.search(s):\n raise InvalidRomanNumeralError('Invalid Roman numeral: {0}'.format(s))\n\n result = 0\n index = 0\n for numeral, integer in roman_numeral_map:\n while s[index : index + len(numeral)] == numeral:\n result += integer\n index += len(numeral)\n return result\n",
"execution_count": 52,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "再びテストを実行する"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(ToRomanBadInput)\nunittest.TextTestRunner().run(test) \ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test)",
"execution_count": 53,
"outputs": [
{
"output_type": "stream",
"text": "No traceback available to show.\n..\n----------------------------------------------------------------------\nRan 2 tests in 0.007s\n\nOK\n.......\n----------------------------------------------------------------------\nRan 7 tests in 0.010s\n\nOK\n.\n----------------------------------------------------------------------\nRan 1 test in 0.174s\n\nOK\n",
"name": "stderr"
},
{
"output_type": "execute_result",
"data": {
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=0>"
},
"metadata": {},
"execution_count": 53
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 参考リンク"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- [Dive Into Python3 9章 ユニットテスト](http://diveintopython3-ja.rdy.jp/unit-testing.html)\n- [unittest — ユニットテストフレームワーク](http://docs.python.jp/3/library/unittest.html)"
}
],
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py",
"name": "python",
"version": "3.5.1",
"mimetype": "text/x-python"
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"toc": {
"toc_number_sections": true,
"toc_threshold": "6",
"toc_cell": true,
"toc_window_display": false
},
"gist": {
"id": "1833320ab55ae5ea660ce0c635483d26",
"data": {
"description": "Dive Into Python3 9章メモ ユニットテスト",
"public": true
}
},
"_draft": {
"nbviewer_url": "https://gist.github.com/1833320ab55ae5ea660ce0c635483d26"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment