C
Python/テスト/Lesson 22

pytest をはじめよう

1時間·theory
Python

pytest をはじめよう

🎯 このレッスンを読み終えたら

このレッスンを最後まで読めば、以下の3つを自信を持ってできるようになります。

  • ✅ Python が なぜ AI・データの標準言語になったのか
  • ✅ Python 3.x 基準の venv + requirements.txt セットアップ
  • ✅ print / input / type / dir の4つの組み込み関数

学習目標を チェックリストとして 手元に置き、すべて答えられるようになったらレッスンを閉じてください。

pytest — コード + 実行結果

pytest = Python テストの標準フレームワーク (Django・FastAPI・numpy など)。関数名が test_ で始まれば自動で認識されます。


1. インストール + 最初のテスト

bash
$ pip install pytest
python
# test_math.py
def add(a, b):
    return a + b

def test_add_normal():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -1) == -2
bash
$ pytest test_math.py
# ============= 2 passed in 0.05s =============

2. 失敗時の詳細エラー

python
def test_fail():
    assert add(2, 3) == 6        # ❌ 5 != 6
code
FAILED test_math.py::test_fail
assert 5 == 6
 +  where 5 = add(2, 3)

3. 例外の検証

python
import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("0 で割り算不可")
    return a / b

def test_divide_by_zero_raises_exception():
    with pytest.raises(ValueError, match="不可"):
        divide(10, 0)

4. パラメータ化 — 複数ケースを一度に

python
import pytest

@pytest.mark.parametrize("a, b, expected", [
    (2, 3, 5),
    (-1, -1, -2),
    (0, 0, 0),
    (100, 200, 300),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

# 4 個のテストが自動実行

5. フィクスチャ — 共通の準備

python
import pytest

@pytest.fixture
def user():
    return {"名前": "ホン・ギルドン", "年齢": 28}

def test_name(user):                       # fixture 自動注入
    assert user["名前"] == "ホン・ギルドン"

def test_age(user):
    assert user["年齢"] >= 18

一言まとめ

def test_X(): assert ... + parametrize + fixture の3つで95%をカバーできます。

💻 pytest の基本的な使い方
# インストール: pip install pytest

# test_example.py
def test_addition():
    assert 1 + 1 == 2

def test_string():
    assert "hello".upper() == "HELLO"

# 例外テスト
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

# パラメータ化テスト
@pytest.mark.parametrize("input,expected", [
    (1, 1),
    (2, 4),
    (3, 9),
])
def test_square(input, expected):
    assert input ** 2 == expected

# マーカー (条件付き実行)
@pytest.mark.skip(reason="まだ未実装")
def test_not_implemented():
    pass

@pytest.mark.skipif(True, reason="条件付きスキップ")
def test_conditional():
    pass

# 実行
# pytest                    # 全てのテスト
# pytest test_example.py    # 特定のファイル
# pytest -v                 # 詳細出力
# pytest -k "square"        # 名前フィルター

💡 重要ポイント

1. ファイル名: test_.py または _test.py
2. 関数名: test_ プレフィックス
3. assert 文ひとつでシンプルに検証

Python は簡潔で読みやすい文法により、さまざまな分野で活用されています。インタープリタ言語のため、REPL 環境で即座に実行できます。PEP 8 コーディングスタイルガイドに従い、Black/autopep8 で自動フォーマットします。型ヒント (type hints) でコードの可読性と IDE サポートを向上させます。pip でパッケージ管理、venv/conda で仮想環境を構築します。

🐍 実際に試してみよう — pytest をはじめよう

上記の概念を実際にコードで実行してみましょう。値を変えながら動作を自分の目で確認するのが最も効率的な学習法です。
✏️ Python 코드
📟 コンソール出力
▶ 実行ボタンを押してください
🐍 Pyodideで実際のPythonを実行 — 初回は読み込みに3〜5秒

🤖 AI にこう聞いてみよう

このレッスンの概念を理解すれば、AI に 具体的に 指示できます。漠然とした「直して」ではなく、語彙を持ったリクエスト — それがトークン節約の出発点です。

  • 「この関数に pytest 単体テスト + parametrize を追加して」
  • 「このフィクスチャを conftest.py に切り出して」

なぜこれがトークンを減らすのか

概念を知らない状態では、AI の回答を受け取っても 「それって何ですか?」 と再度質問する必要があります。その「再質問」がトークンを消費します。概念を一度理解すれば、会話が一度で 完結します。

先に読むとよい概念: 非同期プログラミング入門
次のおすすめ: ファイルI/O
pytest入門 - Python