Files
DadaoTask/backend/tests/test_idempotency.py
T
Steven 0c53aa7062 feat(m0): 后端骨架 + Web/安卓前端骨架 + 设计文档
- backend: FastAPI 应用工厂、统一错误信封、JWT、短信登录、工作区/成员/邀请、幂等中间件
- alembic 0001: workspace/member/invitation/audit_log/app_user + RLS 策略 + 双角色 GRANT
- tests: 认证/工作区/租户隔离/幂等 四组用例(尚未在本机执行)
- web: React18+Vite 骨架(登录、工作区、邀请落地页)
- android: Compose 骨架(登录、工作区列表)
- 2.Design: PRODUCT-PLAN / ROADMAP-M0-M1 / NAMING / DEVELOPMENT
2026-10-28 02:38:53 +08:00

65 lines
2.3 KiB
Python

"""幂等键:客户端网络抖动重试时,不能建出两个工作区。"""
from __future__ import annotations
from httpx import AsyncClient
from .conftest import login
async def test_same_key_returns_first_result(client: AsyncClient) -> None:
user = await login(client)
headers = {**user["headers"], "Idempotency-Key": "k-1"}
payload = {"name": "幂等工作区"}
first = await client.post("/api/v1/workspaces", json=payload, headers=headers)
second = await client.post("/api/v1/workspaces", json=payload, headers=headers)
assert first.status_code == 200
assert first.json()["data"]["id"] == second.json()["data"]["id"]
assert second.headers.get("X-Idempotent-Replay") == "1"
listed = await client.get("/api/v1/workspaces", headers=user["headers"])
assert len(listed.json()["data"]["items"]) == 1
async def test_different_keys_create_different_workspaces(client: AsyncClient) -> None:
user = await login(client)
a = await client.post(
"/api/v1/workspaces",
json={"name": "一号"},
headers={**user["headers"], "Idempotency-Key": "k-a"},
)
b = await client.post(
"/api/v1/workspaces",
json={"name": "二号"},
headers={**user["headers"], "Idempotency-Key": "k-b"},
)
assert a.json()["data"]["id"] != b.json()["data"]["id"]
async def test_errors_are_not_cached(client: AsyncClient) -> None:
user = await login(client)
headers = {**user["headers"], "Idempotency-Key": "k-err"}
bad = await client.post("/api/v1/workspaces", json={"name": ""}, headers=headers)
assert bad.status_code == 422
good = await client.post("/api/v1/workspaces", json={"name": "修好了"}, headers=headers)
assert good.status_code == 200
assert "X-Idempotent-Replay" not in good.headers
async def test_keys_are_scoped_per_user(client: AsyncClient) -> None:
alice = await login(client)
bob = await login(client)
a = await client.post(
"/api/v1/workspaces",
json={"name": "Alice 的"},
headers={**alice["headers"], "Idempotency-Key": "shared"},
)
b = await client.post(
"/api/v1/workspaces",
json={"name": "Bob 的"},
headers={**bob["headers"], "Idempotency-Key": "shared"},
)
assert a.json()["data"]["id"] != b.json()["data"]["id"]