item-atlas/backend/tests/ios_experience_smoke.py

470 lines
26 KiB
Python

"""Validate iOS workflows in a disposable environment with a native_account row for viewer."""
import concurrent.futures
import os
from urllib.parse import urlencode
from uuid import uuid4
from smoke import RUN, await_operation, call, ready
def verify():
ready()
verify_profiles()
verify_inventory_summary()
space = call("POST", "/api/households", {"name": "见物体验 " + RUN}, status=201)
root = "/api/households/" + space["id"]
try:
verify_inventory_appearance(root)
verify_search_and_voice(root)
verify_optional_locations(root)
verify_direct_invitations(root)
verify_location_order(root)
verify_location_layout(root)
verify_community(root)
finally:
call("DELETE", root, status=202)
def verify_profiles():
path = "/api/me/profile"
call("GET", path, user=None, status=401)
owner = call("GET", path)
viewer = call("GET", path, user="viewer")
assert viewer["username"] == "viewer"
fields = ("nickname", "signature", "avatar")
try:
update = {"nickname": " 小见 ", "signature": " 把常用物放回原处 ", "avatar": "LEAF"}
result = call("PUT", path, update)
assert result == {"username": owner["username"], "nickname": "小见", "signature": "把常用物放回原处", "avatar": "LEAF"}
assert call("GET", path) == result
assert call("GET", path, user="viewer") == viewer
call("PUT", path, dict(update, avatar="UNKNOWN"), status=400)
call("PUT", path, dict(update, signature="字" * 101), status=400)
assert call("GET", path) == result
finally:
call("PUT", path, {field: owner[field] for field in fields})
print("PASS private editable profile, account display and input validation", flush=True)
def verify_inventory_summary():
summary = "/api/me/inventory-summary"
call("GET", summary, user=None, status=401)
before = call("GET", summary)
viewer_summary = call("GET", summary, user="viewer")
roots = ["/api/households/" + call("POST", "/api/households", {"name": "物品统计 " + RUN}, status=201)["id"]
for _ in range(2)]
maximum = 9_990_000_000_000
def check(items, units, priced, archived, published, cents):
current = call("GET", summary)
for key, delta in zip(("activeItems", "activeUnits", "pricedItems", "archivedItems", "publishedItems"),
(items, units, priced, archived, published)):
assert current[key] == before[key] + delta, (key, current[key], before[key], delta)
assert current["totalValueCents"] == str(int(before["totalValueCents"]) + cents), current
assert call("GET", summary, user="viewer") == viewer_summary
def create_at(root):
return call("POST", root + "/items", {"name": "待整理设备", "quantity": 2,
"appearance": {"icon": "BOX", "priceCents": maximum}}, status=201)
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
first, second = pool.map(create_at, roots)
check(2, 4, 2, 0, 0, maximum * 4)
call("POST", roots[0] + "/items", {"name": "超额测试", "quantity": 1,
"appearance": {"icon": "BOX", "priceCents": maximum + 1}}, status=400)
note = call("POST", roots[0] + "/items", {"name": "未填价格的物品", "quantity": 1}, status=201)
check(3, 5, 2, 0, 0, maximum * 4)
path = roots[0] + "/items/" + first["id"]
update = {"name": first["name"], "quantity": 3, "version": first["version"],
"appearance": {"icon": "BOX", "priceCents": 8888}}
edited = call("PUT", path, update)
check(3, 6, 2, 0, 0, maximum * 2 + 3 * 8888)
publication = path + "/publication"
draft = {"title": "测试分享", "body": "体验记录"}
assert call("PUT", publication, draft) == call("PUT", publication, draft)
check(3, 6, 2, 0, 1, maximum * 2 + 3 * 8888)
call("DELETE", publication, status=204)
check(3, 6, 2, 0, 0, maximum * 2 + 3 * 8888)
call("PUT", publication, draft)
call("DELETE", path + "?version=" + str(edited["version"]), status=204)
check(2, 3, 1, 1, 0, maximum * 2)
call("DELETE", roots[1], status=202)
roots.pop()
check(1, 1, 0, 1, 0, 0)
assert note["priceCents"] is None and second["priceCents"] == maximum
finally:
for root in roots:
call("DELETE", root, status=202)
check(0, 0, 0, 0, 0, 0)
print("PASS private persisted owner totals, concurrent spaces, price cap, publication, archive and deletion", flush=True)
def verify_search_and_voice(root):
def location(name, parent=None):
return call("POST", root + "/locations", {"name": name, "parentId": parent}, status=201)["id"]
room = location("书房")
drawer = location("右抽屉", room)
entry = location("玄关")
duplicate = location("右抽屉", entry)
def item(name, place, aliases=None, quantity=1):
return {"name": name, "quantity": quantity, "locationId": place, "notes": "", "aliases": aliases or []}
exact = call("POST", root + "/items", item("数据线", drawer), status=201)["id"]
alias = call("POST", root + "/items", item("充电配件", drawer, ["数据线"]), status=201)["id"]
prefix = call("POST", root + "/items", item("数据线收纳包", duplicate), status=201)["id"]
contains = call("POST", root + "/items", item("旧数据线备用", drawer), status=201)["id"]
percent = call("POST", root + "/items", item("标签%尺寸", entry), status=201)["id"]
assert call("GET", root + "/items?favorites=true") == []
call("PUT", root + "/items/" + exact + "/preference", {"favorite": True})
assert [row["id"] for row in call("GET", root + "/items?favorites=true")] == [exact]
def search(term):
return [row["id"] for row in call("GET", root + "/items?" + urlencode({"q": term}))]
assert search("数据线") == [exact, alias, prefix, contains]
assert set(search("书房 / 右抽屉")) == {exact, alias, contains}
assert search("%") == [percent]
call("GET", root + "/items?" + urlencode({"q": "数据线"}), user="other", status=404)
print("PASS scoped weighted name/alias/path search and literal wildcard", flush=True)
def draft(text):
result = call("POST", root + "/drafts", {"text": text, "source": "VOICE"}, status=201)
assert result["status"] == "READY" and result["source"] == "VOICE"
return result
for text in ("我没把钥匙放在书房右抽屉", "钥匙好像放在书房右抽屉", "两根线一个转接头放在书房右抽屉"):
assert draft(text)["candidates"] == []
note = draft("我刚把两根转接线放在书房右抽屉了。")
assert note["candidates"] == [{"name": "转接线", "quantity": 2, "action": "RECORD", "location": "书房右抽屉了"}]
confirm = root + "/drafts/" + note["id"] + "/confirm"
payload = {"version": note["version"], "items": [item("转接线", duplicate, quantity=2)], "automatic": True}
call("POST", confirm, payload, status=409)
payload["items"][0]["locationId"] = drawer
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
operations = list(pool.map(lambda _: call("POST", confirm, payload, status=202), range(2)))
assert operations[0]["id"] == operations[1]["id"]
await_operation(root + "/operations/" + operations[0]["id"], "COMPLETED")
assert len(search("转接线")) == 1
print("PASS voice rules, automatic location guard and one outbox delivery", flush=True)
def verify_inventory_appearance(root):
locations = root + "/locations"
room = call("POST", locations, {"name": "储藏室", "icon": "HOME"}, status=201)
assert room["icon"] == "HOME"
box = call("POST", locations, {"name": "收纳柜", "parentId": room["id"]}, status=201)
assert box["icon"] == "FOLDER"
path = locations + "/" + box["id"]
edited = call("PUT", path, {"name": box["name"], "parentId": room["id"], "icon": "CABINET"})
assert edited["parentId"] == room["id"] and edited["icon"] == "CABINET"
assert call("PUT", path, {"name": box["name"], "parentId": room["id"]})["icon"] == "CABINET"
call("PUT", path, {"name": box["name"], "parentId": room["id"], "icon": "KEY"}, status=400)
items = root + "/items"
payload = {"name": "充电器套装", "quantity": 1, "locationId": box["id"],
"appearance": {"icon": "CABLE", "priceCents": 3999}}
key = uuid4()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
created = list(pool.map(lambda _: call("POST", items, payload, status=201, request_key=key), range(2)))
assert created[0] == created[1] and created[0]["icon"] == "CABLE" and created[0]["priceCents"] == 3999
item = created[0]
path = items + "/" + item["id"]
basic = {"name": item["name"], "quantity": 1, "version": item["version"]}
legacy_edit = call("PUT", path, basic)
assert legacy_edit["icon"] == "CABLE" and legacy_edit["priceCents"] == 3999
edit = dict(basic, version=legacy_edit["version"], appearance={"icon": "TOOL", "priceCents": None})
call("PUT", path, dict(edit, appearance={"icon": "TOOL", "priceCents": -1}), status=400)
updated = call("PUT", path, edit)
assert updated["icon"] == "TOOL" and updated["priceCents"] is None
assert call("GET", path)["item"] == updated
print("PASS location and item icons, integer price, older clients and deduplicated creation", flush=True)
def verify_optional_locations(root):
items = root + "/items"
place = call("POST", root + "/locations", {"name": "衣帽间 " + RUN}, status=201)
manual = call("POST", items, {"name": "待整理的手电 " + RUN, "quantity": 1, "aliases": ["备用照明 " + RUN]}, status=201)
assert manual["locationId"] is None and manual["locationPath"] == ""
address = items + "/" + manual["id"]
assert call("GET", address)["item"] == manual
assert [p["id"] for p in call("GET", items + "?" + urlencode({"q": manual["aliases"][0]}))] == [manual["id"]]
assert manual["id"] not in {p["id"] for p in call("GET", items + "?location=" + place["id"])}
stored = call("POST", items, {"name": "电池", "quantity": 1, "locationId": place["id"]}, status=201)
stored_path = items + "/" + stored["id"]
call("PUT", stored_path + "/relations", {"itemId": manual["id"], "kind": "ACCESSORY"}, status=204)
linked, = call("GET", stored_path)["relations"]
assert linked["itemId"] == manual["id"] and linked["locationPath"] == ""
call("POST", address + "/moves", {"version": manual["version"]}, status=400)
moved = call("POST", address + "/moves", {"locationId": place["id"], "version": manual["version"]})
assert moved["locationPath"] == place["name"]
call("POST", address + "/moves", {"locationId": None, "version": manual["version"]}, status=409)
cleared = call("POST", address + "/moves", {"locationId": None, "version": moved["version"]})
assert cleared["locationId"] is None
latest, initial = call("GET", address)["moves"]
assert (initial["fromPath"], initial["toPath"]) == ("", place["name"])
assert (latest["fromPath"], latest["toPath"]) == (place["name"], "")
name = "录入无位置手表 " + RUN
draft = call("POST", root + "/drafts", {"text": "记录两只手表", "source": "VOICE"}, status=201)
assert draft["candidates"] == [{"name": "手表", "quantity": 2, "action": "RECORD", "location": None}]
confirm = root + "/drafts/" + draft["id"] + "/confirm"
payload = {"version": draft["version"], "items": [{"name": name, "quantity": 1, "locationId": None},
{"name": "带位置的物品 " + RUN, "quantity": 1, "locationId": place["id"]}]}
call("POST", confirm, dict(payload, automatic=True), status=409)
call("POST", confirm, {"version": draft["version"], "items": [{"name": "手表", "quantity": 2}],
"automatic": True}, status=409)
operation = call("POST", confirm, payload, status=202)
await_operation(root + "/operations/" + operation["id"], "COMPLETED")
actual, = call("GET", items + "?" + urlencode({"q": name}))
assert actual["locationId"] is None and actual["locationPath"] == ""
with_location, = call("GET", items + "?" + urlencode({"q": payload["items"][1]["name"]}))
assert with_location["locationId"] == place["id"]
call("DELETE", address + "?version=" + str(cleared["version"]), status=204)
print("PASS unset positions in manual creation, search, links, move history and mixed draft confirmation", flush=True)
def verify_direct_invitations(root):
sent = root + "/direct-invitations"
inbox = "/api/households/direct-invitations"
call("POST", sent, {"username": "unknown-" + RUN, "role": "VIEWER"}, status=202)
assert call("GET", sent) == []
call("GET", root + "/items", user="viewer", status=404)
call("POST", sent, {"username": "ViEwEr", "role": "VIEWER"}, status=202)
call("POST", sent, {"username": "viewer", "role": "EDITOR"}, status=202)
outgoing, = call("GET", sent)
assert outgoing["username"] == "viewer" and outgoing["role"] == "VIEWER"
received, = [row for row in call("GET", inbox, user="viewer") if row["id"] == outgoing["id"]]
assert received["role"] == "VIEWER"
assert not any(row["id"] == outgoing["id"] for row in call("GET", inbox, user="other"))
accept = inbox + "/" + outgoing["id"] + "/accept"
call("POST", accept, user="other", status=404)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda _: call("POST", accept, user="viewer"), range(2)))
assert results[0] == results[1] and results[0]["role"] == "VIEWER"
call("GET", root + "/items", user="viewer")
call("POST", root + "/drafts", {"text": "数据线放在书房右抽屉", "source": "VOICE"}, user="viewer", status=403)
call("POST", sent, {"username": "other", "role": "EDITOR"}, user="viewer", status=403)
assert call("GET", sent) == []
print("PASS addressed invitations, private inbox, atomic acceptance and role checks", flush=True)
def verify_location_order(root):
locations = root + "/locations"
endpoint = locations + "/order"
def place(name, parent=None):
return call("POST", locations, {"name": name, "parentId": parent}, status=201)
def payload(order, ids, parent=None):
return {"version": order["version"], "ids": ids, "parentId": parent}
room = place("排序房间")
first = place("A 柜", room["id"])
second = place("B 柜", room["id"])
nested = endpoint + "?" + urlencode({"parentId": room["id"]})
initial = call("GET", nested, user="viewer")
assert initial["ids"] == [first["id"], second["id"]]
assert first["sortRank"] is None and second["sortRank"] is None
request = payload(initial, list(reversed(initial["ids"])), room["id"])
call("PUT", endpoint, request, user="viewer", status=403)
call("GET", nested, user="other", status=404)
call("PUT", endpoint, payload(initial, [first["id"], room["id"]], room["id"]), status=400)
call("PUT", endpoint, payload(initial, [first["id"]] * 2, room["id"]), status=400)
saved = call("PUT", endpoint, request)
assert saved == call("GET", nested) == call("PUT", endpoint, request)
assert initial["version"] != saved["version"]
call("PUT", endpoint, payload(initial, initial["ids"], room["id"]), status=409)
third = place("0 应排在末尾", room["id"])
assert third["sortRank"] == 2
assert call("GET", nested)["ids"] == saved["ids"] + [third["id"]]
call("PUT", locations + "/" + second["id"], {"name": "改名后仍在首位", "parentId": room["id"]})
assert call("GET", nested)["ids"][0] == second["id"]
call("DELETE", locations + "/" + first["id"], status=204)
call("PUT", endpoint, request, status=409)
assert call("GET", nested)["ids"] == [second["id"], third["id"]]
root_order = call("GET", endpoint)
reversed_root = list(reversed(root_order["ids"]))
assert call("PUT", endpoint, payload(root_order, reversed_root))["ids"] == reversed_root
all_places = {row["id"]: row for row in call("GET", locations)}
assert [all_places[item]["sortRank"] for item in reversed_root] == list(range(len(reversed_root)))
assert call("GET", nested)["ids"] == [second["id"], third["id"]]
print("PASS persisted sibling order, append, scoped roles, stale edits and idempotent retry", flush=True)
def verify_location_layout(root):
location_path = root + "/locations"
layout_path = root + "/location-layout"
def shape(template, x, y, w, h, rotation=0):
return {"template": template, "xMm": x, "yMm": y, "widthMm": w, "depthMm": h, "rotation": rotation}
def entry(id, geometry, name=None):
return {"id": id, "geometry": geometry, "newName": name}
def content(point, placements, parent=None):
return {"version": point["version"], "parentId": parent, "placements": placements}
room = call("POST", location_path, {"name": "布局客厅"}, status=201)["id"]
first = call("GET", layout_path, user="viewer")
assert any(p["id"] == room and p["geometry"] is None for p in first["locations"])
call("GET", layout_path, user="other", status=404)
sofa_id = str(uuid4())
closed = entry(room, shape("LIVING_ROOM", 200, 300, 4000, 3600))
sofa = entry(sofa_id, shape("SOFA", 500, 700, 1500, 800), "测试沙发")
request = content(first, [closed, sofa])
call("PUT", layout_path, request, user="viewer", status=403)
call("PUT", layout_path, content(first, [closed, entry(str(uuid4()), shape("ROOM", 300, 500, 2100, 1900), "重叠房间")]), status=409)
call("PUT", layout_path, content(first, [entry(room, shape("ROOM", 11800, 300, 4000, 3600))]), status=400)
assert call("GET", layout_path) == first
saved = call("PUT", layout_path, request)
assert saved == call("GET", layout_path) == call("PUT", layout_path, request)
assert call("GET", location_path + "/" + sofa_id)["parentId"] is None
call("PUT", layout_path, content(first, []), status=409)
inner_path = layout_path + "?" + urlencode({"parentId": room})
inner = call("GET", inner_path)
assert (inner["widthMm"], inner["depthMm"], inner["locations"]) == (4000, 3600, [])
cabinet = entry(str(uuid4()), shape("WARDROBE", 2200, 900, 1500, 650), "布局衣柜")
call("PUT", layout_path, content(inner, [entry(sofa_id, sofa["geometry"])], room), status=400)
nested = call("PUT", layout_path, content(inner, [cabinet], room))
assert nested == call("GET", inner_path)
call("GET", layout_path + "?" + urlencode({"parentId": cabinet["id"]}), status=400)
too_small = entry(room, shape("LIVING_ROOM", 100, 100, 2000, 1700))
call("PUT", layout_path, content(saved, [too_small, sofa]), status=409)
turned = entry(room, shape("LIVING_ROOM", 200, 300, 3600, 4000, 90))
rotated = call("PUT", layout_path, content(saved, [turned, sofa]))
assert call("GET", inner_path)["widthMm"] == 4000
removed = call("PUT", layout_path, content(rotated, [turned]))
assert any(p["id"] == sofa_id and p["geometry"] is None for p in removed["locations"])
assert call("GET", location_path + "/" + sofa_id)["name"] == "测试沙发"
draft_path = root + "/location-layout-drafts"
instructions = {"description": "在布局客厅右边放书房,把已有的测试沙发摆到布局客厅里面。",
"version": removed["version"]}
call("POST", draft_path, instructions, user=None, status=401)
call("POST", draft_path, instructions, user="viewer", status=403)
call("POST", draft_path, instructions, user="other", status=404)
call("POST", draft_path, dict(instructions, version=first["version"]), status=409)
if os.environ.get("ATLAS_EXPECT_PLAN_DRAFT") == "1":
proposal = call("POST", draft_path, instructions)
proposed = {change["name"]: change for change in proposal["changes"]}
assert proposed["书房"]["geometry"] is not None
assert proposed["测试沙发"]["locationId"] == sofa_id
elif not any(row["status"] == "AVAILABLE" for row in call("GET", "/api/model-providers")):
call("POST", draft_path, instructions, status=503)
assert call("GET", layout_path) == removed
print("PASS two-level floor plans, shared positions, atomic creation, bounds, overlap, roles and retry", flush=True)
def verify_community(root):
room = call("POST", root + "/locations", {"name": "测试住址" + RUN, "icon": "BEDROOM"}, status=201)
posts = "/api/community/posts"
term = "社区相机" + RUN
def create(name):
return call("POST", root + "/items", {
"name": name, "quantity": 1, "locationId": room["id"], "notes": "仅家庭可见" + RUN,
"appearance": {"icon": "CAMERA", "priceCents": 12800},
}, status=201)
def publication(item):
return root + "/items/" + item["id"] + "/publication"
item, second = create("家庭相机" + RUN), create("旧设备" + RUN)
assert item["published"] is False
assert call("GET", publication(item))["postId"] is None
call("GET", posts, user=None, status=401)
call("GET", posts + "?limit=0", status=400)
call("GET", posts + "?rank=2", status=400)
assert call("GET", posts + "?" + urlencode({"q": term}), user="other")["posts"] == []
draft = {"title": term, "body": "外出拍照携带方便。" * 32}
call("PUT", publication(item), draft, user="viewer", status=403)
call("PUT", publication(item), draft, user="other", status=404)
call("PUT", publication(item), dict(draft, body=" "), status=400)
sharing = call("PUT", publication(item), draft)
assert call("PUT", publication(item), draft) == sharing
weaker = call("PUT", publication(second), {"title": "另一份使用体会", "body": term})["postId"]
address = posts + "/" + sharing["postId"]
assert call("GET", root + "/items/" + item["id"])["item"]["published"] is True
result = call("GET", address, user="other")
assert set(result) == {"id", "title", "body", "author", "authorId", "authorAvatar", "mine", "publishedAt",
"average", "votes", "myRating", "comments"}
assert result["title"] == term and result["body"] == draft["body"] and result["mine"] is False
profile_path = "/api/community/people/" + result["authorId"]
call("GET", profile_path, user=None, status=401)
call("GET", "/api/community/people/" + str(uuid4()), user="other", status=404)
assert call("GET", profile_path, user="other") == {
"id": result["authorId"], "name": result["author"], "avatar": result["authorAvatar"], "publishedItems": 2
}
authors_posts = call("GET", posts + "?" + urlencode({"authorId": result["authorId"]}), user="other")
assert {row["id"] for row in authors_posts["posts"]} == {result["id"], weaker}
assert call("GET", root + "/items/" + item["id"])["item"]["communityPostId"] == result["id"]
assert not any(value in str(result) for value in (item["id"], item["name"], room["id"], room["name"], item["notes"]))
query = {"q": term, "limit": 1}
first = call("GET", posts + "?" + urlencode(query), user="other")
only, = first["posts"]
assert only["id"] == result["id"] and len(only["body"]) == 220
cursor = first["next"]
query.update(rank=cursor["rank"], time=cursor["time"], before=cursor["id"])
assert [row["id"] for row in call("GET", posts + "?" + urlencode(query), user="other")["posts"]] == [weaker]
assert not call("GET", posts + "?mine=true", user="other")["posts"]
assert result["id"] in {post["id"] for post in call("GET", posts + "?mine=true")["posts"]}
assert not call("GET", posts + "?" + urlencode({"q": room["name"]}))["posts"]
assert not call("GET", root + "/items?" + urlencode({"q": term}))
rating = address + "/rating"
call("PUT", rating, {"stars": 6}, user="other", status=400)
assert call("PUT", rating, {"stars": 4}, user="other")["votes"] == 1
updated = call("PUT", rating, {"stars": 5}, user="other")
assert updated["votes"] == 1 and updated["average"] == 5 and updated["myRating"] == 5
assert call("GET", address)["myRating"] is None
assert call("PUT", rating, {}, user="other")["votes"] == 0
comments = address + "/comments"
first = call("POST", comments, {"body": "请问续航怎么样?"}, user="other", status=201)
commenter = call("GET", "/api/community/people/" + first["authorId"], user="viewer")
assert commenter["id"] != result["authorId"] and commenter["publishedItems"] == 0
second_comment = call("POST", comments, {"body": "一天没问题。"}, status=201)
last = call("GET", comments + "?limit=1", user="other")
assert [row["id"] for row in last["comments"]] == [second_comment["id"]]
cursor = last["next"]
rest, = call("GET", comments + "?" + urlencode({"time": cursor["time"], "before": cursor["id"]}),
user="other")["comments"]
assert rest["id"] == first["id"] and rest["mine"] is True
call("DELETE", comments + "/" + first["id"], status=404)
call("DELETE", comments + "/" + first["id"], user="other", status=204)
assert call("GET", address)["comments"] == 1
call("PUT", rating, {"stars": 5}, user="other")
call("DELETE", publication(item), status=204)
call("GET", address, user="other", status=404)
call("GET", comments, user="other", status=404)
call("PUT", rating, {"stars": 1}, user="other", status=404)
private = call("GET", root + "/items/" + item["id"])["item"]
assert private["published"] is False and private["communityPostId"] is None
assert call("GET", profile_path, user="other")["publishedItems"] == 1
again = call("PUT", publication(item), draft)["postId"]
assert again != sharing["postId"]
assert call("GET", posts + "/" + again)["votes"] == 0
assert call("GET", posts + "/" + again + "/comments")["comments"] == []
call("DELETE", root + "/items/" + item["id"] + "?version=" + str(item["version"]), status=204)
call("GET", posts + "/" + again, user="other", status=404)
print("PASS private by default, public field boundary, ranked search, cursor, ratings, comments and withdrawal", flush=True)
if __name__ == "__main__":
verify()