CLI インターフェイス

Pythonによるテスト入門

Alexander Levin

Data Scientist

例: コード

累乗演算子のテスト:

# test_sqneg.py
import unittest
# Declaring the TestCase class
class TestSquared(unittest.TestCase):
    # Defining the test
    def test_negative(self):
        self.assertEqual((-3) ** 2, 9)

CLI コマンド:

python3 -m unittest test_sqneg.py

モジュール unittest で Python スクリプト test_sqneg.py を実行します。

Pythonによるテスト入門

例: 出力

コマンド: python3 -m unittest test_sqneg.py

テスト出力: unittest test_sqneg.py の出力

Pythonによるテスト入門

キーワード引数 -k

unittest -k — パターンや部分文字列に一致するテストメソッド/クラスを実行

コマンド: python3 -m unittest -k "SomeStringOrPattern" test_script.py

: python3 -m unittest -k "Squared" test_sqneg.py

出力: キーワード指定での出力

1 https://docs.python.org/3/library/unittest.html
Pythonによるテスト入門

早期終了フラグ -f

unittest -f — 最初のエラー/失敗で実行を停止します。

コマンド: python3 -m unittest -f test_script.py

ユースケース例: すべてのテストが重要な場合(例: フライト前の航空機テスト)

失敗テストの例

1 https://docs.python.org/3/library/unittest.html
Pythonによるテスト入門

Catch フラグ -c

catch フラグ unittest -c — 「Ctrl - C」でテストを中断できます。

  • Ctrl - C」を1回押すと、unittest は現在のテスト終了を待ち、ここまでの結果を出力します。
  • 2回押すと、unittestKeyboardInterrupt 例外を送出します。 コマンド: python3 -m unittest -c test_script.py

ユースケース例: 大規模なテストスイートのデバッグ時

1 https://docs.python.org/3/library/unittest.html
Pythonによるテスト入門

Verbose フラグ -v

unittest -v — 詳細表示でテストを実行

コマンド: python3 -m unittest -v test_script.py.

ユースケース例: デバッグ用途

出力例: verbose フラグ付きの unittest 出力

1 https://docs.python.org/3/library/unittest.html
Pythonによるテスト入門

まとめ

  • 引数なしの基本コマンド python3 -m unittest test_script.py

  • unittest の出力

  • キーワード引数: python3 -m unittest -k "SomeStringOrPattern" test_script.py

  • 早期終了フラグ: python3 -m unittest -f test_script.py

  • Catch フラグ: python3 -m unittest -c test_script.py

  • Verbose フラグ: python3 -m unittest -v test_script.py

Pythonによるテスト入門

練習してみましょう!

Pythonによるテスト入門

Preparing Video For Download...