173 lines
8.4 KiB
Python
173 lines
8.4 KiB
Python
"""固件发布链路端到端冒烟:上传 → 发布 → 设备 check → 下载 → 上报 → 再 check。
|
||
|
||
用法(后端已 ./scripts/dev.sh 起来):
|
||
.venv/bin/python scripts/smoke_firmware.py [http://127.0.0.1:8100]
|
||
|
||
管理端用例需要管理员账号,默认 admin@nexbuddy.com / NexBuddy2026。
|
||
脚本会在库里留下一个 SMOKE-OTA 设备和一个 9.9.9 的固件包,跑完自动清掉。
|
||
"""
|
||
|
||
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:8100").rstrip("/")
|
||
ADMIN_ACCOUNT = os.getenv("ADMIN_ACCOUNT", "admin@nexbuddy.com")
|
||
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "NexBuddy2026")
|
||
CHIP = f"SMOKEOTA{random.randint(0x100000, 0xFFFFFF):06X}"
|
||
ACCOUNT = f"otas{int(time.time())}@test.local"
|
||
PASSWORD = "otas-pass-123"
|
||
VERSION = f"9.9.{random.randint(1, 99)}"
|
||
MODEL = "JC3636K518C_I_W"
|
||
|
||
# 假固件:真机不会拿它启动,这里只验服务端的字节流、sha、计数
|
||
PAYLOAD = bytes([0xE9]) + os.urandom(200 * 1024)
|
||
SHA = hashlib.sha256(PAYLOAD).hexdigest()
|
||
|
||
ok_count = 0
|
||
|
||
|
||
def step(name: str, cond: bool, extra: str = "") -> None:
|
||
global ok_count
|
||
print(f"[{'PASS' if cond else 'FAIL'}] {name} {extra}")
|
||
if cond:
|
||
ok_count += 1
|
||
else:
|
||
raise SystemExit(f"中止于:{name}")
|
||
|
||
|
||
with httpx.Client(base_url=BASE, timeout=20) as c:
|
||
# ---------------------------------------------------------------- 管理员
|
||
r = c.post("/api/auth/login", json={"account": ADMIN_ACCOUNT, "password": ADMIN_PASSWORD})
|
||
step("admin login", r.status_code == 200, f"{r.status_code}")
|
||
a_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||
|
||
# ---------------------------------------------------------------- 普通用户 + 绑一台假设备
|
||
r = c.post("/api/auth/register", json={"account": ACCOUNT, "password": PASSWORD, "nickname": "OTA冒烟"})
|
||
step("register user", r.status_code == 201, f"{r.status_code}")
|
||
u_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||
|
||
r = c.post("/device/v1/pair/code", json={"chip_id": CHIP, "model": MODEL, "fw_version": "0.1.0"})
|
||
step("device asks code", r.status_code == 200, f"{r.status_code}")
|
||
code = r.json()["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}")
|
||
|
||
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/firmware/check", params={"current": "0.1.0", "lang": "zh"}, headers=d_tok)
|
||
step("check reachable", r.status_code == 200 and "update" in r.json(), r.text[:90])
|
||
print(f" 库里最新已发布:{r.json().get('version') or '(无)'}")
|
||
|
||
# ---------------------------------------------------------------- 上传(先不发布)
|
||
files = {"file": (f"knob_os-{VERSION}.bin", PAYLOAD, "application/octet-stream")}
|
||
data = {
|
||
"version": VERSION,
|
||
"model": MODEL,
|
||
"channel": "stable",
|
||
"notes": "冒烟用固件",
|
||
"notes_en": "smoke firmware",
|
||
"publish": "false",
|
||
}
|
||
r = c.post("/api/admin/firmwares", files=files, data=data, headers=a_tok)
|
||
step("admin upload", r.status_code == 200, f"{r.status_code} {r.text[:120]}")
|
||
|
||
r = c.get("/api/admin/firmwares", headers=a_tok)
|
||
rows = r.json()
|
||
row = next((x for x in rows["items"] if x["version"] == VERSION), None)
|
||
step("uploaded listed", row is not None)
|
||
fw_id = row["id"]
|
||
step("sha matches file", row["sha256"].lower() == SHA, f"{row['sha256'][:12]}… vs {SHA[:12]}…")
|
||
step("size matches file", row["size_bytes"] == len(PAYLOAD), str(row["size_bytes"]))
|
||
step("not published yet", row["published"] is False)
|
||
|
||
# 未发布 → 设备不该看见它(9.9.x 是最高的,一旦可见就会被选中)
|
||
r = c.get("/device/v1/firmware/check", params={"current": "0.1.0"}, headers=d_tok)
|
||
step("unpublished invisible", r.json().get("version") != VERSION, str(r.json().get("version")))
|
||
|
||
# ---------------------------------------------------------------- 发布
|
||
r = c.put(f"/api/admin/firmwares/{fw_id}", json={"published": True}, headers=a_tok)
|
||
step("publish", r.status_code == 200, f"{r.status_code}")
|
||
|
||
r = c.get("/device/v1/firmware/check", params={"current": "0.1.0", "lang": "zh"}, headers=d_tok)
|
||
j = r.json()
|
||
step("check -> update", j["update"] is True, j.get("version", ""))
|
||
step("version correct", j["version"] == VERSION)
|
||
step("size in payload", j["size"] == len(PAYLOAD), str(j["size"]))
|
||
step("sha in payload", j["sha256"].lower() == SHA)
|
||
step("url is relative", j["url"].startswith("/device/v1/firmware/"), j["url"])
|
||
step("reason newer", j["reason"] in ("newer", "forced"), j["reason"])
|
||
|
||
# 同版本 → 不该再推
|
||
r = c.get("/device/v1/firmware/check", params={"current": VERSION}, headers=d_tok)
|
||
step("same version -> no update", r.json()["update"] is False)
|
||
|
||
# ---------------------------------------------------------------- 下载
|
||
r = c.get(j["url"], headers=d_tok)
|
||
step("download 200", r.status_code == 200, f"{r.status_code}")
|
||
body = r.content
|
||
step("download bytes match", body == PAYLOAD, f"{len(body)} bytes")
|
||
step("download sha match", hashlib.sha256(body).hexdigest() == SHA)
|
||
step("x-firmware-version header", r.headers.get("x-firmware-version") == VERSION,
|
||
r.headers.get("x-firmware-version", "-"))
|
||
|
||
# 无 token → 401
|
||
r = c.get(j["url"])
|
||
step("download needs token", r.status_code in (401, 403), f"{r.status_code}")
|
||
|
||
# ---------------------------------------------------------------- 上报成功
|
||
r = c.post("/device/v1/firmware/report",
|
||
json={"version": VERSION, "status": "success", "slot": "app1"}, headers=d_tok)
|
||
step("report success", r.status_code == 200 and r.json()["state"] == "success", r.text[:80])
|
||
|
||
r = c.get("/device/v1/firmware/check", params={"current": VERSION}, headers=d_tok)
|
||
step("after report -> no update", r.json()["update"] is False)
|
||
|
||
# 设备列表里能看到新版本与槽位
|
||
r = c.get("/api/admin/devices/upgrades", headers=a_tok)
|
||
drows = r.json()
|
||
items = drows["items"]
|
||
dev = next((x for x in items if x["chip_id"] == CHIP), None)
|
||
step("device row exists", dev is not None)
|
||
step("device fw_version updated", dev and dev["fw_version"] == VERSION, (dev or {}).get("fw_version", "-"))
|
||
step("device slot recorded", dev and dev["boot_slot"] == "app1", (dev or {}).get("boot_slot", "-"))
|
||
step("upgrade_state success", dev and dev["upgrade_state"] == "success", (dev or {}).get("upgrade_state", "-"))
|
||
|
||
# ---------------------------------------------------------------- 上报失败
|
||
r = c.post("/device/v1/firmware/report",
|
||
json={"version": VERSION, "status": "failed", "error": "sha256 校验失败", "slot": "app1"},
|
||
headers=d_tok)
|
||
step("report failed", r.status_code == 200 and r.json()["state"] == "failed", r.text[:80])
|
||
|
||
# ---------------------------------------------------------------- 点名推送(强制)
|
||
r = c.post(f"/api/admin/devices/{dev['id']}/upgrade",
|
||
json={"firmware_id": fw_id}, headers=a_tok)
|
||
step("force upgrade 200", r.status_code == 200, f"{r.status_code} {r.text[:100]}")
|
||
r = c.get("/device/v1/firmware/check", params={"current": VERSION}, headers=d_tok)
|
||
step("forced even if same version", r.json()["update"] is True and r.json()["mandatory"] is True,
|
||
f"update={r.json().get('update')} mandatory={r.json().get('mandatory')}")
|
||
|
||
# 点名回滚到更低的版本也得能推(compare 会把 lower 判成"不升",点名要绕过它)
|
||
r = c.post(f"/api/admin/firmwares/{fw_id}/rollout",
|
||
json={"firmware_id": fw_id, "device_ids": [dev["id"]]}, headers=a_tok)
|
||
step("rollout ok", r.status_code == 200, r.text[:80])
|
||
|
||
# ---------------------------------------------------------------- 清理
|
||
r = c.delete(f"/api/admin/devices/{dev['id']}/upgrade", headers=a_tok)
|
||
step("cancel target", r.status_code == 200, f"{r.status_code}")
|
||
|
||
r = c.delete(f"/api/admin/firmwares/{fw_id}", headers=a_tok)
|
||
step("cleanup firmware", r.status_code == 200, f"{r.status_code} {r.text[:100]}")
|
||
|
||
print(f"\n全部通过:{ok_count} 项")
|