# -*- coding: utf-8 -*- """后端全链路自测脚本:短信登录 → 下单(袋/盒) → 支付 → 发货 → DXF/统计。""" import json import random import sys import urllib.request BASE = "http://127.0.0.1:8080" PHONE = "138%08d" % random.randint(0, 99999999) # 每次运行随机手机号,避免触发限流 ok_count = 0 def call(method, path, token=None, body=None, raw=False): req = urllib.request.Request(BASE + path, method=method) req.add_header("Content-Type", "application/json") if token: req.add_header("Authorization", "Bearer " + token) data = json.dumps(body).encode() if body is not None else None try: with urllib.request.urlopen(req, data=data) as resp: payload = resp.read() return resp.status, payload if raw else json.loads(payload) except urllib.error.HTTPError as e: body = e.read() or b"{}" try: return e.code, json.loads(body) except ValueError: return e.code, {"raw": body[:200].decode("utf-8", "replace")} def check(name, cond, extra=""): global ok_count mark = "✓" if cond else "✗" print("[%s] %s %s" % (mark, name, extra)) if cond: ok_count += 1 else: sys.exit(1) # --- 管理员登录 --- st, r = call("POST", "/api/auth/admin/login", body={"username": "admin", "password": "admin123"}) check("管理员登录", st == 200 and r.get("token")) admin = r["token"] st, r = call("POST", "/api/auth/admin/login", body={"username": "admin", "password": "wrong"}) check("错误密码拒绝", st == 401) # --- 短信流程 --- st, r = call("POST", "/api/auth/sms/send", body={"phone": "" + PHONE + ""}) check("发送验证码(demo 返回 code)", st == 200 and r.get("demo") and r.get("code")) code = r["code"] st, r = call("POST", "/api/auth/sms/send", body={"phone": "" + PHONE + ""}) check("60 秒内重发被限流", st == 429) st, r = call("POST", "/api/auth/sms/login", body={"phone": "" + PHONE + "", "code": "000000"}) check("错误验证码拒绝", st == 400) st, r = call("POST", "/api/auth/sms/login", body={"phone": "" + PHONE + "", "code": code}) check("短信登录并注册新用户", st == 200 and r["user"]["role"] == "user") token = r["token"] st, r = call("GET", "/api/auth/me", token=token) check("获取当前用户", st == 200 and r["phone"] == "" + PHONE + "") # --- 纸盒订单(带刀版几何)--- box_body = { "type": "box", "contact": {"name": "测试客户", "phone": "" + PHONE + "", "email": "a@b.c", "address": "上海市黄浦区南京路 1 号", "note": "加急"}, "spec": {"boxNo": "100030", "boxName": "飞机式插锁盒", "structure": "mailer", "w": 120, "d": 80, "h": 180, "material": "card", "materialName": "350g白卡", "qty": 1000}, "quote": {"unit": 3.21, "total": 3210.0}, "summary": "飞机式插锁盒 120x80x180 · 350g白卡 · 1000 件", "design": {"name": "测试纸盒", "faces": {}}, "dieline": { "kind": "box", "size": {"w": 392, "h": 260}, "minX": 0, "minY": 0, "panels": [ {"x": 0, "y": 0, "w": 15, "h": 186, "face": None, "kind": "glue"}, {"x": 15, "y": 0, "w": 184.8, "h": 186, "face": "front", "kind": "body", "holes": [{"x": 50, "y": 20, "r": 4}]}, {"x": 199.8, "y": 0, "w": 122.4, "h": 186, "face": "right", "kind": "body"}, {"poly": [[0, 186], [50, 220], [0, 220]], "face": None, "kind": "flap", "x": 0, "y": 186, "w": 50, "h": 34}, ], "folds": [{"x1": 15, "y1": 0, "x2": 15, "y2": 186}, {"x1": 199.8, "y1": 0, "x2": 199.8, "y2": 186}], "meta": {"boxNo": "100030", "boxName": "飞机式插锁盒", "inner": {"w": 120, "d": 80, "h": 180}, "material": "350g白卡", "thickness": "0.5", "qty": 1000}, }, "previews": {"dieline": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="}, } st, r = call("POST", "/api/orders", token=token, body=box_body) check("创建纸盒订单", st == 200 and r["orderNo"].startswith("PL-"), r.get("orderNo", "")) box_no = r["orderNo"] check("初始状态 待支付/未支付", r["status"] == "pending_payment" and r["payStatus"] == "unpaid") # --- 袋子订单(无刀版,面轮廓)--- bag_body = { "type": "bag", "contact": {"name": "测试客户", "phone": "" + PHONE + "", "address": "北京市朝阳区 8 号", "note": ""}, "spec": {"productId": "standup", "productName": "站立袋", "sizeLabel": "140×210mm", "material": "matte", "materialName": "哑光膜", "finish": "none", "qty": 500}, "quote": {"unit": 3.09, "total": 1545.0}, "summary": "站立袋 140×210 · 哑光膜 · 500 只", "design": {"name": "测试袋子", "sides": {}}, "dieline": {"kind": "bag", "bleed": 3, "faces": [{"key": "front", "w": 140, "h": 210}, {"key": "back", "w": 140, "h": 210}], "meta": {"productName": "站立袋", "material": "哑光膜", "finish": "标准印刷", "qty": 500}}, "previews": {"front": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "back": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="}, } st, r = call("POST", "/api/orders", token=token, body=bag_body) check("创建袋子订单", st == 200, r.get("orderNo", "")) bag_no = r["orderNo"] # 缺地址应被拒绝 bad = dict(bag_body) bad["contact"] = {"name": "x", "phone": "" + PHONE + "", "address": ""} st, r = call("POST", "/api/orders", token=token, body=bad) check("缺少收货地址被拒绝", st == 400) # --- 我的订单 --- st, r = call("GET", "/api/orders/mine", token=token) check("我的订单列表", st == 200 and r["total"] == 2 and len(r["items"]) == 2) st, r = call("GET", "/api/orders/mine/" + bag_no, token=token) check("订单详情含事件", st == 200 and len(r["events"]) == 1 and r["previews"] == ["back", "front"]) # 未登录不可见 st, r = call("GET", "/api/orders/mine/" + bag_no) check("未登录 401", st == 401) # --- 取消(袋子单未支付)--- st, r = call("POST", "/api/orders/mine/%s/cancel" % bag_no, token=token) check("未支付订单取消", st == 200 and r["status"] == "cancelled") # --- 支付(盒子单)--- st, r = call("POST", "/api/orders/mine/%s/pay" % box_no, token=token) check("模拟支付", st == 200 and r["payStatus"] == "paid" and r["status"] == "producing") st, r = call("POST", "/api/orders/mine/%s/pay" % box_no, token=token) check("重复支付被拒绝", st == 400) # --- 管理侧 --- st, r = call("GET", "/api/admin/stats", token=admin) check("统计", st == 200 and r["ordersTotal"] == 2 and r["revenue"] == 3210.0, json.dumps(r, ensure_ascii=False)) st, r = call("GET", "/api/admin/orders?type=box&query=%s" % box_no, token=admin) check("订单筛选查询", st == 200 and r["total"] == 1 and r["items"][0]["ownerPhone"] == "" + PHONE + "") st, r = call("GET", "/api/admin/orders", token=token) check("普通用户访问管理接口 403", st == 403) st, r = call("GET", "/api/admin/orders/" + box_no, token=admin) check("订单详情含设计标记", st == 200 and r["hasDesign"] and r["hasDieline"]) # 发货 st, r = call("POST", "/api/admin/orders/%s/ship" % box_no, token=admin, body={"carrier": "顺丰速运", "tracking_no": "SF123456789"}) check("发货", st == 200 and r["status"] == "shipped" and r["trackingNo"] == "SF123456789" and any(e["kind"] == "logistics" for e in r["events"])) # 完成订单 st, r = call("PATCH", "/api/admin/orders/" + box_no, token=admin, body={"status": "completed"}) check("管理员完成订单", st == 200 and r["status"] == "completed") # 用户侧看到物流 st, r = call("GET", "/api/orders/mine/" + box_no, token=token) check("用户侧查看物流", st == 200 and r["carrier"] == "顺丰速运" and r["trackingNo"] == "SF123456789") # --- DXF 导出(盒 + 袋)--- st, box_dxf = call("GET", "/api/admin/orders/%s/dxf" % box_no, token=admin, raw=True) check("盒订单 DXF 导出", st == 200 and box_dxf.lstrip().startswith(b"0\nSECTION"), "%d bytes" % len(box_dxf)) st, raw = call("GET", "/api/admin/orders/%s/dxf" % bag_no, token=admin, raw=True) check("袋订单 DXF 导出", st == 200 and raw.lstrip().startswith(b"0\nSECTION"), "%d bytes" % len(raw)) # DXF 二次导出命中缓存 st, box_dxf2 = call("GET", "/api/admin/orders/%s/dxf" % box_no, token=admin, raw=True) check("DXF 缓存命中", st == 200 and box_dxf2 == box_dxf) st, prev = call("GET", "/api/admin/orders/%s/dxf-preview" % box_no, token=admin, raw=True) check("盒订单 CAD 预览(SVG)", st == 200 and b"= 0 for e in r.get("events", []))) # 取消分配 st, r = call("PATCH", "/api/admin/orders/" + box_no, token=admin, body={"clear_assignment": True}) check("取消分配", st == 200 and not r["assignedTo"]) st, r = call("GET", "/api/factory/orders", token=hptok) check("取消后工厂不可见", st == 200 and r["total"] == 0) # 重置密码 + 禁用 st, r = call("PATCH", "/api/admin/factory-accounts/%d" % fac2_id, token=admin, body={"password": "new987654"}) check("重置工厂密码", st == 200) st, r = call("POST", "/api/auth/admin/login", body={"username": "hangzhou-print", "password": "new987654"}) check("新密码可登录", st == 200) st, r = call("PATCH", "/api/admin/factory-accounts/%d" % fac2_id, token=admin, body={"status": "disabled"}) check("禁用工厂账号", st == 200 and r["status"] == "disabled") st, r = call("POST", "/api/auth/admin/login", body={"username": "hangzhou-print", "password": "new987654"}) check("禁用后登录被拒", st == 403) call("PATCH", "/api/admin/factory-accounts/%d" % fac2_id, token=admin, body={"status": "active"}) # --- AI 后台配置 --- st, r = call("GET", "/api/admin/ai-config", token=token) check("普通用户访问 AI 配置 403", st == 403) st, r = call("GET", "/api/admin/ai-config", token=admin) check("AI 配置读取(初始)", st == 200 and "apiKeyMasked" in r and r["configured"] is False, json.dumps(r)[:80]) st, r = call("PUT", "/api/admin/ai-config", token=admin, body={"base_url": "https://api.example.com/v1", "model": "test-model", "api_key": "sk-test1234567890abcd"}) check("AI 配置保存", st == 200 and r.get("ok")) st, r = call("GET", "/api/admin/ai-config", token=admin) check("Key 打码回显", st == 200 and r["hasKey"] and r["apiKeyMasked"].startswith("sk-") and "*" in r["apiKeyMasked"] and "test1234567890abcd" not in json.dumps(r), r["apiKeyMasked"]) check("保存后 configured=true", r["configured"] is True) st, r = call("POST", "/api/admin/ai-config/test", token=admin) check("测试连通(假地址失败但不炸)", st == 200 and r.get("ok") is False, str(r.get("error", ""))[:40]) st, r = call("PUT", "/api/admin/ai-config", token=admin, body={"base_url": "notaurl"}) check("非法 URL 被拒", st == 400) # 清空配置恢复未配置状态(api_key 留空不改——直接改库清掉) import pymysql as _p conn = _p.connect(host='127.0.0.1', port=3307, user='root', password='pouchlab', database='pouchlab') cur = conn.cursor() cur.execute("DELETE FROM settings WHERE k LIKE 'ai_%'") conn.commit(); conn.close() import cache as _c _c.client().delete("pl:ai-config") st, r = call("GET", "/api/admin/ai-config", token=admin) check("清空后恢复未配置", r["configured"] is False) # --- AI 排版(额度/门禁;本地未配置 key 走 503 分支) --- st, r = call("GET", "/api/ai/quota") check("AI 未登录 401", st == 401) st, r = call("GET", "/api/ai/quota", token=token) check("AI 额度查询", st == 200 and "left" in r and "configured" in r, json.dumps(r, ensure_ascii=False)[:80]) st, r = call("POST", "/api/ai/layout", token=token, body={"type": "bag", "brief": "测试"}) if ai_unconfigured := (st == 503): check("AI 未配置返回 503", True) else: check("AI 生成(已配置环境)", st in (200, 502), str(st)) st, r = call("POST", "/api/ai/layout", token=token, body={"type": "bag"}) check("空需求被拒", st == 400) # 额度=0 → 403 uid_for_ai = None st, r = call("GET", "/api/admin/users", token=admin) uid_for_ai = r["items"][0]["id"] if r["items"] else None if uid_for_ai: call("PATCH", "/api/admin/users/%d" % uid_for_ai, token=admin, body={"ai_quota": 0}) st, r = call("POST", "/api/ai/layout", token=token, body={"type": "bag", "brief": "x"}) check("额度 0 拒绝(403)", st == 403, r.get("detail", "")[:30]) call("PATCH", "/api/admin/users/%d" % uid_for_ai, token=admin, body={"ai_quota": 20, "ai_used": 5}) st, r = call("GET", "/api/ai/quota", token=token) check("额度重设生效", st == 200 and r["quota"] == 20 and r["used"] == 5, json.dumps(r)[:60]) call("PATCH", "/api/admin/users/%d" % uid_for_ai, token=admin, body={"ai_used": 0}) # --- Agent(首页 AI 设计师) --- st, r = call("POST", "/api/agent/chat", body={"session_id": "e2e-sid-001", "message": "hi"}) check("Agent 未登录 401", st == 401) st, r = call("POST", "/api/agent/chat", token=token, body={"session_id": "bad!id", "message": "hi"}) check("Agent 非法会话 id 400", st == 400) st, r = call("GET", "/api/agent/session/e2e-sid-001/status", token=token) check("Agent 状态轮询(idle)", st == 200 and r.get("status") == "idle") if ai_unconfigured: st, r = call("POST", "/api/agent/chat", token=token, body={"session_id": "e2e-sid-001", "message": "做个袋子"}) check("Agent 未配置 503", st == 503) # --- 用户管理 --- st, r = call("GET", "/api/admin/users?query=%s" % (PHONE[:6]) + "", token=admin) check("用户搜索", st == 200 and r["total"] == 1 and r["items"][0]["orderCount"] == 2) uid = r["items"][0]["id"] st, r = call("PATCH", "/api/admin/users/%d" % uid, token=admin, body={"status": "disabled"}) check("禁用用户", st == 200 and r["status"] == "disabled") st, r = call("GET", "/api/auth/me", token=token) check("被禁用用户请求 403", st == 403) st, r = call("PATCH", "/api/admin/users/%d" % uid, token=admin, body={"status": "active"}) check("恢复用户", st == 200 and r["status"] == "active") st, r = call("GET", "/api/auth/me", token=token) check("恢复后请求正常", st == 200) print("\n全部通过:%d 项" % ok_count)