「Effective Python」を久しぶりに読み返して、当時は特に何も思わなかった箇所に引っかかったのでメモを残しておきますシリーズ第6弾。

Effective Python ―Pythonプログラムを改良する59項目
- 作者: Brett Slatkin,石本敦夫,黒川利明
- 出版社/メーカー: オライリージャパン
- 発売日: 2016/01/23
- メディア: 大型本
- この商品を含むブログ (5件) を見る
Python で unittest ですべてをテストする
ひー!!
いや、ホントそうですよね。
こじんまりと Python 使っていたときはそこまで意識してなかったですが、やはり unittest 大事ですよね。(まぁ、Python に限らずすべての言語で必要だと思いますが。)
写経した結果をぺたりとすると、
# utils.py def to_str(data): if isinstance(data, str): return data elif isinstance(data, bytes): return data.decode('utf-8') else: raise TypeError('Must supply str or bytes, found: %r' % data)
↑がテスト対象の関数で、
# utils_test.py from unittest import TestCase, main from utils import to_str class UtilsTestCase(TestCase): def test_to_str_bytes(self): self.assertEqual('hello', to_str(b'hello')) def test_to_str_str(self): self.assertEqual('hello', to_str('hello')) def test_to_str_bad(self): self.assertRaises(TypeError, to_str, object()) if __name__ == '__main__': main()
↑がテストコードです。
うん、良いですね、unittest って。