Files
cuotibiye/tests/smoke_manual.py
T

146 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""端到端核对:手输一道题 + 删号冷静期(跑在临时库和临时端口上,不碰演示数据)。"""
import json
import os
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DB = ROOT / "data" / "http_check.db"
for s in ("", "-wal", "-shm"):
p = Path(str(DB) + s)
if p.exists():
p.unlink()
ENV = dict(os.environ, QINGLING_DB=str(DB), PYTHONUTF8="1")
PORT = 8031
LOG = ROOT / "tests" / "_manual_server.log"
fh = open(LOG, "w", encoding="utf-8")
proc = subprocess.Popen([sys.executable, "-m", "backend.app", "--port", str(PORT)],
cwd=str(ROOT), env=ENV,
stdout=fh, stderr=subprocess.STDOUT)
BASE = f"http://127.0.0.1:{PORT}"
def call(method, path, body=None, token=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, 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:
return r.status, json.loads(r.read().decode())
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read().decode())
ok = []
def check(name, cond, extra=""):
ok.append(bool(cond))
print((" ok " if cond else " FAIL ") + name + ("" if cond else " " + str(extra)))
try:
up = False
for _ in range(60):
if proc.poll() is not None:
break
try:
if call("GET", "/api/health")[0] == 200:
up = True
break
except Exception:
time.sleep(0.25)
if not up:
fh.flush()
print("服务没起来,日志:")
print(LOG.read_text(encoding="utf-8", errors="replace")[-2000:])
sys.exit(1)
st, r = call("GET", "/api/health")
check("health 200", st == 200, r)
check("routes=58", r["data"]["routes"] == 58, r["data"].get("routes"))
st, r = call("POST", "/api/auth/wx-login", {"code": "demo"})
tok = r["data"]["token"]
st, r = call("POST", "/api/consent", {"version": "v1"}, tok)
check("同意", st == 200, r)
st, r = call("POST", "/api/children", {"nickname": "皮皮", "grade": 2}, tok)
cid = r["data"]["id"]
check("建档", st == 200 and r["data"]["subjects"] == ["math", "chinese"], r)
# ① 手输一道计算题
st, r = call("POST", "/api/mistakes/manual",
{"child_id": cid, "subject": "math", "stem": "36 + 47 =", "answer": "83"}, tok)
check("手输计算题 200", st == 200, r)
check("判成 calc", r["data"]["judge_type"] == "calc", r["data"])
check("第一次错进观察中", r["data"]["created"][0]["status"] == "observing", r["data"])
# ② 手输一道选择题
st, r = call("POST", "/api/mistakes/manual",
{"child_id": cid, "subject": "math", "stem": "7 × 8 =( )", "answer": "C",
"options": ["48", "54", "56", "64"]}, tok)
check("手输选择题 200", st == 200, r)
check("判成 choice 且带选项", r["data"]["judge_type"] == "choice" and len(r["data"]["options"]) == 4, r["data"])
# ③ 答案不是字母 → 400
st, r = call("POST", "/api/mistakes/manual",
{"child_id": cid, "subject": "math", "stem": "7 × 8 =( )", "answer": "56",
"options": ["48", "54", "56", "64"]}, tok)
check("答案非字母 → BAD_ANSWER", st == 400 and r["error"]["code"] == "BAD_ANSWER", r)
# ④ 题干空 → 400
st, r = call("POST", "/api/mistakes/manual", {"child_id": cid, "subject": "math", "stem": " "}, tok)
check("空题干 → EMPTY_STEM", st == 400 and r["error"]["code"] == "EMPTY_STEM", r)
st, r = call("GET", f"/api/mistakes?child_id={cid}", None, tok)
check("错题本里有 2 道", len(r["data"]["items"]) == 2, len(r["data"]["items"]))
choice = [m for m in r["data"]["items"] if m["judge_type"] == "choice"]
check("接口把选项还原成数组", choice and isinstance(choice[0]["options"], list), choice)
# ⑤ 删号:进冷静期 → 令牌作废 → 重新登录仍能看到 → 撤销
st, r = call("GET", "/api/me", None, tok)
check("初始没有删号记录", r["data"]["deletion"] is None, r["data"])
st, r = call("DELETE", "/api/me", {"reason": "测试"}, tok)
check("申请删号 200", st == 200, r)
check("冷静期 7 天", r["data"]["grace_days"] == 7, r["data"])
purge_after = r["data"]["purge_after"]
st, r = call("GET", "/api/me", None, tok)
check("删号后旧令牌失效 401", st == 401, (st, r))
st, r = call("GET", "/api/health")
check("health 顺手跑 purge(未到期不动)", r["data"]["ok"] is True, r)
st, r = call("POST", "/api/auth/wx-login", {"code": "demo"})
tok2 = r["data"]["token"]
st, r = call("GET", "/api/me", None, tok2)
check("重新登录能看到冷静期", r["data"]["deletion"] and r["data"]["deletion"]["purge_after"] == purge_after, r["data"])
st, r = call("POST", "/api/me/cancel-deletion", {}, tok2)
check("撤销删号", st == 200 and r["data"]["cancelled"] is True, r)
st, r = call("GET", "/api/me", None, tok2)
check("撤销后记录清空", r["data"]["deletion"] is None, r["data"])
st, r = call("GET", f"/api/mistakes?child_id={cid}", None, tok2)
check("撤销后数据还在", len(r["data"]["items"]) == 2, r)
print(f"\n通过 {sum(ok)} 项,失败 {len(ok) - sum(ok)} 项")
sys.exit(0 if all(ok) else 1)
finally:
proc.terminate()
try:
proc.wait(timeout=8)
except subprocess.TimeoutExpired:
proc.kill()
for s in ("", "-wal", "-shm"):
p = Path(str(DB) + s)
if p.exists():
try:
p.unlink()
except OSError:
pass