item-atlas/backend/tests/smoke.py

132 lines
6.6 KiB
Python

"""Exercise the gateway, both services and PostgreSQL with disposable demo data."""
import base64
import concurrent.futures
import json
import os
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 call(method, path, payload=None, *, user="owner", status=200):
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}")
try:
response = urlopen(request, timeout=78)
except HTTPError as error:
response = error
with response:
raw = response.read()
assert response.status == status, f"{method} {path} expected {status}, got {response.status}: {raw[:800]!r}"
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 (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 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
assert [row["id"] for row in call("GET", "/api/households", user="other")] == [OTHER_HOUSE.rsplit("/", 1)[1]]
print("PASS authentication, household isolation and internal route boundary", flush=True)
study = location("书房 " + RUN)
entry = location("玄关 " + RUN)
box_a = location("白盒", study)
box_b = location("白盒", entry)
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("书房 ")
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("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
for _ in range(20):
operation = call("GET", f"{HOUSE}/operations/{operations[0]['id']}")
if operation["status"] == "COMPLETED":
break
time.sleep(0.5)
assert operation["status"] == "COMPLETED", operation
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 __name__ == "__main__":
main()