# -*- coding: utf-8 -*- """初中版 HTTP 冒烟:真起一个服务,把一整条流程跑一遍。 python tests/smoke_junior.py """ from __future__ import annotations import json import shutil import sys import urllib.error import urllib.request from pathlib import Path from threading import Thread ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(Path(__file__).resolve().parent)) # tests/ 自己 from _tmpdir import workdir as _workdir # noqa: E402 from http.server import ThreadingHTTPServer # noqa: E402 from junior import app as japp # noqa: E402 from junior import db as dbm # noqa: E402 TMP = _workdir("junior_smoke") BASE = None PASS = 0 FAIL = 0 def check(name, cond, extra=""): global PASS, FAIL if cond: PASS += 1 print(f" ok {name}") else: FAIL += 1 print(f" FAIL {name} {extra}") def call(method, path, body=None, token=None, raw=False): url = BASE + path data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(url, data=data, method=method) req.add_header("Content-Type", "application/json") if token: req.add_header("Authorization", "Bearer " + token) try: with urllib.request.urlopen(req, timeout=15) as r: payload = r.read() return r.status, payload if raw else json.loads(payload) except urllib.error.HTTPError as e: payload = e.read() try: return e.code, json.loads(payload) except Exception: # noqa: BLE001 return e.code, {"raw": payload[:200]} def main(): global BASE shutil.rmtree(TMP, ignore_errors=True) TMP.mkdir(parents=True) db_path = TMP / "smoke.db" japp.dbm.DB_PATH = db_path conn = dbm.connect(db_path) dbm.init_db(conn) conn.close() httpd = ThreadingHTTPServer(("127.0.0.1", 0), japp.App) port = httpd.server_address[1] BASE = f"http://127.0.0.1:{port}" Thread(target=httpd.serve_forever, daemon=True).start() print(f"服务已起:{BASE}") try: s, j = call("GET", "/api/health") check("health 200", s == 200 and j["data"]["service"] == "qingling-junior") s, j = call("GET", "/api/me") check("未登录 401", s == 401) s, j = call("POST", "/api/dev/reseed", {}) check("reseed 200", s == 200 and j["data"]["mistakes"] == 10) s, j = call("POST", "/api/auth/student", {"code": "demo"}) check("学生登录 200", s == 200 and j["data"]["student"]["nickname"] == "小林") tok = j["data"]["token"] sid = j["data"]["student"]["id"] s, j = call("GET", "/api/me", token=tok) check("科目 4 个", s == 200 and len(j["data"]["subjects"]) == 4) s, j = call("GET", "/api/today", token=tok) td = j["data"] check("今日队列 ≤6", s == 200 and len(td["items"]) <= 6) check("有 1 道待变式", len(td["variants"]) == 1) check("有 1 道待讲清", len(td["explains"]) == 1) item = td["items"][0] s, j = call("POST", f"/api/mistakes/{item['id']}/attempt", {"answer": item["answer"]}, token=tok) check("作答 200", s == 200 and "status" in j["data"]) ex = td["explains"][0] s, j = call("POST", f"/api/mistakes/{ex['id']}/explain", {"channel": "ai_voice", "text": "错在把符号写反了,先移项再合并同类项,下次先抄原式"}, token=tok) check("讲清通过 → 毕业", s == 200 and j["data"]["passed"] and j["data"]["status"] == "graduated") va = td["variants"][0] s, j = call("POST", f"/api/mistakes/{va['id']}/variant", {"answer": "随便写"}, token=tok) check("变式判不出 → 不判、状态不动", s == 200 and j["data"]["correct"] is None and j["data"]["status"] == "variant_pending") s, j = call("POST", f"/api/mistakes/{va['id']}/variant", {"answer": "999Pa"}, token=tok) check("变式做错 → 回到已对 1 次", s == 200 and j["data"]["status"] == "recalled") s, j = call("GET", "/api/report/weekly", token=tok) check("周报三个数字", s == 200 and {"new_this_week", "graduated_this_week", "kill_rate"} <= set(j["data"]["numbers"])) s, payload = call("GET", f"/api/print/a4?token={tok}", raw=True) text = payload.decode("utf-8") check("A4 含签字栏", s == 200 and "老师批阅" in text and "家长签字" in text) s, payload = call("GET", f"/api/export/csv?token={tok}", raw=True) check("CSV 含表头", s == 200 and "学科" in payload.decode("utf-8-sig")[:200]) s, j = call("POST", "/api/invite", {}, token=tok) code = j["data"]["code"] check("生成 6 位邀请码", s == 200 and len(code) == 6) s, j = call("POST", "/api/auth/guardian", {"code": code, "nickname": "妈妈"}) check("家长绑定 200", s == 200 and j["data"]["student_id"] == sid) gtok = j["data"]["token"] gid = j["data"]["guardian_id"] s, j = call("POST", "/api/g/consent", {"student_id": sid, "version": ""}, token=gtok) check("同意必须带版本 400", s == 400 and j["error"]["code"] == "CONSENT_REQUIRED") s, j = call("POST", "/api/g/consent", {"student_id": sid, "version": "junior-2026-11"}, token=gtok) check("监护人同意 200", s == 200) s, j = call("GET", f"/api/g/report?student_id={sid}", token=gtok) check("家长看周报 200", s == 200 and "numbers" in j["data"]) qid = item["question_id"] s, j = call("GET", f"/api/g/question/{qid}", token=gtok) check("未授权看原题 403", s == 403 and j["error"]["code"] == "NOT_AUTHORIZED") s, j = call("POST", "/api/share-grants", {"guardian_id": gid, "question_id": qid, "days": 7}, token=tok) check("学生授权 200", s == 200 and j["data"]["id"]) s, j = call("GET", f"/api/g/question/{qid}", token=gtok) check("授权后能看原题", s == 200 and j["data"]["question"]["id"] == qid) s, j = call("GET", "/api/today", token=gtok) check("家长令牌打学生接口 403", s == 403 and j["error"]["code"] == "GUARDIAN_TOKEN") s, j = call("GET", f"/api/g/children", token=tok) check("学生令牌打家长接口 403", s == 403 and j["error"]["code"] == "STUDENT_TOKEN") s, j = call("POST", "/api/dev/notify-tick", {}) check("提醒 200", s == 200 and "sent" in j["data"]) s, j = call("POST", "/api/dev/advance", {"days": 1}) check("时间快进 200", s == 200) s, payload = call("GET", "/docs", raw=True) check("/docs 200", s == 200 and b"/api/today" in payload) s, j = call("GET", "/api/stats", token=tok) check("统计 200", s == 200 and "kill_rate" in j["data"]) finally: httpd.shutdown() shutil.rmtree(TMP, ignore_errors=True) print(f"\n{'=' * 40}\n通过 {PASS} 项,失败 {FAIL} 项\n{'=' * 40}") return 0 if FAIL == 0 else 1 if __name__ == "__main__": sys.exit(main())