Created
April 4, 2016 10:54
-
-
Save Cartman0/0c0af20eb95236da4da9547258fe2bb3 to your computer and use it in GitHub Desktop.
Dive Into Python3 10章メモ (リファクタリング)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"metadata": { | |
"toc": "true" | |
}, | |
"cell_type": "markdown", | |
"source": "# Table of Contents\n <p><div class=\"lev1\"><a href=\"#10章-リファクタリング-1\"><span class=\"toc-item-num\">1 </span>10章 リファクタリング</a></div><div class=\"lev2\"><a href=\"#飛び込む-1.1\"><span class=\"toc-item-num\">1.1 </span>飛び込む</a></div><div class=\"lev2\"><a href=\"#要件の変更に対処する-1.2\"><span class=\"toc-item-num\">1.2 </span>要件の変更に対処する</a></div><div class=\"lev2\"><a href=\"#リファクタリング-1.3\"><span class=\"toc-item-num\">1.3 </span>リファクタリング</a></div><div class=\"lev2\"><a href=\"#まとめ-1.4\"><span class=\"toc-item-num\">1.4 </span>まとめ</a></div><div class=\"lev2\"><a href=\"#参考リンク-1.5\"><span class=\"toc-item-num\">1.5 </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)\n- [Dive Into Python3 9章メモ(ユニットテスト)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/1833320ab55ae5ea660ce0c635483d26/raw/46034833206366c8011594cbea2efce90168d54b/DiveIntoPython3_09.ipynb?flush_cache=true)" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "# 10章 リファクタリング" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## 飛び込む" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "包括的なユニットテストを書いても、バグは出てくる。\n「バグ」とは一体何だろうか? バグとはまだ書かれていないテストケースになる。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": true | |
}, | |
"cell_type": "code", | |
"source": "import re\n\nroman_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\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": 1, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "これはバグ。\n空白文字列に対しては、有効なローマ数字となっていない他の文字列の場合と同じように、\n`InvalidRomanNumeralError`例外が送出されなくてはならない。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false, | |
"scrolled": true | |
}, | |
"cell_type": "code", | |
"source": "from_roman('')", | |
"execution_count": 2, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "0" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 2 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "バグを再現できたら、それを修正するのに先立って、パスしないようなテストケースを書かなければならない。こうしてバグをはっきりと示す。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false | |
}, | |
"cell_type": "code", | |
"source": "import unittest\n\nclass InvalidRomanNumeralError(ValueError): \n pass\n\n\nclass FromRomanBadInput(unittest.TestCase):\n \n def test_too_many_repeated_numerals(self):\n '''from_roman should fail with too many repeated numerals'''\n for s in ('MMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n \n def test_repeated_pairs(self):\n '''from_roman should fail with repeated pairs of numerals'''\n for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n \n def test_malformed_antecedents(self):\n '''from_roman should fail with malformed antecedents'''\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 \n # 新しく追加\n def testBlank(self):\n '''from_roman should fail with blank string'''\n self.assertRaises(InvalidRomanNumeralError, from_roman, '')\n ", | |
"execution_count": 3, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "すなわち、from_roman()を空白文字列とともに呼び出し、\n`InvalidRomanNumeralError`例外が送出されるかどうかを確認する。\n難しいのはバグを見つけ出す段階であって、一度分かってしまえば、そのバグをテストするのはごく簡単。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false | |
}, | |
"cell_type": "code", | |
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(FromRomanBadInput)\nunittest.TextTestRunner().run(test) ", | |
"execution_count": 4, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"name": "stderr", | |
"text": "No traceback available to show.\nF...\n======================================================================\nFAIL: testBlank (__main__.FromRomanBadInput)\nfrom_roman should fail with blank string\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<ipython-input-3-f620bb1328bb>\", line 31, in testBlank\n self.assertRaises(InvalidRomanNumeralError, from_roman, '')\nAssertionError: InvalidRomanNumeralError not raised by from_roman\n\n----------------------------------------------------------------------\nRan 4 tests in 0.011s\n\nFAILED (failures=1)\n" | |
}, | |
{ | |
"data": { | |
"text/plain": "<unittest.runner.TextTestResult run=4 errors=0 failures=1>" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 4 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": true | |
}, | |
"cell_type": "markdown", | |
"source": "これでようやくこのバグを修正できる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "たった二行のコードを追加するだけで足りる。\n一行目で明示的に空白文字列をチェックし、二行目には`raise`文 をあてる。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": true | |
}, | |
"cell_type": "code", | |
"source": "class OutOfRangeError(ValueError):\n pass\n\nclass NotIntegerError(ValueError):\n pass\n\ndef 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": 5, | |
"outputs": [] | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": true, | |
"code_folding": [] | |
}, | |
"cell_type": "code", | |
"source": "roman_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 if not s:\n raise InvalidRomanNumeralError('Input can not be blank')\n if not re.search(roman_numeral_pattern, s):\n raise InvalidRomanNumeralError('Invalid Roman numeral: {}'.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": 6, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "```\n'Invalid Roman numeral: {}'.format(s)\n```\n\nPython 3.1からは、フォーマット指定子の中でインデクスを使用する場合に数字を省略できるようになっている。\nつまり、format()メソッドの最初の引数を参照する場合に、フォーマット指定子の{0}を使わなくとも、\n単純に `{}` とすればPython が自動で適当なインデクスを埋めてくれる。\n\nこれは引数がいくつあっても機能するもので、\n最初の{}は{0} に、次の{}は{1} というように解釈されていく。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false | |
}, | |
"cell_type": "code", | |
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(FromRomanBadInput)\nunittest.TextTestRunner().run(test)", | |
"execution_count": 7, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"name": "stderr", | |
"text": "No traceback available to show.\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.009s\n\nOK\n" | |
}, | |
{ | |
"data": { | |
"text/plain": "<unittest.runner.TextTestResult run=4 errors=0 failures=0>" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 7 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "空白文字列のテストケースをパスしていることから、このバグが修正されたと分かる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "このようにコーディングしても、別にバグが修正しやすくなるわけではない。\n(このバグのように)簡単なバグには簡単なテストケースで足りるが、\n複雑なバグには複雑なテストケースが必要となる。\n\nもしかしたら、テスト中心の開発環境だとバグを修正するのに長い時間がかかるように見えるかもしれない。\nまずもって、(テストケースを書いて)何がバグなのかをコードの中で明確に示してからバグを修正しなくてはならないし、\nしかもそこでテストケースをパスしなかったら、修正が間違っていたのか、\nそれともテストケース自体にバグがあるのかを調べなくてはならない。\n\nしかし、長い目で見れば、テストコードとそのテストを受けるコードの間を行ったり来たりすることは十分割に合うことだろう。\nこうすれば、バグが最初の一回で正しく修正されやすくなるし、\n新しいテストケースと一緒に他のすべてのテストケースを再実行することも簡単にできるので、\n新しいコードを加える際に古いコードを壊してしまうということが非常に少なくなる。\n今日のユニットテストは、明日の回帰テストとなる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## 要件の変更に対処する" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "どれだけ顧客から厳密な要件を引き出しても、要件というのは変わってしまう。\nそもそも、ほとんどの顧客は実際に見てみるまで、自分が何を求めているのかを理解しないもの。\n\nたとえ理解していたとしても、顧客はどういうものがあれば十分なのかをはっきりと伝えるのが上手ではない。\n仮に明確に伝えてきたとしても、どのみち次のリリースの時には別の機能も欲しがるようになっている。\nだから、要件の変更に合わせてテストケースをアップデートできるようにしておく。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "例えば、このローマ数字の変換関数が扱える値の範囲を拡張したいと思ったとする。\n\n普通なら、ローマ数字のどの文字も連続して4回以上繰り返すことはできないのだが、\n実のところローマ人は時に「4000を表すために、Mの文字を四個続けることができる」という例外を設けていた。\nこの変更を施せば、変換できる数の範囲を 1..3999 から 1..4999 に拡張できることになる。\nしかし、まず最初にテストケースに修正を加える必要がある。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "すでにタプルに入っている既知の値については何も変更を加えないが(これらはまだテストする意味のある値だ)、\n4000台の数をいくつか加える必要がある。\nここでは\n- 4000(最も短い数)、\n- 4500(二番目に短い数)、\n- 4888(最も長い数)、\n- 4999(最大の数)\n\nを加えてある。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": true | |
}, | |
"cell_type": "code", | |
"source": "class 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 (4000, 'MMMM'),\n (4500, 'MMMMD'),\n (4888, 'MMMMDCCCLXXXVIII'),\n (4999, 'MMMMCMXCIX')\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\n \n", | |
"execution_count": 8, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "「大きな入力値」の定義が変わっている。\nこのテストは `to_roman()` を4000と共に呼び出してエラーが出るかを確認するものだったが、\n4000-4999は有効な入力値となったので、引数の値を5000まで引き上げなくてはならない。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": 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, 5000)\n \n", | |
"execution_count": 9, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "「繰り返され過ぎている数字」の定義も変わっている。\nこのテストは `from_roman()` を'MMMM'とともに呼び出してエラーが出るかを確認するものだったが、\nMMMMは有効なローマ数字となったので、引数の値を'MMMMM'まで引き上げなくてはならない。," | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false | |
}, | |
"cell_type": "code", | |
"source": "class FromRomanBadInput(unittest.TestCase):\n \n def test_too_many_repeated_numerals(self):\n '''from_roman should fail with too many repeated numerals'''\n for s in ('MMMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n \n def test_repeated_pairs(self):\n '''from_roman should fail with repeated pairs of numerals'''\n for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n \n def test_malformed_antecedents(self):\n '''from_roman should fail with malformed antecedents'''\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 \n # 新しく追加\n def testBlank(self):\n '''from_roman should fail with blank string'''\n self.assertRaises(InvalidRomanNumeralError, from_roman, '')\n \n", | |
"execution_count": 10, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "この動作確認テストでは 1 から 3999 までのすべての数をループしていたが、\n値の範囲が拡張されたのに合わせて、このforループも4999 までの数をテストするように修正しなければならない。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": 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, 5000):\n numeral = to_roman(integer)\n result = from_roman(numeral)\n self.assertEqual(integer, result)\n \n \n", | |
"execution_count": 11, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`from_roman()` の既知の値のテストは'MMMM'に突き当たったところで失敗する。\n`from_roman()` がまだこのローマ数字を無効なものとしているからだ。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`to_roman()` の既知の値のテストは4000に突き当たったところで失敗する。\n`to_roman()` がまだこれを範囲外の数としているため。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "往復テスト( `RoundTripTest` )も4000に突き当たったところで失敗する。\n`to_roman()` がまだこれを範囲外の数としているため。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false, | |
"scrolled": false | |
}, | |
"cell_type": "code", | |
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test)\ntest = unittest.TestLoader().loadTestsFromTestCase(FromRomanBadInput)\nunittest.TextTestRunner().run(test)\ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test)", | |
"execution_count": 12, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"name": "stderr", | |
"text": "No traceback available to show.\nEE\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-8-051340391a19>\", line 76, in test_from_roman_known_values\n result = from_roman(numeral)\n File \"<ipython-input-6-0ddb24c33a8a>\", line 18, in from_roman\n raise InvalidRomanNumeralError('Invalid Roman numeral: {}'.format(s))\nInvalidRomanNumeralError: Invalid Roman numeral: MMMM\n\n======================================================================\nERROR: 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-8-051340391a19>\", line 68, in test_to_roman_known_values\n result = to_roman(integer)\n File \"<ipython-input-5-8a6a496128ad>\", line 11, in to_roman\n raise OutOfRangeError('number out of range (must be 1..3999)')\nOutOfRangeError: number out of range (must be 1..3999)\n\n----------------------------------------------------------------------\nRan 2 tests in 0.008s\n\nFAILED (errors=2)\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.009s\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-11-cce19637b0ef>\", line 7, in test_roundtrip\n numeral = to_roman(integer)\n File \"<ipython-input-5-8a6a496128ad>\", line 11, in to_roman\n raise OutOfRangeError('number out of range (must be 1..3999)')\nOutOfRangeError: number out of range (must be 1..3999)\n\n----------------------------------------------------------------------\nRan 1 test in 0.128s\n\nFAILED (errors=1)\n" | |
}, | |
{ | |
"data": { | |
"text/plain": "<unittest.runner.TextTestResult run=1 errors=1 failures=0>" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 12 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "これで新しい要件によって失敗するテストケースができ上がったので、これらのテストをパスするようにコードを修正する作業に移ることができる\n\n(ユニットテストをコーディングし始めた最初のうちは、テスト対象のコードが決してユニットテストの「先」にこないことに違和感を覚えるかもしれない。コードが追いついていないのに、\nまだやるべき作業があって、\nそしてコードがテストケースに追いついたら、\n即座にコーディングをやめる。)。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": true | |
}, | |
"cell_type": "code", | |
"source": "roman_numeral_pattern = re.compile('''\n ^ # beginning of string\n M{0,4} # thousands - 0 to 4 Ms MMMMまで許すよう変更\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 to_roman(n):\n '''convert integer to Roman numeral'''\n if not (0 < n < 5000): # 4999まで許容\n raise OutOfRangeError('number out of range (must be 1..4999)')\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\n# fromは変更しない\ndef from_roman(s):\n '''convert Roman numeral to integer'''\n if not s:\n raise InvalidRomanNumeralError('Input can not be blank')\n if not re.search(roman_numeral_pattern, s):\n raise InvalidRomanNumeralError('Invalid Roman numeral: {}'.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", | |
"execution_count": 13, | |
"outputs": [] | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false | |
}, | |
"cell_type": "code", | |
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test)\ntest = unittest.TestLoader().loadTestsFromTestCase(FromRomanBadInput)\nunittest.TextTestRunner().run(test)\ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test)", | |
"execution_count": 14, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"name": "stderr", | |
"text": "No traceback available to show.\n..\n----------------------------------------------------------------------\nRan 2 tests in 0.004s\n\nOK\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.006s\n\nOK\n.\n----------------------------------------------------------------------\nRan 1 test in 0.166s\n\nOK\n" | |
}, | |
{ | |
"data": { | |
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=0>" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 14 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "テストケースをすべてパスした。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## リファクタリング" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "ユニットテストの最も良い点は、容赦なく **リファクタリング** を施す自由を与えてくれることにある。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "**リファクタリング** とは、動作するコードを取り上げて、より良く動くようにしていくプロセスのこと。\n普通、「より良い」とは「もっと速い」ということを意味するのだが、\n状況によっては「メモリの使用が少ない」とか「使用ディスクスペースが小さい」とかいうことを指す場合もあるし、\nあるいは単純に「よりエレガントだ」ということでもありうる。\n\nこの言葉があなたにとって、あるいはそのプロジェクトや環境においてどんな意味を持つのであれ、\nリファクタリングはおよそプログラムの長期的な健全性を保つのに重要なものだと言える。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "ここでは「より良い」を**「より速い」と「より保守しやすい」の二つの意味** で使う。\n\n要するに、`from_roman()`関数は私が期待するよりも遅くて複雑になってしまっているということなのだが、\nその原因は巨大で扱いにくい正規表現を使ってローマ数字の有効性を検証していることにある。\nここまで読むと、あなたはこのように考えるかもしれない: \n「確かにこの正規表現は大きくて不調法だけど、それ以外に任意の文字列が有効なローマ数字かどうかを検証する方法があるだろうか?」\n\n答え: たった5000個しかないんだから、参照テーブルを作ってみたらどうだろう? \nしかも、こうすれば正規表現をまったく使う必要がないということに気がつけば、このアイデアはさらに魅力なものになるだろう。\nつまり、整数をローマ数字に変換する参照テーブルを組み立てるときに、\nローマ数字を整数に変換する逆の参照テーブルも作ることができるので、\n任意の文字列が有効なローマ数字かどうかを判別する時には、\n有効なローマ数字の一覧表が出来上がっていることになる。\n\nここにおいて「有効性の検証」は一つの辞書を参照するという作業に帰着することになる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "そして何といっても、\n完全なユニットテストのセットが既に全部そろっている。\n仮にモジュールのコードを半分以上変更したとしても、\nユニットテストは前のまま変わらないでいてくれる。\nだから、新しいコードが元のコードと同じように機能すると —自分に対しても他人に対しても— 証明できる。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": true | |
}, | |
"cell_type": "code", | |
"source": "# roman10.py\nclass OutOfRangeError(ValueError): \n pass\nclass NotIntegerError(ValueError): \n pass\nclass InvalidRomanNumeralError(ValueError): \n pass\n\nroman_numeral_map = (('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\nto_roman_table = [ None ]\nfrom_roman_table = {}\n\ndef to_roman(n):\n '''convert integer to Roman numeral'''\n if not (0 < n < 5000):\n raise OutOfRangeError('number out of range (must be 1..4999)')\n if int(n) != n:\n raise NotIntegerError('non-integers can not be converted')\n return to_roman_table[n]\n\ndef from_roman(s):\n '''convert Roman numeral to integer'''\n if not isinstance(s, str):\n raise InvalidRomanNumeralError('Input must be a string')\n if not s:\n raise InvalidRomanNumeralError('Input can not be blank')\n if s not in from_roman_table:\n raise InvalidRomanNumeralError('Invalid Roman numeral: {0}'.format(s))\n return from_roman_table[s]\n\ndef build_lookup_tables():\n def to_roman(n):\n result = ''\n for numeral, integer in roman_numeral_map:\n if n >= integer:\n result = numeral\n n -= integer\n break\n if n > 0:\n result += to_roman_table[n]\n return result\n\n for integer in range(1, 5000):\n roman_numeral = to_roman(integer)\n to_roman_table.append(roman_numeral)\n from_roman_table[roman_numeral] = integer\n \n\nbuild_lookup_tables()", | |
"execution_count": 15, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "コードを小さく分割してみる。\n\n```\nbuild_lookup_tables()\n```" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "ここで関数が呼び出されているが、これは `if __name__ == '__main__'` ブロックではない。\n従って、この関数はモジュールがインポートされた時に呼び出されることになる\n(モジュールは一度しかインポートされず、あとはキャッシュされるということをちゃんと理解しておこう。既にインポートされているモジュールを再びインポートしても、何も実行されないのだ。このコードも最初にモジュールをインポートした時にのみ呼び出されることになる)。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`build_lookup_tables()`関数は一体どんな処理を行うものなのか。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "1. `to_roman()`関数は上の方でも定義されているが、これは参照テーブルで値を探しだし、\nその値を返すというものでしかない。\n一方、`build_lookup_tables()`関数は `to_roman()`関数を再定義していて、\nこの関数に(参照テーブルを加える前のコードがしていたような)実際の処理を行わせている。\nこの `build_lookup_tables()` 中で `to_roman()` を呼び出すと、\n再定義された方の `to_roman()`関数が呼び出されることになる。\n\nそして、`build_lookup_tables()` の実行が終わると、\nこの再定義されたバージョンは消えてしまう \n— この関数はあくまでもbuild_lookup_tables()のローカルスコープ内で定義されたもの。\n\n```\nto_roman_table = [ None ]\nfrom_roman_table = {}\n.\n.\n.\ndef build_lookup_tables():\n def to_roman(n): ①\n result = ''\n for numeral, integer in roman_numeral_map:\n if n >= integer:\n result = numeral\n n -= integer\n break\n if n > 0:\n result += to_roman_table[n]\n return result\n\n for integer in range(1, 5000):\n roman_numeral = to_roman(integer) ②\n to_roman_table.append(roman_numeral) ③\n from_roman_table[roman_numeral] = integer\n```\n\n2.再定義した `to_roman()`関数を呼び出してローマ数字を実際に組み立てている。\n\n3.(再定義したto_roman()関数から)値が返ってきたら、整数と対応するローマ数字の二つを両方の参照テーブルに加えていく。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "参照テーブルができあがってしまえば、後のコードは簡潔で高速なものに仕上がる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`to_roman()`関数は、前と同じように入力値をチェックしたあとは、単に適切な値を参照テーブルから探し出してその値を返すという処理だけを行う。\n\n```\ndef to_roman(n):\n '''convert integer to Roman numeral'''\n if not (0 < n < 5000):\n raise OutOfRangeError('number out of range (must be 1..4999)')\n if int(n) != n:\n raise NotIntegerError('non-integers can not be converted')\n return to_roman_table[n] ①\n```\n" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "同様に、`from_roman()`関数も入力値をチェックする部分の他に一行のコードが置かれているだけになっている。\nここには正規表現は使われていないし、ループもない。\nあるのはローマ数字と整数を相互変換する `O(1)` のコードだけ。\n\n```\ndef from_roman(s):\n '''convert Roman numeral to integer'''\n if not isinstance(s, str):\n raise InvalidRomanNumeralError('Input must be a string')\n if not s:\n raise InvalidRomanNumeralError('Input can not be blank')\n if s not in from_roman_table:\n raise InvalidRomanNumeralError('Invalid Roman numeral: {0}'.format(s))\n return from_roman_table[s] ②\n```" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "O(1)により、このコードは処理も速い。\n現に処理速度はほとんど10倍になっている。もちろん、これは完全にフェアな比較とは言えない。このバージョンだと(参照テーブルを作り上げるので)インポートするのに長い時間がかかるからだ。\nしかし、インポートされるのは一回だけなので、この起動にかかるコストはto_roman()とfrom_roman()の呼び出しごとに償却されてゆくことになる。このテストは何千回もこれらの関数を呼び出すので(往復テストだけで一万回呼び出している)、この最初のコストはすぐに回収される。" | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": true | |
}, | |
"cell_type": "code", | |
"source": "# test\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 (4000, 'MMMM'),\n (4500, 'MMMMD'),\n (4888, 'MMMMDCCCLXXXVIII'),\n (4999, 'MMMMCMXCIX')\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 \nclass ToRomanBadInput(unittest.TestCase):\n \n def test_too_large(self):\n '''to_roman should fail with large input'''\n self.assertRaises(OutOfRangeError, to_roman, 5000)\n \n\nclass FromRomanBadInput(unittest.TestCase):\n \n def test_too_many_repeated_numerals(self):\n '''from_roman should fail with too many repeated numerals'''\n for s in ('MMMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n \n def test_repeated_pairs(self):\n '''from_roman should fail with repeated pairs of numerals'''\n for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):\n self.assertRaises(InvalidRomanNumeralError, from_roman, s)\n \n \n def test_malformed_antecedents(self):\n '''from_roman should fail with malformed antecedents'''\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 \n # 新しく追加\n def testBlank(self):\n '''from_roman should fail with blank string'''\n self.assertRaises(InvalidRomanNumeralError, from_roman, '')\n \n\nclass 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, 5000):\n numeral = to_roman(integer)\n result = from_roman(numeral)\n self.assertEqual(integer, result)", | |
"execution_count": 16, | |
"outputs": [] | |
}, | |
{ | |
"metadata": { | |
"trusted": true, | |
"collapsed": false | |
}, | |
"cell_type": "code", | |
"source": "%tb\ntest = unittest.TestLoader().loadTestsFromTestCase(KnownValues)\nunittest.TextTestRunner().run(test)\ntest = unittest.TestLoader().loadTestsFromTestCase(FromRomanBadInput)\nunittest.TextTestRunner().run(test)\ntest = unittest.TestLoader().loadTestsFromTestCase(RoundtripCheck)\nunittest.TextTestRunner().run(test)", | |
"execution_count": 17, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"name": "stderr", | |
"text": "No traceback available to show.\n..\n----------------------------------------------------------------------\nRan 2 tests in 0.006s\n\nOK\n....\n----------------------------------------------------------------------\nRan 4 tests in 0.011s\n\nOK\n.\n----------------------------------------------------------------------\nRan 1 test in 0.027s\n\nOK\n" | |
}, | |
{ | |
"data": { | |
"text/plain": "<unittest.runner.TextTestResult run=1 errors=0 failures=0>" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 17 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "この話の教訓は:\n\n- 単純さは善\n- 特に正規表現が関わってくる時には。ユニットテストは大規模なリファクタリングを行う自信を与えてくれる" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## まとめ" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "ユニットテストは強力なコンセプトで、正しく実行できればどんな長期プロジェクトにおいても、保守にかかるコストを減らし、柔軟性も高めることができる。\n\nただし、ユニットテストは優れたテストケースを書くのは難しいことだし、\nテストケースをたえず更新していくのには自律心が要る(とりわけ、顧客がクリティカルなバグの修正を求めてわめいている状況では)。\n\n加えて、ユニットテストは、機能テストや統合テスト、アセプタンステストなどの他の形式のテストに取って代わるものでもない。\n\nしかし、このユニットテストは実行可能な手法で、しかもちゃんと機能してくれるものだ。\n一度このやり方がうまくいくと分かったら、ユニットテスト無しで今までどうしてやってこれたのだろうといぶかしく思うようになる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "ユニットテストのフレームワークには様々な言語向けのものが存在するし、そのどれについてもここで述べたのと同じ基本的なコンセプトを理解する必要がある:\n\n- 明確かつ独立であり、しかも自動で実行できるようなテストケースを設計する。\n- **テストするコードの前にテストケースを書く**。\n- 有効な入力値を試して、適切な結果が返ってくるかをチェックするテストを書く。\n- 有効でない入力値を試して、適切に失敗するかをチェックするテストを書く。\n- 新しい要件を反映するように、テストケースを書いたり修正したりする。\n- 容赦なくリファクタリングを施し、機能性や拡張性、可読性、保守性、あるいは何であれコードに欠けている「~性」を向上させていく。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## 参考リンク" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "- [Dive Into Python3 10章 リファクタリング](http://diveintopython3-ja.rdy.jp/refactoring.html)" | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"name": "python3", | |
"display_name": "Python 3", | |
"language": "python" | |
}, | |
"language_info": { | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"version": "3.5.1", | |
"codemirror_mode": { | |
"version": 3, | |
"name": "ipython" | |
}, | |
"pygments_lexer": "ipython3", | |
"nbconvert_exporter": "python" | |
}, | |
"toc": { | |
"toc_threshold": "6", | |
"toc_cell": true, | |
"toc_number_sections": true, | |
"toc_window_display": false | |
}, | |
"gist": { | |
"id": "", | |
"data": { | |
"description": "Dive Into Python3 10章メモ (リファクタリング)", | |
"public": true | |
} | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment