nex_buddy/server/scripts/smoke.py

346 lines
18 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""端到端冒烟:注册 → 发码 → 绑定 → 换 token → 资料/星盘 → 天气 → 解绑 → 码表管理。
用法:
../.venv/bin/python scripts/smoke.py [http://127.0.0.1:8000]
管理端用例需要管理员账号,默认取环境变量 ADMIN_ACCOUNT / ADMIN_PASSWORD,
不传则跳过那几条(不算失败)。
"""
from __future__ import annotations
import hashlib
import os
import random
import sys
import time
import httpx
BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8000").rstrip("/")
ADMIN_ACCOUNT = os.getenv("ADMIN_ACCOUNT", "admin@nexbuddy.com")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "NexBuddy2026")
CHIP = f"SMOKE{random.randint(0x10000000, 0x7FFFFFFF):08X}" # 13 chars,模拟 efuse MAC
ACCOUNT = f"smoke{int(time.time())}@test.local"
PASSWORD = "smoke-pass-123"
ok_count = 0
def step(name: str, cond: bool, extra: str = "") -> None:
global ok_count
mark = "PASS" if cond else "FAIL"
print(f"[{mark}] {name} {extra}")
if cond:
ok_count += 1
else:
raise SystemExit(f"中止于:{name}")
with httpx.Client(base_url=BASE, timeout=15) as c:
h = c.get("/healthz").json()
step("healthz", h["ok"] and h["db"] and h["redis"], f"weather_ready={h['weather_ready']}")
r = c.post("/api/auth/register", json={"account": ACCOUNT, "password": PASSWORD, "nickname": "冒烟用户"})
step("register", r.status_code == 201, f"{r.status_code}")
web = r.json()
u_tok = {"Authorization": f"Bearer {web['token']}"}
step("first user is admin", web["user"]["role"] in ("admin", "user"), web["user"]["role"])
r = c.post("/api/auth/login", json={"account": ACCOUNT, "password": PASSWORD})
step("login", r.status_code == 200, f"{r.status_code}")
r = c.post("/api/auth/login", json={"account": ACCOUNT, "password": "wrong-pass"})
step("wrong password rejected", r.status_code == 401, f"{r.status_code}")
r = c.post("/device/v1/pair/code", json={"chip_id": CHIP, "fw_version": "0.1.0"})
step("device asks code", r.status_code == 200, f"{r.status_code}")
code = r.json()["code"]
print(f" code = {code}")
r = c.get("/device/v1/pair/status", params={"code": code, "chip_id": CHIP})
step("status waiting", r.json()["status"] == "waiting")
r = c.post("/api/devices/pair", json={"code": "000000"}, headers=u_tok)
step("bad code rejected", r.status_code == 404, f"{r.status_code}")
r = c.post("/api/devices/pair", json={"code": code}, headers=u_tok)
step("web binds device", r.status_code == 200, f"{r.status_code}")
device_id = r.json()["id"]
r = c.get("/device/v1/pair/status", params={"code": code, "chip_id": CHIP})
step("status bound", r.json()["status"] == "bound")
r = c.post("/device/v1/pair/claim", json={"code": code, "chip_id": CHIP})
step("device claims token", r.status_code == 200, f"{r.status_code}")
d_tok = {"Authorization": f"Bearer {r.json()['token']}"}
r = c.get("/device/v1/profile", headers=d_tok)
step("device profile", r.status_code == 200 and r.json()["nickname"] == "冒烟用户")
r = c.get("/device/v1/profile", headers={"Authorization": "Bearer 00000000-0000-0000-0000-000000000000:bogus"})
step("bogus device token rejected", r.status_code == 401, f"{r.status_code}")
r = c.get("/device/v1/weather", headers=d_tok)
if r.status_code == 200:
w = r.json()
step("device weather", True, f"{w['city']} {w['temp']}°C {w['text']}")
else:
# 缺 Host → 503,凭据/配额问题 → 502,都应该是明确的上游错误而不是 500
step("weather degrades cleanly", r.status_code in (502, 503),
f"{r.status_code} {r.json().get('detail','')[:60]}")
r = c.get("/api/devices", headers=u_tok)
step("device list", r.status_code == 200 and len(r.json()) == 1)
r = c.get("/api/meta/regions/tree", headers=u_tok)
tree = r.json()
step("region tree", r.status_code == 200 and tree["count"] > 3000, f"{tree['count']} 条")
r = c.get("/api/meta/zodiacs", headers=u_tok)
step("zodiac table", r.status_code == 200 and r.json()["count"] == 12, f"{r.json()['count']} 个")
# 1995-06-18 中午出生在杭州:太阳必在双子,月亮由出生时间决定
r = c.put("/api/user/profile", json={
"birthday": "1995-06-18", "birth_time": "09:20",
"birth_region_code": "330106", "residence_region_code": "310000",
}, headers=u_tok)
u = r.json()
step("profile with region", r.status_code == 200 and u["birth_place"] == "浙江省 杭州市 西湖区",
f'{u.get("birth_place")}')
step("sun sign computed", u.get("sun_sign") == "gemini" and u.get("sun_sign_name") == "双子座",
f'{u.get("sun_sign_name")} {u.get("sun_degree")}°')
step("moon sign computed", bool(u.get("moon_sign_name")), f'{u.get("moon_sign_name")} {u.get("moon_degree")}°')
step("residence resolved", u.get("residence_city") == "上海市", str(u.get("residence_city")))
r = c.post("/api/meta/astro/preview", json={
"birthday": "1990-01-20", "birth_time": "23:50", "birth_region_code": "330106",
}, headers=u_tok)
step("astro preview", r.status_code == 200 and r.json()["sun"]["code"] == "aquarius",
f'{r.json()["sun"]["name"]}')
# 居住时区:合法值生效,非法值 400
r = c.put("/api/user/profile", json={"timezone": "Asia/Tokyo"}, headers=u_tok)
step("timezone saved", r.status_code == 200 and r.json()["timezone"] == "Asia/Tokyo",
str(r.json().get("timezone")))
r = c.put("/api/user/profile", json={"timezone": "Mars/Olympus"}, headers=u_tok)
step("bad timezone rejected", r.status_code == 400, f"{r.status_code}")
c.put("/api/user/profile", json={"timezone": "Asia/Shanghai"}, headers=u_tok)
# 本月运势(Web 端)
r = c.get("/api/meta/fortune", params={"lang": "zh"}, headers=u_tok)
f_zh = r.json()
step("my fortune zh", r.status_code == 200 and f_zh["fortune"] and len(f_zh["fortune"]["content"]) > 10,
f'{f_zh["period"]} {f_zh["fortune"]["title"]}')
r = c.get("/api/meta/fortune", params={"lang": "en"}, headers=u_tok)
step("my fortune en", r.status_code == 200 and "the" in r.json()["fortune"]["content"].lower(),
r.json()["fortune"]["title"][:40])
# 设备端星盘:太阳/月亮 + 本月运势,中英文各一次
r = c.get("/device/v1/astro", headers=d_tok)
a = r.json()
step("device astro", r.status_code == 200 and a["sun"]["name"] == "双子座" and a["moon"]["name"],
f'☉{a["sun"]["name"]} ☽{a["moon"]["name"]} {a["period"]}')
step("device astro fortune", bool(a["fortune"]) and len(a["fortune"]["content"]) > 10,
a["fortune"]["title"][:30])
r = c.get("/device/v1/astro", params={"lang": "en"}, headers=d_tok)
step("device astro en", r.status_code == 200 and r.json()["sun"]["name"] == "Gemini",
r.json()["sun"]["name"])
r = c.get("/api/admin/regions", headers=u_tok)
step("admin blocked for normal user", r.status_code == 403, f"{r.status_code}")
# 管理端:管理员登录后做一轮码表增删
r = c.post("/api/auth/login", json={"account": ADMIN_ACCOUNT, "password": ADMIN_PASSWORD})
if r.status_code == 200 and r.json()["user"]["role"] == "admin":
a_tok = {"Authorization": f"Bearer {r.json()['token']}"}
tmp_code = f"99{random.randint(1000, 9999)}"
r = c.post("/api/admin/regions", json={"code": tmp_code, "name": "冒烟地区", "level": 3,
"parent_code": "330100"}, headers=a_tok)
step("admin create region", r.status_code == 200, f"{r.status_code}")
r = c.put(f"/api/admin/regions/{tmp_code}", json={"name": "冒烟地区2"}, headers=a_tok)
step("admin update region", r.status_code == 200)
r = c.delete(f"/api/admin/regions/{tmp_code}", headers=a_tok)
step("admin delete region", r.status_code == 200)
r = c.get("/api/admin/zodiacs", headers=a_tok)
step("admin zodiac list", r.status_code == 200 and len(r.json()["items"]) == 12)
# 用户与设备管理
r = c.get("/api/admin/users", headers=a_tok)
users = r.json()["items"]
me = next((u for u in users if u["email"] == ACCOUNT), None)
step("admin user list with devices", r.status_code == 200 and me is not None and len(me["devices"]) == 1,
f'{len(users)} 用户')
# 运势:写一条指定年月,设备端应立即取到它
tmp_period = f"2099-{random.randint(1, 12):02d}"
r = c.post("/api/admin/fortunes", json={
"zodiac_code": "gemini", "scope": "ym", "period": tmp_period,
"title": "冒烟运势", "content": "这是冒烟测试写入的指定年月运势文案。",
"title_en": "Smoke", "content_en": "Smoke test monthly fortune.",
}, headers=a_tok)
step("admin create fortune", r.status_code == 200, tmp_period)
r = c.get("/api/admin/fortunes", params={"zodiac_code": "gemini", "scope": "ym"}, headers=a_tok)
row = next((x for x in r.json()["items"] if x["period"] == tmp_period), None)
step("admin list fortune", row is not None)
# 2099 年不会影响设备端「当月」,只验证 CRUD
r = c.put(f"/api/admin/fortunes/{row['id']}", json={"title": "冒烟运势2"}, headers=a_tok)
step("admin update fortune", r.status_code == 200)
r = c.delete(f"/api/admin/fortunes/{row['id']}", headers=a_tok)
step("admin delete fortune", r.status_code == 200)
# ---- 固件管理:上传 → 校验拦截 → 下发 → 设备检查/下载/上报 → 清理 ----
# 用 beta 通道 + 9.9.x:不会污染 stable 的「自动更新最新版」,
# 否则真机下次 check 就会去下载这个假镜像。版本号带随机尾数,
# 上一轮若中途失败留下 9.9.x 也不会撞唯一约束。
fw_ver = f"9.9.{random.randint(100, 999)}"
fake = b"\xe9" + os.urandom(128 * 1024 - 1)
files = {"file": ("smoke-fw.bin", fake, "application/octet-stream")}
form = {"version": fw_ver, "channel": "beta", "notes": "冒烟固件", "publish": "true"}
r = c.post("/api/admin/firmwares", files=files, data=form, headers=a_tok)
step("admin upload firmware", r.status_code == 200, r.json().get("detail", "")[:40])
r = c.post("/api/admin/firmwares", files={"file": ("dup.bin", fake, "application/octet-stream")},
data=form, headers=a_tok)
step("duplicate version rejected", r.status_code == 409, f"{r.status_code}")
r = c.post("/api/admin/firmwares", files={"file": ("x.bin", b"not-an-image", "application/octet-stream")},
data={**form, "version": "9.9.998"}, headers=a_tok)
step("non-esp32 image rejected", r.status_code == 400, r.json().get("detail", "")[:40])
r = c.post("/api/admin/firmwares", files={"file": ("x.bin", fake, "application/octet-stream")},
data={**form, "version": "v1"}, headers=a_tok)
step("bad version rejected", r.status_code == 400, r.json().get("detail", "")[:40])
r = c.get("/api/admin/firmwares", headers=a_tok)
fw = next((x for x in r.json()["items"] if x["version"] == fw_ver), None)
step("admin firmware list", fw is not None and fw["size_bytes"] == len(fake))
fw_id = fw["id"]
# beta 包不进自动更新通道(stable 上若有已发布新版,这里只会给那一版,绝不会给 9.9.x)
r = c.get("/device/v1/firmware/check", headers=d_tok)
step("beta not auto-delivered", r.json().get("version") != fw_ver,
f'update={r.json()["update"]} version={r.json().get("version") or "-"}')
r = c.post(f"/api/admin/devices/{device_id}/upgrade", json={"firmware_id": fw_id}, headers=a_tok)
step("admin push upgrade", r.status_code == 200, r.json().get("detail", ""))
r = c.delete(f"/api/admin/firmwares/{fw_id}", headers=a_tok)
step("delete blocked while targeted", r.status_code == 400, f"{r.status_code}")
r = c.get("/device/v1/firmware/check", headers=d_tok)
chk = r.json()
step("device sees forced update", chk["update"] and chk["version"] == fw_ver and chk["mandatory"],
f'{chk["version"]} {chk["size"]}B')
r = c.get(chk["url"], headers=d_tok)
got = hashlib.sha256(r.content).hexdigest()
step("device downloads image", r.status_code == 200 and got == fw["sha256"] and len(r.content) == len(fake),
f"{len(r.content)}B")
r = c.post("/device/v1/firmware/report", json={"version": fw_ver, "status": "success", "slot": "app0"},
headers=d_tok)
step("device reports success", r.status_code == 200 and r.json()["state"] == "success")
r = c.get("/api/admin/devices/upgrades", headers=a_tok)
up = next((x for x in r.json()["items"] if x["id"] == device_id), None)
step("admin sees new version", up is not None and up["fw_version"] == fw_ver and up["boot_slot"] == "app0",
f'{up["fw_version"]} {up["upgrade_state"]}')
r = c.delete(f"/api/admin/firmwares/{fw_id}", headers=a_tok)
step("admin delete firmware", r.status_code == 200, f"{r.status_code}")
else:
print("[SKIP] 管理员用例(账号不可用)")
# ---- TF 卡媒体:上传 → 清单 → 设备下载/回报 → 删除 → 清单消失 ----
import io
import zlib
from PIL import Image
# 图片:真实 PNG(32x48),服务端应转成 JPEG 并回填尺寸
img = Image.new("RGB", (32, 48), (200, 60, 60))
buf = io.BytesIO()
img.save(buf, "PNG")
r = c.post("/api/media", files={"file": ("smoke-photo.png", buf.getvalue(), "image/png")}, headers=u_tok)
step("upload image -> jpeg", r.status_code == 201 and r.json()["kind"] == "image" and r.json()["width"] == 32,
f'{r.json().get("kind")} {r.json().get("width")}x{r.json().get("height")} {r.json().get("size")}B')
img_id = r.json()["id"]
# 音乐:假 MP3(服务端不解码,只透传)
mp3 = b"\xff\xfb\x90\x00" + os.urandom(64 * 1024)
r = c.post("/api/media", files={"file": ("smoke-song.mp3", mp3, "audio/mpeg")}, headers=u_tok)
step("upload music", r.status_code == 201 and r.json()["kind"] == "music", r.json().get("name", ""))
song_id = r.json()["id"]
r = c.post("/api/media", files={"file": ("virus.exe", b"MZxxxx", "application/x-exe")}, headers=u_tok)
step("bad type rejected", r.status_code == 400, r.json().get("detail", "")[:40])
# 同名重传 = 替换:id 不变、内容更新
mp3b = b"\xff\xfb\x90\x00" + os.urandom(48 * 1024)
r = c.post("/api/media", files={"file": ("smoke-song.mp3", mp3b, "audio/mpeg")}, headers=u_tok)
step("same-name replace", r.status_code == 201 and r.json()["id"] == song_id and r.json()["size"] == len(mp3b),
f'{r.json().get("size")}B')
song_crc = r.json()["crc32"]
r = c.get("/api/media", headers=u_tok)
step("media list", r.status_code == 200 and len(r.json()) == 2 and all(x["synced_devices"] == 0 for x in r.json()))
# 用户进「TF 卡文件」模块:先看到待同步数量,点「立即同步」才下发任务
r = c.get(f"/api/devices/{device_id}/media/pending", headers=u_tok)
st = r.json()
step("web pending check", r.status_code == 200 and st["pending"] == 2 and st["seq"] == 0,
f'pending={st["pending"]} seq={st["seq"]}')
r = c.post(f"/api/devices/{device_id}/media/sync", headers=u_tok)
step("web triggers sync", r.status_code == 200 and r.json()["seq"] == 1, f'seq={r.json().get("seq")}')
r = c.get("/device/v1/media/pending", headers=d_tok)
st = r.json()
step("device sees request", st["seq"] == 1 and st["ack"] == 0, f'seq={st["seq"]} ack={st["ack"]}')
sync_seq = st["seq"]
r = c.get("/device/v1/media/manifest", headers=d_tok)
man = r.json()
names = [x["name"] for x in man["items"]]
step("device manifest", r.status_code == 200 and len(man["items"]) == 2 and "smoke-song.mp3" in names,
f'rev={man["rev"]} {names}')
r = c.get(next(x["url"] for x in man["items"] if x["name"] == "smoke-song.mp3"), headers=d_tok)
step("device downloads media", r.status_code == 200 and (zlib.crc32(r.content) & 0xFFFFFFFF) == song_crc,
f"{len(r.content)}B")
r = c.post(
"/device/v1/media/report",
json={"synced": [img_id, song_id], "deleted": [], "seq": sync_seq, "rev": man["rev"]},
headers=d_tok,
)
step("device reports sync", r.status_code == 200 and r.json()["synced"] == 2 and r.json()["ack"] == sync_seq,
f'ack={r.json().get("ack")}')
r = c.get(f"/api/devices/{device_id}/media/pending", headers=u_tok)
st = r.json()
step("web sees up to date", st["pending"] == 0 and st["rev"] == st["synced_rev"],
f'pending={st["pending"]} rev={st["rev"]}')
r = c.get("/api/media", headers=u_tok)
step("web sees synced badge", all(x["synced_devices"] == 1 for x in r.json()),
str([x["synced_devices"] for x in r.json()]))
# 用户删除 → 清单里消失 → 设备回报删除 → 徽标清零
r = c.delete(f"/api/media/{img_id}", headers=u_tok)
step("user deletes media", r.status_code == 204, f"{r.status_code}")
r = c.get("/device/v1/media/manifest", headers=d_tok)
man = r.json()
step("manifest shrinks", len(man["items"]) == 1 and all(x["id"] != img_id for x in man["items"]),
f'{len(man["items"])} items')
r = c.post("/device/v1/media/report", json={"synced": [song_id], "deleted": [img_id]}, headers=d_tok)
step("device reports deletion", r.status_code == 200 and r.json()["deleted"] == 1)
r = c.delete(f"/api/media/{song_id}", headers=u_tok)
step("cleanup media", r.status_code == 204, f"{r.status_code}")
r = c.delete(f"/api/devices/{device_id}", headers=u_tok)
step("unbind", r.status_code == 200, r.json().get("detail", ""))
r = c.get("/device/v1/profile", headers=d_tok)
step("token revoked after unbind", r.status_code == 401, f"{r.status_code}")
print(f"\n{ok_count} 项全部通过 · chip_id={CHIP}")