はじめに この記事ではPythonのテストについて、標準ライブラリであるunittest
を使って学んでいきます。
公式リファレンスのコードを引用しながら、解説をしていきます。
解説 基本 test_modlue.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import unittestclass TestStringMethods (unittest.TestCase) : def test_upper (self) : self.assertEqual('foo' .upper(), 'FOO' ) def test_isupper (self) : self.assertTrue('FOO' .isupper()) self.assertFalse('Foo' .isupper()) def test_split (self) : s = 'hello world' self.assertEqual(s.split(), ['hello' , 'world' ]) with self.assertRaises(TypeError): s.split(2 ) if __name__ == '__main__' : unittest.main()
細かくみていきましょう。
unittest
は標準ライブラリであるためインストールの必要はなく、ただインポートすればOKです。
次に、クラスの定義をしています。またこのクラスはunittest.TestCase
を継承しています。
1 class TestStringMethods (unittest.TestCase) :
クラス内で3つのメソッドを定義しています。これらがテストケースに相当します。
1 2 def test_upper (self) :...
最後にメイン関数でunittest.main()
を実行します。ここでテストが実行されることになります。
1 2 if __name__ == '__main__' : unittest.main()
さて、先ほどのスクリプトを実行してみましょう。
1 2 3 4 5 ... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK
上記のように出力されれば成功です。 3件のテスト全てに成功したことがわかります。
コマンドライン実行 -m
オプションを使うことでモジュールを実行することができるため、下記のようにテストすることもできます。
(Python -mオプションの仕組み も参照)
この場合、スクリプト内でメイン関数を実行する必要はありません。
1 python3 -m unittest test_module
1 python3 -m unittest test_module.py
テストに失敗した場合 コードを書き換えてテストを失敗させてみましょう。
1 2 def test_upper (self) : self.assertEqual('foo' .upper(), 'FOOO' )
テストを実行しましょう。
1 2 3 4 5 6 7 8 9 10 AssertionError: 'FOO' != 'FOOO' - FOO + FOOO ? + ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures=1)
1件で失敗したことがわかります。わかります。
詳細の表示 -v
オプションをつけることで詳細を表示することができます
1 python3 -m unittest test_module -v
1 python3 test_module.py -v
のように実行します。
1 2 3 4 5 6 test_isupper (__main__.TestStringMethods) ... ok test_split (__main__.TestStringMethods) ... ok test_upper (__main__.TestStringMethods) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.001s
このように詳細に結果を得られます。
失敗時 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 test_isupper (__main__.TestStringMethods) ... ok test_split (__main__.TestStringMethods) ... ok test_upper (__main__.TestStringMethods) ... FAIL ====================================================================== FAIL: test_upper (__main__.TestStringMethods) ---------------------------------------------------------------------- Traceback (most recent call last): File "test_module.py", line 6, in test_upper self.assertEqual('foo'.upper(), 'FOOO') AssertionError: 'FOO' != 'FOOO' - FOO + FOOO ? + ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures=1)
どのケースが成功したかが表示される分、やはりわかりやすいですね。
長くなりそうなので、続きは次回!
Python test入門 その2
記事情報
投稿日:2020年4月8日
最終更新日:2020年4月10日