振る舞いを記録するテストのアサーション
予測と観察した証拠を記録した後にのみ支援を許可。
Prerequisites
前のアクティビティを完了していること。行き詰まったら、記載されている回復リンクを使う。
Learning Objective
assertEqual と assertRaises を使って unittest.TestCase を書き、python -m unittest -v を実行し、最後の OK の行が何を証明し何を証明しないかを説明する。
Instructions
各 test_ メソッドは1つの振る舞いの主張で、名前は test_empty_list_returns_zero のようにドキュメントとして読めるべき。assertEqual(actual, expected) は値を検査し、with self.assertRaises(例外型): は呼び出しが契約どおりに失敗することを証明する。テストの実行方法は2つある。プロジェクトディレクトリでの python -m unittest -v(python -m unittest discover -v と同じ)は、そのディレクトリの test_*.py という名前のモジュールを発見する。python test_counter.py は、ファイル末尾の unittest.main() を通じてそのファイルに定義されたテストだけを実行する。unittest.main() は隣にある test_*.py モジュールを発見しない。
Practice & Prediction Log
空のディレクトリに counter.py を作り、空白以外の文字を含む要素の個数を返し、要素が str でなければ TypeError を投げる count_non_empty(lines) を書く。test_counter.py には4つのテストを持つ CounterTests クラスを書く:空リストは0を返す、空白だけの行は無視される、混在する行では空でない行だけ数える、そして str でない要素(例えば None)は TypeError を投げる(assertRaises で検査)。4つの結果を予測してから、そのディレクトリで python -m unittest -v を実行する。Python 3.13/3.14 での期待される実行(テストはアルファベット順に実行され、時間は変動する。古い Python では括弧内の名前が短く表示されることがある):
test_empty_list_returns_zero (test_counter.CounterTests.test_empty_list_returns_zero) ... ok
test_mixed_lines_count_only_non_empty (test_counter.CounterTests.test_mixed_lines_count_only_non_empty) ... ok
test_non_string_item_raises_type_error (test_counter.CounterTests.test_non_string_item_raises_type_error) ... ok
test_whitespace_only_line_is_ignored (test_counter.CounterTests.test_whitespace_only_line_is_ignored) ... ok
...
Ran 4 tests in 0.001s
OK
各テストでどのアサーションが実行されるか予測する。テストが1つも実行されなかった(Ran 0 tests)と報告されたら、ファイル名が test_*.py か、発見を実行したディレクトリが正しいかを確認する。
参照実装(2つのファイルは同じディレクトリに置く。Python 3.13 と 3.14 で検証済み):
# file: counter.py
def count_non_empty(lines):
"""Return how many items contain non-whitespace text.
Raise TypeError if an item is not a str.
"""
count = 0
for line in lines:
if not isinstance(line, str):
raise TypeError(f"expected str, got {type(line).__name__}")
if line.strip():
count += 1
return count
# end file
# file: test_counter.py
import unittest
from counter import count_non_empty
class CounterTests(unittest.TestCase):
def test_empty_list_returns_zero(self):
self.assertEqual(count_non_empty([]), 0)
def test_whitespace_only_line_is_ignored(self):
self.assertEqual(count_non_empty([" \t\n"]), 0)
def test_mixed_lines_count_only_non_empty(self):
self.assertEqual(count_non_empty(["alpha\n", " \n", "", "beta"]), 2)
def test_non_string_item_raises_type_error(self):
with self.assertRaises(TypeError):
count_non_empty(["alpha", None])
if __name__ == "__main__":
unittest.main()
# end file
そのディレクトリから発見で実行:
$ python -m unittest -v
test_empty_list_returns_zero (test_counter.CounterTests.test_empty_list_returns_zero) ... ok
test_mixed_lines_count_only_non_empty (test_counter.CounterTests.test_mixed_lines_count_only_non_empty) ... ok
test_non_string_item_raises_type_error (test_counter.CounterTests.test_non_string_item_raises_type_error) ... ok
test_whitespace_only_line_is_ignored (test_counter.CounterTests.test_whitespace_only_line_is_ignored) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
ファイルを直接実行すると、unittest.main() を通じてそのファイルのテストだけが実行され、モジュール名は __main__ と表示される:
$ python test_counter.py -v
test_empty_list_returns_zero (__main__.CounterTests.test_empty_list_returns_zero) ... ok
test_mixed_lines_count_only_non_empty (__main__.CounterTests.test_mixed_lines_count_only_non_empty) ... ok
test_non_string_item_raises_type_error (__main__.CounterTests.test_non_string_item_raises_type_error) ... ok
test_whitespace_only_line_is_ignored (__main__.CounterTests.test_whitespace_only_line_is_ignored) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
OK が証明すること:このインタプリタでこれら4つの入力についてすべてのアサーションが成立したこと(None が TypeError を投げたことを含む)。証明しないこと:誰もテストしていない入力、例えば他の str 以外の型や珍しい空白文字に対して count_non_empty が正しいこと。
実行が assertRaises のテスト1つを含めて Ran 4 tests ... OK で終わり、OK が「これらの入力ですべてのアサーションが成立した」意味であり「関数がすべての可能な入力で正しい」意味ではないと述べられる。
Authoritative Source Resources & Provenance
Python Standard Library: unittest
該当セクション・タイムスタンプ: Classes and functions: Test cases (TestCase assert methods)
検証バージョンと日付: Python 3.12 documentation; verified 2026-10-30
Normative reference for unittest.TestCase, assertEqual, assertRaises, and python -m unittest output.
unittest ships with the interpreter, so every example runs offline; help(unittest.TestCase) documents the assert methods.
比較対象候補リソースと選定評価 (2)
Strong third-party runner, but it adds an installation step and its own conventions; unittest needs no environment change and is the baseline the rest of the curriculum assumes.
Docstring-embedded examples suit tiny pure functions; unittest was selected for the structured TestCase isolation the check suites need.