# -*- coding: utf-8 -*- """HTTP 冒烟测试:真的起一个服务,用 urllib 跑完整流程。 跑:python tests/smoke_http.py """ from __future__ import annotations import json import sys import threading import urllib.error import urllib.request from http.server import ThreadingHTTPServer from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) from backend import db as dbm # noqa: E402 from backend.app import App # noqa: E402 PASS, FAIL = [], [] def call(base, method, path, body=None, token=None): 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, timeout=10) as r: raw = r.read() ctype = r.headers.get("Content-Type", "") return r.status, (json.loads(raw) if "json" in ctype else raw.decode("utf-8")) except urllib.error.HTTPError as e: raw = e.read() try: return e.code, json.loads(raw) except Exception: return e.code, raw.decode("utf-8", "replace") def check(name, cond, extra=""): (PASS if cond else FAIL).append(name) print((" ok " if cond else " FAIL ") + name + ("" if cond else f" <- {extra}")) def main(): db_path = ROOT / "data" / "smoke.db" for suffix in ("", "-wal", "-shm"): p = Path(str(db_path) + suffix) if p.exists(): p.unlink() conn = dbm.connect(db_path) dbm.init_db(conn) conn.close() dbm.DB_PATH = db_path # 让 App 用这个库(App 每次请求都 connect 默认库) httpd = ThreadingHTTPServer(("127.0.0.1", 0), App) port = httpd.server_address[1] threading.Thread(target=httpd.serve_forever, daemon=True).start() base = f"http://127.0.0.1:{port}" print(f"服务已起:{base}") st, d = call(base, "GET", "/api/health") check("GET /api/health 200", st == 200 and d["data"]["ok"] is True, d) st, d = call(base, "GET", "/api/children") check("没登录访问 /api/children 401", st == 401, d) st, d = call(base, "POST", "/api/auth/wx-login", {"code": "demo"}) token = d["data"]["token"] gid = d["data"]["guardian_id"] check("登录返回 token 且 needs_consent", st == 200 and d["data"]["needs_consent"] is True, d) check("新用户自动 3 天试用", d["data"]["entitlement"]["kind"] == "trial" and d["data"]["entitlement"]["days_left"] == 3, d) st, d = call(base, "POST", "/api/dev/issue-codes", {"count": 1, "kind": "trial7"}) code = d["data"]["codes"][0] check("签发激活码", st == 200 and code.startswith("QL-"), d) st, d = call(base, "POST", "/api/entitlement/redeem", {"code": code}, token) check("兑换 +7 天(3+7=10)", st == 200 and d["data"]["entitlement"]["days_left"] == 10, d) st, d = call(base, "POST", "/api/entitlement/redeem", {"code": code}, token) check("同一个码不能兑两次(409)", st == 409 and d["error"]["code"] == "CODE_USED", d) st, d = call(base, "POST", "/api/children", {"nickname": "皮皮", "grade": 2}, token) check("没同意就建档被拒(403 NO_CONSENT)", st == 403 and d["error"]["code"] == "NO_CONSENT", d) st, d = call(base, "POST", "/api/consent", {"version": "v1"}, token) check("监护人同意", st == 200 and d["data"]["consented"] is True, d) st, d = call(base, "POST", "/api/children", {"nickname": "皮皮", "grade": 2, "subjects": ["math", "chinese"]}, token) child = d["data"] cid = child["id"] check("建孩子档案", st == 200 and child["subjects"] == ["math", "chinese"], d) st, d = call(base, "POST", "/api/papers", {"child_id": cid, "subject": "math"}, token) qs = d["data"]["questions"] check("拍作业切出 6 道题", st == 200 and len(qs) == 6, d) st, d = call(base, "POST", "/api/mistakes/import", {"child_id": cid, "question_ids": [q["id"] for q in qs[:3]]}, token) check("入库 3 道(观察中)", st == 200 and len(d["data"]["created"]) == 3, d) st, d = call(base, "GET", f"/api/today?child_id={cid}", None, token) check("当天队列为空(观察中,次日复核)", st == 200 and len(d["data"]["items"]) == 0, d) st, d = call(base, "POST", "/api/dev/advance", {"days": 1}) check("时间快进 1 天", st == 200 and d["data"]["due_now"] >= 3, d) st, d = call(base, "GET", f"/api/today?child_id={cid}", None, token) items = d["data"]["items"] check("今日队列 3 道且不超过上限 5", st == 200 and 1 <= len(items) <= 5, d) mid, ans = items[0]["id"], items[0]["answer"] st, d = call(base, "POST", f"/api/mistakes/{mid}/attempt", {"child_id": cid, "answer": ans}, token) check("做对 → 粗心小记(24h 内)", st == 200 and d["data"]["status"] == "careless", d) mid2 = items[1]["id"] st, d = call(base, "POST", f"/api/mistakes/{mid2}/attempt", {"child_id": cid, "answer": "999"}, token) check("做错 → 确认没懂进队列", st == 200 and d["data"]["status"] == "queued" and d["data"]["correct"] is False, d) st, d = call(base, "POST", f"/api/mistakes/{mid2}/explain", {"child_id": cid, "channel": "ai_voice", "text": "我先算了个位,忘了进位,所以少了十。下次先看有没有进位。"}, token) check("还没连对两次就讲清 → 409", st == 409 and d["error"]["code"] == "NOT_TO_EXPLAIN", d) # 当天错了又对 → 会但不稳 → 隔天再做对 → 已对 1 次 → 再隔天 → 待讲清 → 讲清毕业 mid3 = items[2]["id"] call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": "999"}, token) st, d = call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": items[2]["answer"]}, token) check("当天错了又对 → 会但不稳", st == 200 and d["data"]["status"] == "unstable" and d["data"]["unstable"] is True, d) call(base, "POST", "/api/dev/advance", {"days": 1}) st, d = call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": items[2]["answer"]}, token) check("隔天做对 → 已对 1 次", st == 200 and d["data"]["status"] == "passed_once", d) call(base, "POST", "/api/dev/advance", {"days": 1}) st, d = call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": items[2]["answer"]}, token) check("连对两次 → 待讲清", st == 200 and d["data"]["need_explain"] is True, d) st, d = call(base, "POST", f"/api/mistakes/{mid3}/explain", {"child_id": cid, "channel": "ai_voice", "text": "我先算了个位,忘了进位,所以少了十。下次先看有没有进位。"}, token) check("讲清通过 → 已毕业", st == 200 and d["data"]["passed"] is True and d["data"]["status"] == "graduated", d) st, d = call(base, "GET", f"/api/report/weekly?child_id={cid}", None, token) # 注意:dev_advance 会把 attempts 的日期一起往前挪(不然「当天错了又对」永远成立), # 所以跑到这里,前面的做题记录已经不在本周了。这里只校验结构 + 至少一条记录。 check("周报有数字和一句话", st == 200 and "numbers" in d["data"] and d["data"]["numbers"]["attempts_this_week"] >= 1 and d["data"]["one_line"], d) st, d = call(base, "GET", f"/api/print/weekly?child_id={cid}&token={token}") check("周日那张纸是 HTML 且含签字栏/答案折叠", st == 200 and "家长签字" in d and "
" in d, str(d)[:80]) st, d = call(base, "GET", f"/api/export/csv?child_id={cid}&token={token}") check("导出 CSV 含表头", st == 200 and "错题ID" in d, str(d)[:80]) st, d = call(base, "POST", f"/api/children/{cid}/session", {}, token) ctoken = d["data"]["child_token"] check("签发孩子口答令牌(15 分钟)", st == 200 and d["data"]["expires_in"] == 900, d) st, d = call(base, "GET", "/api/children", None, ctoken) check("孩子令牌不能做家长操作(403)", st == 403, d) st, d = call(base, "GET", "/docs") check("接口文档页 200", st == 200 and "错题毕业" in d, st) # —— 多孩子:一个账号两个娃,数据互相看不见 st, d = call(base, "POST", "/api/children", {"nickname": "朵朵", "grade": 4, "subjects": ["math"]}, token) cid2 = d["data"]["id"] check("新增第二个孩子", st == 200 and cid2 != cid, d) st, d = call(base, "GET", f"/api/today?child_id={cid2}", None, token) check("第二个孩子自己是空的", st == 200 and len(d["data"]["items"]) == 0, d) st, d = call(base, "GET", "/api/children", None, token) check("孩子列表 2 个", st == 200 and len(d["data"]["items"]) == 2, d) # —— 订阅消息:额度制(一次授权一条) st, d = call(base, "GET", "/api/wx/config") check("微信配置可查(个人主体无支付)", st == 200 and d["data"]["pay_enabled"] is False, d) st, d = call(base, "POST", "/api/notify/subscribe", {}, token) check("记一次订阅授权 → 1 条额度", st == 200 and d["data"]["quota"] == 1, d) st, d = call(base, "GET", "/api/notify/quota", None, token) check("查额度 1 条", st == 200 and d["data"]["quota"] == 1, d) # —— 订单:下单 → 人工到账 → 发码 → 兑换 st, d = call(base, "POST", "/api/orders", {"sku": "term"}, token) oid = d["data"]["id"] check("下单 69 元但支付不可用", st == 200 and d["data"]["amount_cents"] == 6900 and d["data"]["pay"]["available"] is False, d) st, d = call(base, "POST", f"/api/orders/{oid}/pay", {}, token) code2 = d["data"]["code"] check("确认到账 → 发出 120 天激活码", st == 200 and d["data"]["status"] == "paid" and code2.startswith("QL-"), d) st, d = call(base, "POST", "/api/entitlement/redeem", {"code": code2}, token) check("订单发的码能兑换", st == 200 and d["data"]["days"] == 120, d) st, d = call(base, "POST", "/api/wechat/pay-notify", {}) check("支付回调未配置时 501(不假装成功)", st == 501 and d["error"]["code"] == "PAY_NOT_CONFIGURED", d) st, d = call(base, "POST", "/api/dev/notify-tick", {}) check("提醒任务可跑", st == 200 and "queued" in d["data"], d) st, d = call(base, "POST", "/api/dev/reseed", {}) check("重置演示数据 → 今日 5 道", st == 200 and d["data"]["mistakes"].get("queued", 0) >= 1, d) st, d = call(base, "POST", "/api/auth/wx-login", {"code": "demo"}) token2 = d["data"]["token"] cid2 = d["data"]["children"][0]["id"] st, d = call(base, "GET", f"/api/today?child_id={cid2}", None, token2) check("演示数据今日正好 5 道", len(d["data"]["items"]) == 5, len(d["data"]["items"])) httpd.shutdown() print() print(f"通过 {len(PASS)} 项,失败 {len(FAIL)} 项") if FAIL: print("失败:", FAIL) return 1 return 0 if __name__ == "__main__": sys.exit(main())