Pythonによるテスト入門
Alexander Levin
Data Scientist
一般的な問題:
これらは修正のための大きな費用増につながり得ます。
テストの効果:
仕様を満たすことを確認するために必要です
テスト(試験) — ソフトウェアやシステムの正しさを検証する手順
assert 文飛行機を考えてみましょう:
これらはすべてテストであり、安全のために必要です。

assert condition — condition が True かをテストします。condition が False の場合、Python は AssertionError を送出します。pytest — Python の代表的なテストフレームワーク。シンプルにテストを書けます。
pytest を用いた「assert」テストの例:
import pytest
# テスト対象関数
def squared(number):
return number * number
# テスト関数は "test" で始める
def test_squared():
assert squared(-2) == squared(2)
with 文で利用する Python オブジェクト# ファイル書き込みの例
with open("hello_world.txt", 'w') as hello_file:
hello_file.write("Hello world \n")
pytest.raises — 例外の送出を期待するテストに使います
import pytest
# テスト対象関数
def division(a, b):
return a / b
# テスト関数
def test_raises():
with pytest.raises(ZeroDivisionError):
division(a=25, b=0)
テストとは:
テストの実装:
pytest — 強力な Python フレームワーク。テストを簡素化assert — 条件の検証で基本的なテストを作成する Python キーワードpytest.raises — 例外発生を期待するテスト用のコンテキストマネージャPythonによるテスト入門