読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第4節 重複・競合の再現

4.1 再送で予約が増えない

同じ再送用のキーで、同じ予約を2回送ります。

def test_same_key_twice_makes_one_reservation(before_deadline):
    headers = {**login("tanaka"), "Idempotency-Key": "k-test-dup-01"}
    first = client.post("/reservations", json=BODY, headers=headers)
    second = client.post("/reservations", json=BODY, headers=headers)
    assert (first.status_code, second.status_code) == (201, 200)
    assert first.json()["id"] == second.json()["id"]
    assert count_reservations() == 4

before_deadline は、現在の時刻を11月1日19:00に固定する fixture です。

確かめていることは3つです。

  1. 1回目は 201(作成)、2回目は 200(保存済みを返す)
  2. 2回の応答の予約IDが同じ
  3. データベースの予約が、初期の3件に1件足した4件

応答だけを確かめると、APIが同じIDを返しながら、データベースには2件保存している、という誤りを見逃します。データベースの件数も確かめます。

def count_reservations() -> int:
    with Session(engine) as session:
        return session.scalar(select(func.count()).select_from(Reservation))

14 / 20