item-atlas/backend/tests/smoke.py

307 lines
17 KiB
Python

"""Exercise the gateway, both services and PostgreSQL with disposable demo data."""
import base64
import concurrent.futures
import json
import os
import subprocess
import time
import uuid
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
BASE = os.environ.get("ATLAS_BASE_URL", "http://127.0.0.1:8080").rstrip("/")
PASSWORD = os.environ.get("ATLAS_LOCAL_PASSWORD")
TOKENS = {name: os.environ.get("ATLAS_SMOKE_TOKEN_" + name.upper())
for name in ("owner", "viewer", "other")}
if not (all(TOKENS.values()) or PASSWORD and not any(TOKENS.values())):
raise ValueError("Supply ATLAS_LOCAL_PASSWORD or the three staging access tokens")
HOUSE = "/api/households/00000000-0000-0000-0000-000000000001"
OTHER_HOUSE = "/api/households/00000000-0000-0000-0000-000000000002"
RUN = uuid.uuid4().hex[:8]
def make_request(method, path, payload, user):
data = json.dumps(payload).encode() if payload is not None else None
request = Request(BASE + path, data=data, method=method)
if data is not None:
request.add_header("Content-Type", "application/json")
if user:
if TOKENS[user]:
request.add_header("Authorization", f"Bearer {TOKENS[user]}")
else:
token = base64.b64encode(f"{user}:{PASSWORD}".encode()).decode()
request.add_header("Authorization", f"Basic {token}")
return request
def call(method, path, payload=None, *, user="owner", status=200):
request = make_request(method, path, payload, user)
try:
response = urlopen(request, timeout=78)
except HTTPError as error:
response = error
with response:
raw = response.read()
summary = "invitation response omitted" if "/invitations" in path else repr(raw[:800])
assert response.status == status, f"{method} {path} expected {status}, got {response.status}: {summary}"
return json.loads(raw) if raw and "json" in response.headers.get("Content-Type", "") else None
def ready():
for _ in range(45):
try:
if call("GET", "/actuator/health/readiness", user=None)["status"] == "UP":
call("GET", "/api/households")
call("GET", "/api/model-providers")
return
except (ConnectionError, URLError, AssertionError):
time.sleep(2)
raise AssertionError("Gateway and services did not become ready")
def location(name, parent=None):
return call("POST", HOUSE + "/locations", {"name": name, "parentId": parent}, status=201)["id"]
def await_operation(path, expected):
for _ in range(30):
operation = call("GET", path)
if operation["status"] == expected:
return operation
time.sleep(0.5)
raise AssertionError(f"Expected operation state {expected}, got {operation}")
def recover_unacknowledged_delivery(dsn, operation, draft_path, name):
operation_id = str(uuid.UUID(operation["id"]))
path = f"{HOUSE}/operations/{operation_id}"
# Simulate losing the final acknowledgement after the inventory transaction committed.
# The test database is disposable and the item and inventory's deduplication result stay intact.
changed = subprocess.run(
["psql", dsn, "-XAt", "-v", "ON_ERROR_STOP=1"], text=True, capture_output=True, check=True,
input=f"""
WITH lost_ack AS (
UPDATE confirm_operation SET status='PROCESSING', attempts=5,
lease_until=now()-interval '1 second'
WHERE id='{operation_id}' AND status='COMPLETED'
RETURNING draft_id
)
UPDATE draft SET status='PROCESSING' WHERE id IN (SELECT draft_id FROM lost_ack);
""",
)
assert "UPDATE 1" in changed.stdout, changed.stdout
await_operation(path, "NEEDS_REVIEW")
assert call("GET", draft_path)["status"] == "NEEDS_REVIEW"
call("POST", path + "/retry", user="viewer", status=403)
call("POST", path + "/retry", user="other", status=404)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
def retry_once():
try:
with urlopen(make_request("POST", path + "/retry", None, "owner"), timeout=10) as response:
return response.status, json.load(response)
except HTTPError as error:
return error.code, None
attempts = list(pool.map(lambda _: retry_once(), range(2)))
assert sorted(result[0] for result in attempts) == [202, 409], attempts
assert next(result[1] for result in attempts if result[0] == 202)["id"] == operation_id
await_operation(path, "COMPLETED")
assert call("GET", draft_path)["status"] == "COMPLETED"
call("POST", path + "/retry", status=409)
found = call("GET", HOUSE + "/items?" + urlencode({"q": name}))
assert len(found) == 1 and found[0]["name"] == name
print("PASS exhausted lease, one concurrent recovery and no duplicate after lost acknowledgement", flush=True)
def verify_metrics(targets):
outbox_seen = False
for target in targets.split(","):
with urlopen(target.rstrip("/") + "/actuator/prometheus", timeout=10) as response:
metrics = response.read().decode()
assert "http_server_requests_seconds_bucket" in metrics, target
outbox_seen |= "atlas_outbox_operations" in metrics and "atlas_outbox_delivery_attempts_total" in metrics
assert outbox_seen
print("PASS Prometheus metrics on gateway, inventory and intake", flush=True)
def verify_household_membership(family):
members_path = family + "/members"
invitations = family + "/invitations"
redeem_path = "/api/households/invitations/redeem"
owner, = call("GET", members_path, user="other")
assert set(owner) == {"id", "displayName", "role"} and owner["role"] == "OWNER"
call("GET", members_path, user="viewer", status=404)
call("POST", invitations, {"role": "VIEWER"}, user="viewer", status=404)
call("POST", invitations, {"role": "OWNER"}, user="other", status=400)
call("PUT", members_path + f"/{owner['id']}/role", {"role": "VIEWER"}, user="other", status=409)
call("DELETE", members_path + f"/{owner['id']}", user="other", status=409)
revoked = call("POST", invitations, {"role": "EDITOR"}, user="other", status=201)
call("DELETE", invitations + "/" + revoked["id"], user="other", status=204)
call("POST", redeem_path, {"code": revoked["code"], "displayName": "已撤销"}, user="viewer", status=404)
invite = call("POST", invitations, {"role": "VIEWER"}, user="other", status=201)
pending = call("GET", invitations, user="other")
assert pending == [{key: invite[key] for key in ("id", "role", "expiresAt")}]
call("POST", redeem_path, {"code": invite["code"], "displayName": "匿名"}, user=None, status=401)
call("POST", redeem_path, {"code": "invalid", "displayName": "格式错误"}, user="viewer", status=400)
def compete(user):
payload = {"code": invite["code"], "displayName": "受邀人 " + user}
try:
with urlopen(make_request("POST", redeem_path, payload, user), timeout=10) as response:
return user, response.status
except HTTPError as error:
with error:
return user, error.code
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
attempts = list(pool.map(compete, ["owner", "viewer"]))
assert sorted(status for _, status in attempts) == [200, 404], attempts
winner = next(user for user, status in attempts if status == 200)
loser = next(user for user, status in attempts if status == 404)
joined = call("POST", redeem_path, {"code": invite["code"], "displayName": "重试不改名"}, user=winner)
assert joined["id"] == family.rsplit("/", 1)[1] and joined["role"] == "VIEWER"
assert call("GET", invitations, user="other") == []
owner_after, member = call("GET", members_path, user="other")
assert owner_after == owner and member["displayName"] == "受邀人 " + winner
member_path = members_path + "/" + member["id"]
call("GET", family + "/items", user=winner)
call("GET", members_path, user=winner, status=403)
call("POST", family + "/locations", {"name": "只读不能写"}, user=winner, status=403)
assert call("PUT", member_path + "/role", {"role": "EDITOR"}, user="other")["role"] == "EDITOR"
place = call("POST", family + "/locations", {"name": "共享位置"}, user=winner, status=201)
item = call("POST", family + "/items", {"name": "共享物品", "locationId": place["id"], "quantity": 1},
user=winner, status=201)
item_path = family + "/items/" + item["id"]
call("PUT", item_path + "/preference", {"favorite": True, "rating": 5}, user=winner)
call("PUT", item_path + "/preference", {"favorite": True, "rating": 4}, user="other")
assert call("PUT", member_path + "/role", {"role": "VIEWER"}, user="other")["role"] == "VIEWER"
call("POST", family + "/drafts", {"text": "只读成员不能生成草稿"}, user=winner, status=403)
call("DELETE", member_path, user="other", status=204)
call("GET", item_path, user=winner, status=404)
call("POST", family + "/drafts", {"text": "移除后不能生成草稿"}, user=winner, status=404)
call("POST", redeem_path, {"code": invite["code"], "displayName": "不能再用"}, user=winner, status=404)
rejoin = call("POST", invitations, {"role": "VIEWER"}, user="other", status=201)
call("POST", redeem_path, {"code": rejoin["code"], "displayName": "再次受邀"}, user=winner)
assert call("GET", item_path, user=winner)["preference"]["rating"] is None
assert call("GET", item_path, user="other")["preference"]["rating"] == 4
_, new_member = call("GET", members_path, user="other")
assert new_member["id"] != member["id"]
call("DELETE", members_path + "/" + new_member["id"], user="other", status=204)
if dsn := os.environ.get("ATLAS_SMOKE_INVENTORY_DSN"):
expiring = call("POST", invitations, {"role": "EDITOR"}, user="other", status=201)
invite_id = str(uuid.UUID(expiring["id"]))
subprocess.run(
["psql", dsn, "-XAt", "-v", "ON_ERROR_STOP=1"], text=True, capture_output=True, check=True,
input=f"UPDATE household_invitation SET expires_at=now()-interval '1 second' WHERE id='{invite_id}';",
)
call("POST", redeem_path, {"code": expiring["code"], "displayName": "到期"}, user=loser, status=404)
assert call("GET", invitations, user="other") == []
print("PASS owner-only invitations, concurrent redemption, role changes and membership removal", flush=True)
def main():
ready()
call("GET", HOUSE + "/items", user=None, status=401)
call("GET", HOUSE + "/items", user="other", status=404)
call("GET", "/internal/operations/" + str(uuid.uuid4()), status=404)
assert len(call("GET", "/api/households", user="viewer")) == 1
other_households = {row["id"] for row in call("GET", "/api/households", user="other")}
assert OTHER_HOUSE.rsplit("/", 1)[1] in other_households and HOUSE.rsplit("/", 1)[1] not in other_households
call("POST", "/api/households", {"name": "未登录"}, user=None, status=401)
call("POST", "/api/households", {"name": " "}, status=400)
created = call("POST", "/api/households", {"name": "刚创建 " + RUN}, user="other", status=201)
family_path = "/api/households/" + created["id"]
assert created["role"] == "OWNER" and call("GET", family_path, user="other") == created
call("GET", family_path, status=404)
delivery_password = os.environ.get("ATLAS_DELIVERY_PASSWORD") if not any(TOKENS.values()) else None
if delivery_password:
request = make_request("POST", "/api/households", {"name": "服务账号"}, None)
machine = base64.b64encode(f"atlas-delivery:{delivery_password}".encode()).decode()
request.add_header("Authorization", f"Basic {machine}")
try:
with urlopen(request, timeout=10) as response:
raise AssertionError(f"Delivery account unexpectedly received HTTP {response.status}")
except HTTPError as error:
assert error.code == 403, error.code
print("PASS authentication, household isolation and internal route boundary", flush=True)
verify_household_membership(family_path)
study = location("书房 " + RUN)
entry = location("玄关 " + RUN)
box_a = location("白盒", study)
box_b = location("白盒", entry)
assert call("GET", f"{HOUSE}/locations/{box_b}")["path"].startswith("玄关 ")
call("PUT", f"{HOUSE}/locations/{study}", {"name": "书房", "parentId": box_a}, status=409)
call("DELETE", f"{HOUSE}/locations/{study}", status=409)
call("POST", HOUSE + "/locations", {"name": "不能新建"}, user="viewer", status=403)
item = call("POST", HOUSE + "/items", {
"name": "HDMI 线", "quantity": 2, "locationId": box_a, "aliases": ["视频线 " + RUN],
}, status=201)
found = call("GET", HOUSE + "/items?" + urlencode({"q": "视频线 " + RUN}))
assert found[0]["id"] == item["id"] and found[0]["locationPath"].startswith("书房 ")
by_path = call("GET", HOUSE + "/items?" + urlencode({"q": "书房 " + RUN}))
assert item["id"] in [row["id"] for row in by_path]
call("DELETE", f"{HOUSE}/locations/{box_a}", status=409)
item_path = f"{HOUSE}/items/{item['id']}"
updated = call("POST", item_path + "/moves", {"locationId": box_b, "version": 0})
assert updated["version"] == 1 and updated["locationPath"].startswith("玄关 ")
call("POST", item_path + "/moves", {"locationId": box_a, "version": 0}, status=409)
edited = call("PUT", item_path, {
"name": "HDMI 线", "quantity": 3, "version": 1, "aliases": ["视频线 " + RUN],
})
assert edited["version"] == 2 and edited["quantity"] == 3
related = call("POST", HOUSE + "/items", {"name": "转接头", "quantity": 1, "locationId": box_a}, status=201)
call("PUT", item_path + "/relations", {"itemId": related["id"], "kind": "ACCESSORY"}, status=204)
call("PUT", item_path + "/preference", {"favorite": True, "rating": 5, "note": "常用"})
call("PUT", item_path + "/preference", {"favorite": False, "rating": 2}, user="viewer")
detail = call("GET", item_path)
assert len(detail["moves"]) == 1 and detail["relations"][0]["itemId"] == related["id"]
assert detail["preference"]["rating"] == 5
assert call("GET", item_path, user="viewer")["preference"]["rating"] == 2
call("PUT", item_path + "/preference", {"favorite": False, "rating": None, "note": ""}, user="viewer")
assert call("GET", item_path, user="viewer")["preference"] == {"favorite": False, "rating": None, "note": ""}
assert call("GET", item_path)["preference"]["rating"] == 5
call("DELETE", f"{item_path}/relations/{related['id']}", user="viewer", status=403)
call("DELETE", f"{item_path}/relations/{related['id']}", status=204)
assert call("GET", item_path)["relations"] == []
call("DELETE", f"{HOUSE}/items/{related['id']}?version=0", status=204)
call("GET", f"{HOUSE}/items/{related['id']}", status=404)
print("PASS location tree, alias search, optimistic version, history, related item and preferences", flush=True)
original = "两根 HDMI 线放书房右抽屉。读卡器先别动。备用钥匙好像在玄关白盒。"
configured = os.environ.get("ATLAS_EXPECT_MODEL") == "1"
providers = {row["id"]: row["status"] for row in call("GET", "/api/model-providers")}
assert providers["ollama"] == ("AVAILABLE" if configured else "UNCONFIGURED")
draft = call("POST", HOUSE + "/drafts", {"text": original}, status=201)
assert draft["originalText"] == original
assert draft["status"] == ("READY" if configured else "MODEL_UNAVAILABLE"), draft
if configured:
assert [row["action"] for row in draft["candidates"]] == ["RECORD", "SKIP", "REVIEW"], draft
assert draft["candidates"][0]["quantity"] == 2
draft_path = f"{HOUSE}/drafts/{draft['id']}"
call("GET", draft_path, user="viewer", status=404)
name = "确认录入 " + RUN
payload = {"version": draft["version"], "items": [{"name": name, "quantity": 1, "locationId": box_b}]}
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
operations = list(pool.map(lambda _: call("POST", draft_path + "/confirm", payload, status=202), range(2)))
assert operations[0]["id"] == operations[1]["id"], operations
operation = await_operation(f"{HOUSE}/operations/{operations[0]['id']}", "COMPLETED")
found = call("GET", HOUSE + "/items?" + urlencode({"q": name}))
assert len(found) == 1 and found[0]["name"] == name
assert call("GET", draft_path)["status"] == "COMPLETED"
print("PASS original text, model status, concurrent confirmation and single delivery", flush=True)
if dsn := os.environ.get("ATLAS_SMOKE_INTAKE_DSN"):
recover_unacknowledged_delivery(dsn, operation, draft_path, name)
if targets := os.environ.get("ATLAS_SMOKE_METRIC_TARGETS"):
verify_metrics(targets)
if __name__ == "__main__":
main()