chore: 首次纳入版本控制(审查前基线,v1.2.0)
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
{"type":"note_card","keyword":"错题本","note_id":"6892b182000000002302734c","xsec_token":"ABtok1","title":"孩子的错题工作台终于可以用了","desc":"拍照收集错题,AI 分析讲解,按遗忘曲线安排复习","note_type":"normal","author_id":"u1001","author_name":"火云智能","liked_count":564,"collected_count":1010,"comment_count":110,"shared_count":32,"publish_time":1762500000000,"ip_location":"福建"}
|
||||
{"type":"note_card","keyword":"错题本","note_id":"69dc5f93000000001b002e03","xsec_token":"ABtok2","title":"小学生错题本高效用法,码住!","desc":"手抄错题的正确姿势","note_type":"normal","author_id":"u1002","author_name":"班主任小林","liked_count":3200,"collected_count":5100,"comment_count":88,"shared_count":210,"publish_time":1762300000000,"ip_location":"浙江"}
|
||||
{"type":"note_detail","keyword":"错题本","note_id":"6892b182000000002302734c","title":"孩子的错题工作台终于可以用了","desc":"拍照收集错题,AI 分析讲解,按遗忘曲线安排复习,连对两次才算过关","author_id":"u1001","author_name":"火云智能","liked_count":564,"collected_count":1010,"comment_count":110,"shared_count":32,"note_type":"normal","publish_time":1762500000000,"ip_location":"福建","tags":["错题本","学习方法","AI工具"],"images":["https://img.example/1.jpg"]}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c001","user_id":"u2001","user_name":"小红薯60C45F83","content":"可以试用吗","like_count":2,"create_time":1762600000000,"ip_location":"重庆"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c002","user_id":"u2002","user_name":"momo","content":"这个7天体验,用完积分再额外花钱买积分??我理解的对吗","like_count":1,"create_time":1762610000000,"ip_location":"浙江"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c003","user_id":"u2003","user_name":"386sx","content":"这么贵","like_count":1,"create_time":1762620000000,"ip_location":"广东"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c004","user_id":"u2004","user_name":"彼岸花","content":"电脑怎么拍试卷","like_count":1,"create_time":1762630000000,"ip_location":"广东"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c005","user_id":"u2005","user_name":"远路","content":"错题可以打印出么?","like_count":1,"create_time":1762640000000,"ip_location":"云南"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c006","user_id":"u2006","user_name":"财貌双全美少女","content":"只能说差生文具多","like_count":1,"create_time":1762650000000,"ip_location":"江苏"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c007","user_id":"u2007","user_name":"小红薯64DE3B46","content":"豆包爱学?","like_count":0,"create_time":1762660000000,"ip_location":"上海"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c008","user_id":"u2008","user_name":"魔丸烤仔一家","content":"只有数学吗?英语语文,小四门可以吗?","like_count":5,"create_time":1762670000000,"ip_location":"北京"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c009","user_id":"u2009","user_name":"知足常乐","content":"全能扫描王平替,终于不用再被收高价会员费了 #小程序搜复盘错题本","like_count":0,"create_time":1762680000000,"ip_location":"浙江"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c010","user_id":"u2010","user_name":"包包璋琅","content":"高中生可以用吗?","like_count":0,"create_time":1762690000000,"ip_location":"浙江"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"6892b182000000002302734c","comment_id":"c011","user_id":"u2011","user_name":"小红薯60C45F83","content":"这个错题本有没有推荐的平替?","like_count":0,"create_time":1762700000000,"ip_location":"重庆"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"69dc5f93000000001b002e03","comment_id":"c012","user_id":"u2012","user_name":"三年级妈妈","content":"手抄太费时间了,一次要四十分钟","like_count":12,"create_time":1762710000000,"ip_location":"江苏"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"69dc5f93000000001b002e03","comment_id":"c013","user_id":"u2013","user_name":"小学数学王老师","content":"我们班要求统一交错题本,家长都在问怎么弄","like_count":30,"create_time":1762720000000,"ip_location":"山东"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"69dc5f93000000001b002e03","comment_id":"c014","user_id":"u2014","user_name":"lily","content":"有没有app推荐,最好是手机能直接拍的","like_count":3,"create_time":1762730000000,"ip_location":"北京"}
|
||||
{"type":"comment","keyword":"错题本","note_id":"69dc5f93000000001b002e03","comment_id":"c015","user_id":"u2015","user_name":"半个柠檬","content":"买了错题打印机,用两次就吃灰了","like_count":8,"create_time":1762740000000,"ip_location":"四川"}
|
||||
@@ -0,0 +1,12 @@
|
||||
{"type":"xy_item","item_id":"880001","keyword":"错题打印机","title":"错题打印机 买了孩子不用 低价出","price":120,"want_count":6,"abandon_hits":"低价出|孩子不用","abandon_count":2,"url":"https://www.goofish.com/item?id=880001","text":"错题打印机 买了孩子不用 低价出"}
|
||||
{"type":"xy_item","item_id":"880002","keyword":"错题打印机","title":"喵喵机 九成新 吃灰 半价","price":180,"want_count":12,"abandon_hits":"吃灰|半价|九成新","abandon_count":3,"url":"https://www.goofish.com/item?id=880002","text":"喵喵机 九成新 吃灰 半价"}
|
||||
{"type":"xy_item","item_id":"880003","keyword":"错题打印机","title":"全新未拆 多买了一个","price":199,"want_count":2,"abandon_hits":"全新未拆","abandon_count":1,"url":"https://www.goofish.com/item?id=880003","text":"全新未拆 多买了一个"}
|
||||
{"type":"xy_item","item_id":"880004","keyword":"错题本","title":"错题本 手写 一本 小学生","price":8,"want_count":1,"abandon_hits":"","abandon_count":0,"url":"https://www.goofish.com/item?id=880004","text":"错题本 手写 一本 小学生"}
|
||||
{"type":"dy_video","video_id":"7300000000000000001","keyword":"错题本","desc":"花两千块买的错题打印机,最后变成了摆设","author_name":"小明妈妈","digg_count":23000,"comment_count":412,"collect_count":1800,"share_count":210,"create_time":1730000000,"url":"https://www.douyin.com/video/7300000000000000001"}
|
||||
{"type":"dy_video","video_id":"7300000000000000002","keyword":"错题本","desc":"手抄错题三年,中考数学从70到110","author_name":"陪读日记","digg_count":51000,"comment_count":1203,"collect_count":9200,"share_count":640,"create_time":1730100000,"url":"https://www.douyin.com/video/7300000000000000002"}
|
||||
{"type":"dy_comment","comment_id":"c9001","video_id":"7300000000000000001","keyword":"错题本","content":"同款,用了两次就吃灰了,主要是我懒得拍照","like_count":1200,"ip_label":"江苏"}
|
||||
{"type":"dy_comment","comment_id":"c9002","video_id":"7300000000000000001","keyword":"错题本","content":"会员太贵了,打印还要另外买纸","like_count":860,"ip_label":"广东"}
|
||||
{"type":"dy_comment","comment_id":"c9003","video_id":"7300000000000000001","keyword":"错题本","content":"孩子根本不配合,拍两张就跑了","like_count":540,"ip_label":"浙江"}
|
||||
{"type":"dy_comment","comment_id":"c9004","video_id":"7300000000000000002","keyword":"错题本","content":"其实直接打印出来贴本子上最有用,不用什么软件","like_count":2100,"ip_label":"山东"}
|
||||
{"type":"dy_comment","comment_id":"c9005","video_id":"7300000000000000002","keyword":"错题本","content":"这个有用吗,感觉是智商税","like_count":330,"ip_label":"河南"}
|
||||
{"type":"dy_comment","comment_id":"c9006","video_id":"7300000000000000002","keyword":"错题本","content":"我都是用excel自己整理,麻烦是麻烦但清楚","like_count":120,"ip_label":"北京"}
|
||||
@@ -0,0 +1,224 @@
|
||||
# -*- 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)
|
||||
|
||||
# 连对两次 → 待讲清 → 讲清通过 → 毕业
|
||||
mid3 = items[2]["id"]
|
||||
call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": "999"}, token)
|
||||
call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": items[2]["answer"]}, token)
|
||||
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)
|
||||
check("周报有数字和一句话", st == 200 and "numbers" in d["data"]
|
||||
and d["data"]["numbers"]["attempts_this_week"] >= 2, d)
|
||||
|
||||
st, d = call(base, "GET", f"/api/print/weekly?child_id={cid}&token={token}")
|
||||
check("周日那张纸是 HTML 且含签字栏/答案折叠", st == 200
|
||||
and "家长签字" in d and "<details>" 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())
|
||||
@@ -0,0 +1,180 @@
|
||||
# -*- 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))
|
||||
|
||||
from http.server import ThreadingHTTPServer # noqa: E402
|
||||
|
||||
from junior import app as japp # noqa: E402
|
||||
from junior import db as dbm # noqa: E402
|
||||
|
||||
TMP = Path(__file__).resolve().parent / "_tmp_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())
|
||||
@@ -0,0 +1,133 @@
|
||||
"""端到端核对:网页登录(手机号 + 验证码)+ 通知列表(临时库、临时端口)。"""
|
||||
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_login.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 = 8033
|
||||
LOG = ROOT / "tests" / "_login_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=55", r["data"]["routes"] == 55, r["data"].get("routes"))
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-code", {"phone": "13800138000"})
|
||||
check("发码 200", st == 200 and r["data"]["sent"] is True, r)
|
||||
code = (r["data"] or {}).get("dev_code") or ""
|
||||
check("发码返回 dev_code(6 位)", len(code) == 6, code)
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-code", {"phone": "13800138000"})
|
||||
check("60 秒内重复发 → 429", st == 429 and r["error"]["code"] == "SMS_TOO_OFTEN", r)
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-code", {"phone": "123"})
|
||||
check("手机号非法 → 400", st == 400 and r["error"]["code"] == "BAD_PHONE", r)
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-login", {"phone": "13800138000", "code": "000000"})
|
||||
check("验证码错 → 400", st == 400 and r["error"]["code"] in ("CODE_WRONG", "CODE_EXPIRED"), r)
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-login", {"phone": "13800138000", "code": code})
|
||||
check("登录 200", st == 200 and bool(r["data"]["token"]), r)
|
||||
tok = r["data"]["token"]
|
||||
check("新用户 needs_consent", r["data"]["needs_consent"] is True, r["data"])
|
||||
check("试用 3 天", (r["data"]["entitlement"] or {}).get("days_left") in (2, 3), r["data"]["entitlement"])
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-login", {"phone": "13800138000", "code": code})
|
||||
check("同一个码第二次 → 400", st == 400, r)
|
||||
|
||||
st, r = call("GET", "/api/me", token=tok)
|
||||
check("带令牌看 /api/me 200", st == 200 and r["data"]["guardian"]["phone"] == "13800138000", r)
|
||||
|
||||
st, r = call("GET", "/api/notifications", token=tok)
|
||||
check("通知列表 200 且为空", st == 200 and r["data"]["items"] == [], r)
|
||||
check("通知列表带 quota", "quota" in (r["data"] or {}), r)
|
||||
|
||||
st, r = call("GET", "/api/notifications")
|
||||
check("未登录看通知 → 401", st == 401, r)
|
||||
|
||||
|
||||
# 一次性门票(小程序 → 工作台免登录)
|
||||
st, r = call("POST", "/api/auth/web-ticket", {"base_url": "http://127.0.0.1:8000"}, tok)
|
||||
check("换门票 200", st == 200 and bool(r["data"]["ticket"]), r)
|
||||
tic = r["data"]["ticket"]
|
||||
check("门票拼了 url", "ticket=" in (r["data"].get("url") or ""), r["data"])
|
||||
st, r = call("POST", "/api/auth/ticket-login", {"ticket": tic})
|
||||
check("门票换登录 200", st == 200 and bool(r["data"]["token"]), r)
|
||||
st, r = call("POST", "/api/auth/ticket-login", {"ticket": tic})
|
||||
check("门票只能用一次 → 401", st == 401, r)
|
||||
st, r = call("POST", "/api/auth/ticket-login", {"ticket": ""})
|
||||
check("空门票 → 400", st == 400, r)
|
||||
|
||||
st, r = call("POST", "/api/auth/sms-login", {"phone": "13900139000", "code": code})
|
||||
check("码不能跨手机号用", st == 400, r)
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=8)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
fh.close()
|
||||
for s in ("", "-wal", "-shm"):
|
||||
p = Path(str(DB) + s)
|
||||
if p.exists():
|
||||
p.unlink()
|
||||
if LOG.exists():
|
||||
LOG.unlink()
|
||||
|
||||
print()
|
||||
print("通过 %d 项,失败 %d 项" % (sum(ok), len(ok) - sum(ok)))
|
||||
sys.exit(0 if all(ok) else 1)
|
||||
@@ -0,0 +1,145 @@
|
||||
"""端到端核对:手输一道题 + 删号冷静期(跑在临时库和临时端口上,不碰演示数据)。"""
|
||||
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=55", r["data"]["routes"] == 55, 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
|
||||
@@ -0,0 +1,578 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""后端测试(标准库 unittest,零依赖)。
|
||||
|
||||
跑:python -m unittest discover -s tests -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import db as dbm # noqa: E402
|
||||
from backend import judging, scheduler # noqa: E402
|
||||
from backend import seed, services as svc # noqa: E402
|
||||
from backend.services import ApiError # noqa: E402
|
||||
|
||||
|
||||
class JudgingTest(unittest.TestCase):
|
||||
def test_calc_ok(self):
|
||||
self.assertEqual(judging.judge_calc("83", "83")[0], True)
|
||||
self.assertEqual(judging.judge_calc("83", " 83 ")[0], True)
|
||||
self.assertEqual(judging.judge_calc("7 × 8", "56")[0], True)
|
||||
self.assertEqual(judging.judge_calc("83", "83")[0], True) # 全角
|
||||
|
||||
def test_calc_wrong(self):
|
||||
ok, detail = judging.judge_calc("83", "38")
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("83", detail)
|
||||
|
||||
def test_calc_refuse(self):
|
||||
"""字写得太糊/算式缺数字 → 拒答(None),不能乱判。"""
|
||||
self.assertIsNone(judging.judge_calc("83", "8?")[0])
|
||||
self.assertIsNone(judging.judge_calc("", "83")[0])
|
||||
|
||||
def test_text(self):
|
||||
self.assertTrue(judging.judge_text("熊猫", "熊猫")[0])
|
||||
ok, detail = judging.judge_text("熊猫", "熊苗")
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("第 2 个字", detail)
|
||||
self.assertFalse(judging.judge_text("熊猫", "熊")[0])
|
||||
self.assertIn("少了第 2 个字", judging.judge_text("熊猫", "熊")[1])
|
||||
|
||||
def test_choice(self):
|
||||
self.assertTrue(judging.judge_choice("再", "再")[0])
|
||||
self.assertFalse(judging.judge_choice("再", "在")[0])
|
||||
|
||||
def test_manual_refuse(self):
|
||||
self.assertIsNone(judging.judge("manual", "x", "y")[0])
|
||||
|
||||
|
||||
class SchedulerTest(unittest.TestCase):
|
||||
def base(self, **kw):
|
||||
d = {"status": "observing", "stage": 0, "wrong_count": 1, "wrong_code": "E4",
|
||||
"created_at": dbm.now(), "explain_fails": 0}
|
||||
d.update(kw)
|
||||
return d
|
||||
|
||||
def test_import_three_times(self):
|
||||
s1 = scheduler.on_import(None)
|
||||
self.assertEqual(s1["status"], "observing")
|
||||
self.assertIsNotNone(s1["next_due"]) # 次日复核
|
||||
s2 = scheduler.on_import({"wrong_count": 1})
|
||||
self.assertEqual((s2["status"], s2["wrong_count"], s2["wrong_code"]), ("observing", 2, "E2"))
|
||||
s3 = scheduler.on_import({"wrong_count": 2})
|
||||
self.assertEqual((s3["status"], s3["wrong_count"]), ("queued", 3))
|
||||
self.assertEqual(s3["next_due"], dbm.today()) # 第三次错,今天就开始
|
||||
|
||||
def test_careless_within_24h(self):
|
||||
s = scheduler.on_attempt(self.base(), True)
|
||||
self.assertEqual(s["status"], "careless")
|
||||
|
||||
def test_later_correct_is_e3(self):
|
||||
old = (dbm.datetime.now(dbm.TZ) - dbm.timedelta(days=3)).isoformat(timespec="seconds")
|
||||
s = scheduler.on_attempt(self.base(created_at=old), True)
|
||||
self.assertEqual((s["status"], s["wrong_code"]), ("queued", "E3"))
|
||||
self.assertEqual(s["interval_days"], 3)
|
||||
|
||||
def test_two_correct_then_explain(self):
|
||||
m = self.base(status="queued")
|
||||
s1 = scheduler.on_attempt(m, True)
|
||||
self.assertEqual((s1["status"], s1["stage"]), ("passed_once", 1))
|
||||
m.update(s1)
|
||||
s2 = scheduler.on_attempt(m, True)
|
||||
self.assertEqual((s2["status"], s2["stage"]), ("to_explain", 2))
|
||||
s3 = scheduler.on_explain(m, True)
|
||||
self.assertEqual(s3["status"], "graduated")
|
||||
|
||||
def test_wrong_resets(self):
|
||||
m = self.base(status="passed_once", stage=1, wrong_count=1)
|
||||
s = scheduler.on_attempt(m, False)
|
||||
self.assertEqual((s["status"], s["stage"]), ("queued", 0))
|
||||
self.assertEqual(s["interval_days"], 1)
|
||||
|
||||
def test_explain_fail_back_to_queue(self):
|
||||
s = scheduler.on_explain(self.base(status="to_explain", stage=2), False)
|
||||
self.assertEqual(s["status"], "queued")
|
||||
self.assertEqual(s["wrong_code"], "E2")
|
||||
self.assertEqual(s["explain_fails"], 1)
|
||||
|
||||
def test_rubric(self):
|
||||
good = "我先算个位,忘了进位,所以少了十。下次先看有没有进位。"
|
||||
self.assertTrue(scheduler.score_explain(good)["passed"])
|
||||
self.assertFalse(scheduler.score_explain("不知道")["passed"])
|
||||
self.assertTrue(scheduler.score_explain("错在进位,下次注意", "three_lines")["passed"])
|
||||
|
||||
|
||||
class ServiceFlowTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmpdir = Path(__file__).resolve().parent / "_tmp"
|
||||
self.tmpdir.mkdir(exist_ok=True)
|
||||
self.path = self.tmpdir / f"t_{id(self)}.db"
|
||||
self.conn = dbm.connect(self.path)
|
||||
dbm.init_db(self.conn)
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
f = Path(str(self.path) + suffix)
|
||||
if f.exists():
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _login(self, code="demo"):
|
||||
return svc.login(self.conn, code)
|
||||
|
||||
def test_login_is_idempotent(self):
|
||||
a = self._login()
|
||||
b = self._login()
|
||||
self.assertEqual(a["guardian_id"], b["guardian_id"])
|
||||
self.assertTrue(a["is_new"])
|
||||
self.assertFalse(b["is_new"])
|
||||
self.assertTrue(b["needs_consent"])
|
||||
|
||||
def test_child_requires_consent(self):
|
||||
gid = self._login()["guardian_id"]
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.create_child(self.conn, gid, "皮皮", 2)
|
||||
self.assertEqual(ctx.exception.code, "NO_CONSENT")
|
||||
svc.give_consent(self.conn, gid)
|
||||
child = svc.create_child(self.conn, gid, "皮皮", 2)
|
||||
self.assertEqual(child["subjects"], ["math", "chinese"])
|
||||
|
||||
def test_full_lifecycle(self):
|
||||
gid = self._login()["guardian_id"]
|
||||
svc.give_consent(self.conn, gid)
|
||||
child = svc.create_child(self.conn, gid, "皮皮", 2)
|
||||
cid = child["id"]
|
||||
paper = svc.create_paper(self.conn, gid, cid, "math")
|
||||
self.assertEqual(len(paper["questions"]), 6)
|
||||
qs = paper["questions"]
|
||||
imp = svc.import_mistakes(self.conn, gid, cid, [q["id"] for q in qs[:3]])
|
||||
self.assertEqual(len(imp["created"]), 3)
|
||||
# 入库当天不进今日队列(观察中,次日复核)
|
||||
q = svc.today_queue(self.conn, gid, cid)
|
||||
self.assertEqual(len(q["items"]), 0)
|
||||
svc.dev_advance(self.conn, 1)
|
||||
q = svc.today_queue(self.conn, gid, cid)
|
||||
self.assertEqual(len(q["items"]), 3)
|
||||
self.assertLessEqual(len(q["items"]), scheduler.DAILY_CAP)
|
||||
# 做对一次 → 不是粗心(超过 24h 判定为「会但不熟」);这里模拟立即对 → 粗心
|
||||
first = q["items"][0]
|
||||
r = svc.attempt(self.conn, gid, cid, first["id"], first["answer"])
|
||||
self.assertTrue(r["correct"])
|
||||
self.assertEqual(r["status"], "careless")
|
||||
# 另一道做错 → 确认没懂,进队列
|
||||
second = q["items"][1]
|
||||
r2 = svc.attempt(self.conn, gid, cid, second["id"], "999")
|
||||
self.assertFalse(r2["correct"])
|
||||
self.assertEqual(r2["status"], "queued")
|
||||
|
||||
def test_explain_graduates(self):
|
||||
gid = self._login()["guardian_id"]
|
||||
svc.give_consent(self.conn, gid)
|
||||
cid = svc.create_child(self.conn, gid, "皮皮", 2)["id"]
|
||||
qs = svc.create_paper(self.conn, gid, cid, "math")["questions"]
|
||||
svc.import_mistakes(self.conn, gid, cid, [qs[0]["id"]])
|
||||
svc.dev_advance(self.conn, 1)
|
||||
item = svc.today_queue(self.conn, gid, cid)["items"][0]
|
||||
svc.attempt(self.conn, gid, cid, item["id"], "999") # 错 → queued
|
||||
r = svc.attempt(self.conn, gid, cid, item["id"], item["answer"])
|
||||
self.assertEqual(r["status"], "passed_once")
|
||||
svc.dev_advance(self.conn, 1)
|
||||
r = svc.attempt(self.conn, gid, cid, item["id"], item["answer"])
|
||||
self.assertTrue(r["need_explain"])
|
||||
e = svc.explain(self.conn, gid, cid, item["id"], "ai_voice",
|
||||
"我先算了个位,忘了进位,所以少了十。下次先看有没有进位。")
|
||||
self.assertTrue(e["passed"])
|
||||
self.assertEqual(e["status"], "graduated")
|
||||
# 毕业后不再进队列
|
||||
svc.dev_advance(self.conn, 10)
|
||||
ids = [x["id"] for x in svc.today_queue(self.conn, gid, cid)["items"]]
|
||||
self.assertNotIn(item["id"], ids)
|
||||
|
||||
def test_refuse_unjudgeable(self):
|
||||
gid = self._login()["guardian_id"]
|
||||
svc.give_consent(self.conn, gid)
|
||||
cid = svc.create_child(self.conn, gid, "皮皮", 2)["id"]
|
||||
qs = svc.create_paper(self.conn, gid, cid, "math")["questions"]
|
||||
svc.import_mistakes(self.conn, gid, cid, [qs[0]["id"]])
|
||||
svc.dev_advance(self.conn, 1)
|
||||
item = svc.today_queue(self.conn, gid, cid)["items"][0]
|
||||
r = svc.attempt(self.conn, gid, cid, item["id"], "8?3")
|
||||
self.assertIsNone(r["correct"])
|
||||
self.assertTrue(r["refused"])
|
||||
|
||||
def test_weekly_and_exports(self):
|
||||
gid = self._login()["guardian_id"]
|
||||
svc.give_consent(self.conn, gid)
|
||||
cid = svc.create_child(self.conn, gid, "皮皮", 2)["id"]
|
||||
qs = svc.create_paper(self.conn, gid, cid, "math")["questions"]
|
||||
svc.import_mistakes(self.conn, gid, cid, [q["id"] for q in qs[:2]])
|
||||
svc.dev_advance(self.conn, 1)
|
||||
item = svc.today_queue(self.conn, gid, cid)["items"][0]
|
||||
svc.attempt(self.conn, gid, cid, item["id"], item["answer"])
|
||||
rep = svc.weekly_report(self.conn, gid, cid)
|
||||
self.assertEqual(rep["numbers"]["attempts_this_week"], 1)
|
||||
self.assertIn("一句话", {"一句话": rep["one_line"]})
|
||||
html = svc.weekly_sheet_html(self.conn, gid, cid)
|
||||
self.assertIn("家长签字", html) # 打印四条硬规则:留答题区/答案折叠
|
||||
self.assertIn("<details>", html)
|
||||
csv_text = svc.export_csv(self.conn, gid, cid)
|
||||
self.assertIn("错题ID", csv_text)
|
||||
|
||||
def test_cross_guardian_isolation(self):
|
||||
g1 = self._login("alpha")["guardian_id"]
|
||||
g2 = self._login("beta")["guardian_id"]
|
||||
svc.give_consent(self.conn, g1)
|
||||
cid = svc.create_child(self.conn, g1, "皮皮", 2)["id"]
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.get_child(self.conn, g2, cid)
|
||||
self.assertEqual(ctx.exception.code, "NO_CHILD")
|
||||
|
||||
def test_delete_child_really_deletes(self):
|
||||
gid = self._login()["guardian_id"]
|
||||
svc.give_consent(self.conn, gid)
|
||||
cid = svc.create_child(self.conn, gid, "皮皮", 2)["id"]
|
||||
qs = svc.create_paper(self.conn, gid, cid, "math")["questions"]
|
||||
svc.import_mistakes(self.conn, gid, cid, [qs[0]["id"]])
|
||||
svc.delete_child(self.conn, gid, cid)
|
||||
n = self.conn.execute("SELECT COUNT(*) c FROM mistakes WHERE child_id=?", (cid,)).fetchone()["c"]
|
||||
self.assertEqual(n, 0)
|
||||
|
||||
def test_tokens(self):
|
||||
gid = self._login()["guardian_id"]
|
||||
t = svc.make_token(gid)
|
||||
self.assertEqual(svc.parse_token(t), gid)
|
||||
with self.assertRaises(ApiError):
|
||||
svc.parse_token(t[:-2] + "xx")
|
||||
ct = svc.make_token("c_123", kind="child", ttl=60)
|
||||
self.assertEqual(svc.parse_token(ct, kind="child"), "c_123")
|
||||
with self.assertRaises(ApiError):
|
||||
svc.parse_token(ct, kind="parent")
|
||||
|
||||
def test_seed_demo(self):
|
||||
info = seed.seed(self.conn)
|
||||
self.assertIn("child_id", info)
|
||||
gid = info["guardian_id"]
|
||||
cid = info["child_id"]
|
||||
q = svc.today_queue(self.conn, gid, cid)
|
||||
self.assertEqual(len(q["items"]), 5)
|
||||
rep = svc.weekly_report(self.conn, gid, cid)
|
||||
self.assertGreater(rep["numbers"]["attempts_this_week"], 0)
|
||||
|
||||
|
||||
class EntitlementTest(unittest.TestCase):
|
||||
"""体验期与激活码:到期只拦「拍新卷子」,不拦已入库错题的复习。"""
|
||||
|
||||
def setUp(self):
|
||||
self.tmpdir = Path(__file__).resolve().parent / "_tmp"
|
||||
self.tmpdir.mkdir(exist_ok=True)
|
||||
self.path = self.tmpdir / f"e_{id(self)}.db"
|
||||
self.conn = dbm.connect(self.path)
|
||||
dbm.init_db(self.conn)
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
f = Path(str(self.path) + suffix)
|
||||
if f.exists():
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _ready(self, code="demo"):
|
||||
d = svc.login(self.conn, code)
|
||||
gid = d["guardian_id"]
|
||||
svc.give_consent(self.conn, gid)
|
||||
cid = svc.create_child(self.conn, gid, "皮皮", 2)["id"]
|
||||
return gid, cid
|
||||
|
||||
def test_new_user_gets_3_day_trial(self):
|
||||
d = svc.login(self.conn, "demo")
|
||||
ent = d["entitlement"]
|
||||
self.assertEqual(ent["kind"], "trial")
|
||||
self.assertTrue(ent["active"])
|
||||
self.assertEqual(ent["days_left"], 3)
|
||||
|
||||
def test_trial_is_not_renewed(self):
|
||||
gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
self.conn.execute("UPDATE entitlements SET expires_at=date('now','-1 day') WHERE guardian_id=?", (gid,))
|
||||
d = svc.login(self.conn, "demo")
|
||||
self.assertFalse(d["entitlement"]["active"])
|
||||
self.assertEqual(d["entitlement"]["days_left"], 0)
|
||||
|
||||
def test_redeem_extends_from_today(self):
|
||||
gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
code = svc.issue_codes(self.conn, 1, "trial7")[0]
|
||||
r = svc.redeem_code(self.conn, gid, code)
|
||||
self.assertEqual(r["days"], 7)
|
||||
# 试用还有 3 天 → 累加到 10 天
|
||||
self.assertEqual(r["entitlement"]["days_left"], 10)
|
||||
|
||||
def test_code_cannot_be_used_twice(self):
|
||||
gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
code = svc.issue_codes(self.conn, 1, "trial7")[0]
|
||||
svc.redeem_code(self.conn, gid, code)
|
||||
gid2 = svc.login(self.conn, "other")["guardian_id"]
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.redeem_code(self.conn, gid2, code)
|
||||
self.assertEqual(ctx.exception.code, "CODE_USED")
|
||||
|
||||
def test_unknown_code(self):
|
||||
gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.redeem_code(self.conn, gid, "QL-NOPE")
|
||||
self.assertEqual(ctx.exception.code, "CODE_NOT_FOUND")
|
||||
|
||||
def test_expired_blocks_new_paper_but_not_review(self):
|
||||
gid, cid = self._ready()
|
||||
qs = svc.create_paper(self.conn, gid, cid, "math")["questions"]
|
||||
svc.import_mistakes(self.conn, gid, cid, [qs[0]["id"]])
|
||||
self.conn.execute("UPDATE entitlements SET expires_at=date('now','-1 day') WHERE guardian_id=?", (gid,))
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.create_paper(self.conn, gid, cid, "math")
|
||||
self.assertEqual(ctx.exception.code, "ENTITLEMENT_EXPIRED")
|
||||
# 已入库的错题仍然能复习
|
||||
svc.dev_advance(self.conn, 1)
|
||||
items = svc.today_queue(self.conn, gid, cid)["items"]
|
||||
self.assertEqual(len(items), 1)
|
||||
r = svc.attempt(self.conn, gid, cid, items[0]["id"], items[0]["answer"])
|
||||
self.assertTrue(r["correct"])
|
||||
|
||||
|
||||
class NotifyOrderTest(unittest.TestCase):
|
||||
"""订阅消息额度制 + 订单/激活码(个人主体没有微信支付)。"""
|
||||
|
||||
def setUp(self):
|
||||
self.tmpdir = Path(__file__).resolve().parent / "_tmp"
|
||||
self.tmpdir.mkdir(exist_ok=True)
|
||||
self.path = self.tmpdir / f"n_{id(self)}.db"
|
||||
self.conn = dbm.connect(self.path)
|
||||
dbm.init_db(self.conn)
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
f = Path(str(self.path) + suffix)
|
||||
if f.exists():
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _ready(self):
|
||||
d = svc.login(self.conn, "demo")
|
||||
gid = d["guardian_id"]
|
||||
svc.give_consent(self.conn, gid)
|
||||
cid = svc.create_child(self.conn, gid, "皮皮", 2)["id"]
|
||||
qs = svc.create_paper(self.conn, gid, cid, "math")["questions"]
|
||||
svc.import_mistakes(self.conn, gid, cid, [q["id"] for q in qs[:2]])
|
||||
svc.dev_advance(self.conn, 1)
|
||||
return gid, cid
|
||||
|
||||
def test_login_reports_wx_mode(self):
|
||||
d = svc.login(self.conn, "demo")
|
||||
self.assertIn(d["wx"]["mode"], ("dev", "live", "half"))
|
||||
|
||||
def test_quota_recorded_per_grant(self):
|
||||
gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
self.assertEqual(svc.subscribe_quota(self.conn, gid)["quota"], 0)
|
||||
q1 = svc.record_subscribe(self.conn, gid, [])
|
||||
self.assertEqual(q1["quota"], 1)
|
||||
q2 = svc.record_subscribe(self.conn, gid, [])
|
||||
self.assertEqual(q2["quota"], 2) # 授权两次 = 两条额度,不累积成「永久」
|
||||
|
||||
def test_tick_without_quota_asks_for_subscribe(self):
|
||||
gid, cid = self._ready()
|
||||
r = svc.notifications_tick(self.conn)
|
||||
self.assertEqual(len(r["queued"]), 0)
|
||||
self.assertTrue(r["need_subscribe"])
|
||||
self.assertIn("额度", r["need_subscribe"][0]["why"])
|
||||
|
||||
def test_tick_consumes_one_grant(self):
|
||||
gid, cid = self._ready()
|
||||
svc.record_subscribe(self.conn, gid, [])
|
||||
r = svc.notifications_tick(self.conn)
|
||||
self.assertEqual(len(r["queued"]), 1)
|
||||
self.assertEqual(r["queued"][0]["channel"], "dev") # 本地模式:记账不真发
|
||||
self.assertEqual(svc.subscribe_quota(self.conn, gid)["quota"], 0) # 发一条扣一条
|
||||
|
||||
def test_tick_second_day_needs_new_grant(self):
|
||||
gid, cid = self._ready()
|
||||
svc.record_subscribe(self.conn, gid, [])
|
||||
svc.notifications_tick(self.conn)
|
||||
self.conn.execute("DELETE FROM attempts") # 让明天也算「没做过」
|
||||
r2 = svc.notifications_tick(self.conn, dbm.add_days(1))
|
||||
self.assertEqual(len(r2["queued"]), 0)
|
||||
self.assertTrue(r2["need_subscribe"])
|
||||
|
||||
def test_order_pay_issues_code_and_redeems(self):
|
||||
gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
o = svc.create_order(self.conn, gid, "term")
|
||||
self.assertEqual(o["amount_cents"], 6900)
|
||||
self.assertFalse(o["pay"]["available"]) # 个人主体开不了支付
|
||||
self.assertEqual(svc.get_order(self.conn, gid, o["id"])["status"], "created")
|
||||
paid = svc.pay_order(self.conn, gid, o["id"])
|
||||
self.assertEqual(paid["status"], "paid")
|
||||
self.assertTrue(paid["code"].startswith("QL-"))
|
||||
# 到账发的码能直接兑换
|
||||
r = svc.redeem_code(self.conn, gid, paid["code"])
|
||||
self.assertEqual(r["days"], 120)
|
||||
# 重复确认不会重复发码
|
||||
again = svc.pay_order(self.conn, gid, o["id"])
|
||||
self.assertTrue(again.get("already"))
|
||||
self.assertEqual(again["code"], paid["code"])
|
||||
|
||||
def test_bad_sku(self):
|
||||
gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.create_order(self.conn, gid, "forever")
|
||||
self.assertEqual(ctx.exception.code, "BAD_SKU")
|
||||
|
||||
def test_pay_notify_without_config(self):
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.pay_notify(self.conn, {}, b"{}")
|
||||
self.assertEqual(ctx.exception.code, "PAY_NOT_CONFIGURED") # 不假装成功
|
||||
|
||||
|
||||
class ManualMistakeTest(unittest.TestCase):
|
||||
"""手输一道题:不拍照,走同一条入库路。"""
|
||||
|
||||
def setUp(self):
|
||||
self.tmpdir = Path(__file__).resolve().parent / "_tmp"
|
||||
self.tmpdir.mkdir(exist_ok=True)
|
||||
self.path = self.tmpdir / f"manual_{id(self)}.db"
|
||||
self.conn = dbm.connect(self.path)
|
||||
dbm.init_db(self.conn)
|
||||
self.gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid)
|
||||
self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
f = Path(str(self.path) + suffix)
|
||||
if f.exists():
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_manual_calc_goes_observing(self):
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", "36 + 47 =", "83")
|
||||
self.assertEqual(r["judge_type"], "calc")
|
||||
self.assertEqual(len(r["created"]), 1)
|
||||
row = self.conn.execute("SELECT * FROM mistakes WHERE child_id=?", (self.cid,)).fetchone()
|
||||
self.assertEqual(row["status"], "observing") # 第一次错只观察,不进队
|
||||
self.assertEqual(row["wrong_count"], 1)
|
||||
paper = self.conn.execute("SELECT * FROM papers WHERE id=?", (r["paper_id"],)).fetchone()
|
||||
self.assertEqual(paper["source"], "manual")
|
||||
self.assertEqual(paper["image_count"], 0)
|
||||
|
||||
def test_manual_choice_requires_letter(self):
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", "7 × 8 =( )",
|
||||
"C", options=["48", "54", "56", "64"])
|
||||
self.assertEqual(r["judge_type"], "choice")
|
||||
self.assertEqual(r["options"], ["48", "54", "56", "64"])
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", "7 × 8 =( )",
|
||||
"56", options=["48", "54", "56", "64"])
|
||||
self.assertEqual(ctx.exception.code, "BAD_ANSWER")
|
||||
|
||||
def test_manual_choice_without_answer_is_self_judge(self):
|
||||
r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "chinese", "选字填空:( )见",
|
||||
None, options=["在", "再"])
|
||||
self.assertEqual(r["judge_type"], "choice")
|
||||
row = self.conn.execute("SELECT * FROM mistakes WHERE child_id=?", (self.cid,)).fetchone()
|
||||
self.assertIsNone(row["answer"])
|
||||
|
||||
def test_manual_blank_stem_rejected(self):
|
||||
with self.assertRaises(ApiError) as ctx:
|
||||
svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", " ")
|
||||
self.assertEqual(ctx.exception.code, "EMPTY_STEM")
|
||||
|
||||
def test_manual_duplicate_updates_not_duplicates(self):
|
||||
svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", "36 + 47 =", "83")
|
||||
for _ in range(2):
|
||||
svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", "36 + 47 =", "83")
|
||||
n = self.conn.execute("SELECT COUNT(*) c FROM mistakes WHERE child_id=?", (self.cid,)).fetchone()["c"]
|
||||
self.assertEqual(n, 1) # 同题只留一条记录
|
||||
row = self.conn.execute("SELECT * FROM mistakes WHERE child_id=?", (self.cid,)).fetchone()
|
||||
self.assertEqual(row["wrong_count"], 3)
|
||||
self.assertEqual(row["status"], "queued") # 错到第三次才进队列
|
||||
|
||||
|
||||
class DeletionGraceTest(unittest.TestCase):
|
||||
"""删号:7 天冷静期,可撤销;到期才真删(级联带走孩子与错题)。"""
|
||||
|
||||
def setUp(self):
|
||||
self.tmpdir = Path(__file__).resolve().parent / "_tmp"
|
||||
self.tmpdir.mkdir(exist_ok=True)
|
||||
self.path = self.tmpdir / f"del_{id(self)}.db"
|
||||
self.conn = dbm.connect(self.path)
|
||||
dbm.init_db(self.conn)
|
||||
self.gid = svc.login(self.conn, "demo")["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid)
|
||||
self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
f = Path(str(self.path) + suffix)
|
||||
if f.exists():
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _sessions(self):
|
||||
return self.conn.execute("SELECT COUNT(*) c FROM sessions WHERE guardian_id=?",
|
||||
(self.gid,)).fetchone()["c"]
|
||||
|
||||
def test_request_kills_sessions_and_sets_purge_date(self):
|
||||
self.assertGreater(self._sessions(), 0)
|
||||
r = svc.request_deletion(self.conn, self.gid, "不想用了")
|
||||
self.assertTrue(r["requested"])
|
||||
self.assertEqual(r["grace_days"], 7)
|
||||
self.assertEqual(self._sessions(), 0) # 立刻踢下线
|
||||
self.assertIsNotNone(svc.deletion_status(self.conn, self.gid))
|
||||
|
||||
def test_cancel_keeps_data(self):
|
||||
svc.request_deletion(self.conn, self.gid)
|
||||
c = svc.cancel_deletion(self.conn, self.gid)
|
||||
self.assertTrue(c["cancelled"])
|
||||
self.assertIsNone(svc.deletion_status(self.conn, self.gid))
|
||||
self.assertIsNotNone(self.conn.execute("SELECT 1 FROM children WHERE id=?",
|
||||
(self.cid,)).fetchone())
|
||||
|
||||
def test_cancel_without_request_is_noop(self):
|
||||
self.assertFalse(svc.cancel_deletion(self.conn, self.gid)["cancelled"])
|
||||
|
||||
def test_purge_before_due_does_nothing(self):
|
||||
svc.request_deletion(self.conn, self.gid)
|
||||
self.assertEqual(svc.purge_due(self.conn)["purged"], 0)
|
||||
|
||||
def test_purge_after_due_removes_everything(self):
|
||||
svc.request_deletion(self.conn, self.gid)
|
||||
# 把到期日改到昨天,模拟 7 天已过
|
||||
self.conn.execute("UPDATE account_deletions SET purge_after=? WHERE guardian_id=?",
|
||||
(dbm.add_days(-1), self.gid))
|
||||
self.assertEqual(svc.purge_due(self.conn)["purged"], 1)
|
||||
for table, col in (("guardians", "id"), ("children", "id"), ("child_subjects", "child_id")):
|
||||
self.assertIsNone(self.conn.execute(
|
||||
f"SELECT 1 FROM {table} WHERE {col}=?", (self.cid if table != "guardians" else self.gid,)
|
||||
).fetchone(), table)
|
||||
self.assertIsNone(self.conn.execute("SELECT 1 FROM account_deletions WHERE guardian_id=?",
|
||||
(self.gid,)).fetchone())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""选择题:题库 → 切题 → 判分 → 接口,一条线都要通。"""
|
||||
import unittest
|
||||
|
||||
from backend import content, cut, judging
|
||||
|
||||
|
||||
class ChoiceBankTest(unittest.TestCase):
|
||||
def test_both_subjects_have_choice(self):
|
||||
for subject in ("math", "chinese"):
|
||||
qs = content.papers_for(2, subject)
|
||||
picks = [q for q in qs if q["judge_type"] == "choice"]
|
||||
self.assertTrue(picks, f"{subject} 题库里没有选择题")
|
||||
for q in picks:
|
||||
self.assertGreaterEqual(len(q["options"]), 2)
|
||||
self.assertIn(q["answer"], "ABCD"[: len(q["options"])])
|
||||
|
||||
def test_only_two_subjects(self):
|
||||
self.assertEqual(content.SUBJECT_ZH, {"math": "数学", "chinese": "语文"})
|
||||
|
||||
|
||||
class ChoiceJudgeTest(unittest.TestCase):
|
||||
def test_letter_forms(self):
|
||||
for given in ("C", "c", "选C", "C. 56", "(C)"):
|
||||
ok, _ = judging.judge("choice", "C", given)
|
||||
self.assertTrue(ok, given)
|
||||
|
||||
def test_wrong_pick(self):
|
||||
ok, detail = judging.judge("choice", "C", "A")
|
||||
self.assertFalse(ok)
|
||||
self.assertIn("应选 C", detail)
|
||||
|
||||
def test_no_pick(self):
|
||||
ok, _ = judging.judge("choice", "C", "")
|
||||
self.assertFalse(ok)
|
||||
|
||||
def test_old_text_answer(self):
|
||||
# 老数据:选字填空的答案存的是文字
|
||||
self.assertTrue(judging.judge("choice", "再", "再")[0])
|
||||
self.assertFalse(judging.judge("choice", "再", "在")[0])
|
||||
|
||||
|
||||
class ChoiceCutTest(unittest.TestCase):
|
||||
def test_options_on_separate_lines(self):
|
||||
lines = [{"text": "1.6 + 6 =( )"}, {"text": "A.10"}, {"text": "B.11"},
|
||||
{"text": "C.12"}, {"text": "D.13"}, {"text": "2.36 + 47 ="}]
|
||||
qs = cut.segment(lines, "math")
|
||||
self.assertEqual(qs[0]["judge_type"], "choice")
|
||||
self.assertEqual(qs[0]["options"], ["10", "11", "12", "13"])
|
||||
self.assertEqual(qs[0]["answer"], "C") # 算出来 12,对到 C
|
||||
self.assertEqual(qs[1]["judge_type"], "calc")
|
||||
|
||||
def test_options_in_one_line(self):
|
||||
lines = [{"text": "3.下面哪个算式的结果最大?( )"},
|
||||
{"text": "A.6×6 B.8×4 C.9×4 D.5×9"}]
|
||||
qs = cut.segment(lines, "math")
|
||||
self.assertEqual(qs[0]["options"], ["6×6", "8×4", "9×4", "5×9"])
|
||||
self.assertEqual(qs[0]["judge_type"], "manual") # 答案没标,交给孩子自评
|
||||
self.assertEqual(qs[0]["stem"], "下面哪个算式的结果最大?( )")
|
||||
|
||||
def test_no_options_still_calc(self):
|
||||
qs = cut.segment([{"text": "1.72-38 ="}], "math")
|
||||
self.assertEqual(qs[0]["judge_type"], "calc")
|
||||
self.assertEqual(qs[0]["answer"], "34")
|
||||
self.assertIsNone(qs[0]["options"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,288 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""初中版后端单元测试:python -m unittest tests.test_junior -v"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from junior import content as ct # noqa: E402
|
||||
from junior import db as dbm # noqa: E402
|
||||
from junior import judging as jd # noqa: E402
|
||||
from junior import scheduler as sc # noqa: E402
|
||||
from junior import services as svc # noqa: E402
|
||||
|
||||
TMP = Path(__file__).resolve().parent / "_tmp_junior"
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
shutil.rmtree(TMP, ignore_errors=True)
|
||||
TMP.mkdir(parents=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(TMP, ignore_errors=True)
|
||||
|
||||
def setUp(self):
|
||||
self.path = TMP / f"{self._testMethodName}.db"
|
||||
for suf in ("", "-wal", "-shm"):
|
||||
Path(str(self.path) + suf).unlink(missing_ok=True)
|
||||
self.conn = dbm.connect(self.path)
|
||||
dbm.init_db(self.conn)
|
||||
d = svc.login_student(self.conn, "stu", "小林", 9)
|
||||
self.sid = d["student"]["id"]
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
# -- helpers
|
||||
def paper(self, subject="math"):
|
||||
return svc.create_paper(self.conn, self.sid, subject)
|
||||
|
||||
def wrong_q(self, subject="math", idx=0):
|
||||
p = self.paper(subject)
|
||||
q = p["questions"][idx]
|
||||
svc.set_verdict(self.conn, self.sid, q["id"], "wrong")
|
||||
return q
|
||||
|
||||
def to_queue(self, qid, times=3):
|
||||
out = None
|
||||
for _ in range(times):
|
||||
out = svc.import_mistakes(self.conn, self.sid, [qid])
|
||||
return out
|
||||
|
||||
|
||||
class TestToken(Base):
|
||||
def test_roundtrip(self):
|
||||
t = svc.make_token("s_abc", "student")
|
||||
self.assertEqual(svc.parse_token(t, "student"), "s_abc")
|
||||
|
||||
def test_wrong_kind(self):
|
||||
t = svc.make_token("s_abc", "guardian")
|
||||
with self.assertRaises(svc.ApiError):
|
||||
svc.parse_token(t, "student")
|
||||
|
||||
def test_tampered(self):
|
||||
t = svc.make_token("s_abc", "student")
|
||||
body, sig = t.split(".")
|
||||
bad = body[:-2] + ("AA" if body[-2:] != "AA" else "BB") + "." + sig
|
||||
with self.assertRaises(svc.ApiError):
|
||||
svc.parse_token(bad, "student")
|
||||
|
||||
|
||||
class TestLogin(Base):
|
||||
def test_first_login_needs_profile(self):
|
||||
with self.assertRaises(svc.ApiError) as cm:
|
||||
svc.login_student(self.conn, "new")
|
||||
self.assertEqual(cm.exception.code, "NEED_PROFILE")
|
||||
|
||||
def test_same_code_same_student(self):
|
||||
a = svc.login_student(self.conn, "x1", "甲", 8)
|
||||
b = svc.login_student(self.conn, "x1", "甲", 8)
|
||||
self.assertEqual(a["student"]["id"], b["student"]["id"])
|
||||
|
||||
def test_grade7_needs_guardian(self):
|
||||
d = svc.login_student(self.conn, "g7", "小七", 7)
|
||||
self.assertTrue(d["needs_guardian"])
|
||||
with self.assertRaises(svc.ApiError) as cm:
|
||||
svc.create_paper(self.conn, d["student"]["id"], "math")
|
||||
self.assertEqual(cm.exception.code, "GUARDIAN_REQUIRED")
|
||||
|
||||
|
||||
class TestGuardian(Base):
|
||||
def test_invite_claim_consent(self):
|
||||
inv = svc.create_invite(self.conn, self.sid)
|
||||
self.assertEqual(len(inv["code"]), 6)
|
||||
c = svc.claim_invite(self.conn, inv["code"], "妈妈")
|
||||
gid = c["guardian_id"]
|
||||
with self.assertRaises(svc.ApiError) as cm:
|
||||
svc.guardian_consent(self.conn, gid, self.sid, "")
|
||||
self.assertEqual(cm.exception.code, "CONSENT_REQUIRED")
|
||||
svc.guardian_consent(self.conn, gid, self.sid, svc.CONSENT_VERSION)
|
||||
self.assertTrue(svc._has_consent(self.conn, self.sid))
|
||||
|
||||
def test_bad_invite(self):
|
||||
with self.assertRaises(svc.ApiError) as cm:
|
||||
svc.claim_invite(self.conn, "000000")
|
||||
self.assertEqual(cm.exception.code, "BAD_INVITE")
|
||||
|
||||
def test_question_needs_grant(self):
|
||||
inv = svc.create_invite(self.conn, self.sid)
|
||||
gid = svc.claim_invite(self.conn, inv["code"], "妈妈")["guardian_id"]
|
||||
q = self.wrong_q()
|
||||
with self.assertRaises(svc.ApiError) as cm:
|
||||
svc.guardian_view_question(self.conn, gid, q["id"])
|
||||
self.assertEqual(cm.exception.code, "NOT_AUTHORIZED")
|
||||
svc.grant_view(self.conn, self.sid, gid, q["id"], 7)
|
||||
view = svc.guardian_view_question(self.conn, gid, q["id"])
|
||||
self.assertEqual(view["question"]["id"], q["id"])
|
||||
|
||||
|
||||
class TestImport(Base):
|
||||
def test_three_times_rule(self):
|
||||
q = self.wrong_q()
|
||||
r1 = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
self.assertEqual(r1["observing"][0]["status"], "observing")
|
||||
r2 = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
self.assertEqual(r2["observing"][0]["repeat"], 2)
|
||||
r3 = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
self.assertEqual(r3["in_queue"][0]["status"], "queued")
|
||||
self.assertEqual(r3["in_queue"][0]["repeat"], 3)
|
||||
|
||||
def test_gap_goes_backlog(self):
|
||||
q = self.wrong_q()
|
||||
r = svc.import_mistakes(self.conn, self.sid, [q["id"]], {q["id"]: "gap"})
|
||||
self.assertEqual(r["backlog"][0]["status"], "backlog")
|
||||
self.assertEqual(len(svc.list_mistakes(self.conn, self.sid)["items"]), 1)
|
||||
|
||||
def test_not_wrong_skipped(self):
|
||||
p = self.paper()
|
||||
q = p["questions"][0]
|
||||
r = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
self.assertTrue(r["skipped"])
|
||||
|
||||
|
||||
class TestFlow(Base):
|
||||
def _mistake(self, status="queued", **kw):
|
||||
q = self.wrong_q()
|
||||
m = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
mid = (m["observing"] or m["in_queue"] or m["backlog"])[0]["id"]
|
||||
self.conn.execute("UPDATE mistakes SET status=?, stage=?, next_due=? WHERE id=?",
|
||||
(status, kw.get("stage", 0), dbm.today(), mid))
|
||||
return mid, q
|
||||
|
||||
def test_observing_right_within_24h_is_careless(self):
|
||||
mid, q = self._mistake("observing")
|
||||
r = svc.attempt(self.conn, self.sid, mid, q["answer"])
|
||||
self.assertTrue(r["correct"])
|
||||
self.assertEqual(r["status"], "careless")
|
||||
|
||||
def test_queued_right_then_recalled(self):
|
||||
mid, q = self._mistake("queued")
|
||||
r = svc.attempt(self.conn, self.sid, mid, q["answer"])
|
||||
self.assertEqual(r["status"], "recalled")
|
||||
|
||||
def test_recalled_right_needs_variant(self):
|
||||
mid, q = self._mistake("recalled", stage=1)
|
||||
r = svc.attempt(self.conn, self.sid, mid, q["answer"])
|
||||
self.assertEqual(r["status"], "variant_pending")
|
||||
|
||||
def test_variant_right_goes_to_explain(self):
|
||||
mid, q = self._mistake("variant_pending", stage=2)
|
||||
v = ct.variant_for(q["knowledge"], q["subject"])
|
||||
r = svc.variant_attempt(self.conn, self.sid, mid, v["answer"])
|
||||
self.assertTrue(r["correct"])
|
||||
self.assertEqual(r["status"], "to_explain")
|
||||
|
||||
def test_variant_wrong_back_to_recalled(self):
|
||||
mid, q = self._mistake("variant_pending", stage=2)
|
||||
r = svc.variant_attempt(self.conn, self.sid, mid, "999")
|
||||
self.assertFalse(r["correct"])
|
||||
self.assertEqual(r["status"], "recalled")
|
||||
|
||||
def test_variant_refused_stays(self):
|
||||
"""判不出来(拒答)时不能当成做错,状态原地不动。"""
|
||||
mid, q = self._mistake("variant_pending", stage=2)
|
||||
r = svc.variant_attempt(self.conn, self.sid, mid, "瞎写")
|
||||
self.assertIsNone(r["correct"])
|
||||
self.assertEqual(r["status"], "variant_pending")
|
||||
|
||||
def test_explain_guard(self):
|
||||
mid, q = self._mistake("recalled", stage=1)
|
||||
with self.assertRaises(svc.ApiError) as cm:
|
||||
svc.explain(self.conn, self.sid, mid, "ai_voice", "错在符号,先移项再合并同类项,下次注意")
|
||||
self.assertEqual(cm.exception.code, "NOT_TO_EXPLAIN")
|
||||
|
||||
def test_explain_pass_graduates(self):
|
||||
mid, q = self._mistake("to_explain", stage=2)
|
||||
r = svc.explain(self.conn, self.sid, mid, "ai_voice",
|
||||
"错在把 2 看成 -2,先移项再合并同类项,下次遇到先抄一遍原式")
|
||||
self.assertTrue(r["passed"])
|
||||
self.assertEqual(r["status"], "graduated")
|
||||
|
||||
def test_explain_fail_tomorrow(self):
|
||||
mid, q = self._mistake("to_explain", stage=2)
|
||||
r = svc.explain(self.conn, self.sid, mid, "three_lines", "不知道")
|
||||
self.assertFalse(r["passed"])
|
||||
self.assertEqual(r["status"], "queued")
|
||||
row = self.conn.execute("SELECT explain_fails, wrong_code FROM mistakes WHERE id=?", (mid,)).fetchone()
|
||||
self.assertEqual(row["explain_fails"], 1)
|
||||
self.assertEqual(row["wrong_code"], "E2")
|
||||
|
||||
def test_daily_cap_six(self):
|
||||
for _ in range(9):
|
||||
q = self.wrong_q("math", 0)
|
||||
m = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
mid = (m["observing"] or m["in_queue"])[0]["id"]
|
||||
self.conn.execute("UPDATE mistakes SET status='queued', next_due=? WHERE id=?", (dbm.today(), mid))
|
||||
self.conn.execute("UPDATE questions SET verdict='wrong' WHERE id<>?", (q["id"],))
|
||||
q2 = svc.today_queue(self.conn, self.sid)
|
||||
self.assertLessEqual(len(q2["items"]), sc.DAILY_CAP)
|
||||
|
||||
def test_sprint_mode(self):
|
||||
svc.update_student(self.conn, self.sid, exam_date=dbm.add_days(10))
|
||||
q = self.wrong_q()
|
||||
m = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
mid = m["observing"][0]["id"]
|
||||
self.conn.execute("UPDATE mistakes SET status='graduated', graduated_at=? WHERE id=?", (dbm.now(), mid))
|
||||
t = svc.today_queue(self.conn, self.sid)
|
||||
self.assertTrue(t["sprint"]["on"])
|
||||
self.assertEqual(t["items"][0]["kind"], "recall")
|
||||
|
||||
|
||||
class TestJudge(unittest.TestCase):
|
||||
def test_calc_ok(self):
|
||||
self.assertEqual(jd.judge("math", "calc", "5", "5")[0], True)
|
||||
|
||||
def test_calc_dirty_refused(self):
|
||||
self.assertIsNone(jd.judge("math", "calc", "8?", "8")[0])
|
||||
|
||||
def test_physics_needs_unit(self):
|
||||
self.assertIsNone(jd.judge("physics", "numeric", "6", "6m/s")[0])
|
||||
|
||||
def test_physics_unit_mismatch_refused(self):
|
||||
self.assertIsNone(jd.judge("physics", "numeric", "6km/h", "6m/s")[0])
|
||||
|
||||
def test_chemistry_case(self):
|
||||
self.assertTrue(jd.judge("chemistry", "text", "h2o", "H2O")[0])
|
||||
|
||||
def test_english_case_and_punct(self):
|
||||
self.assertTrue(jd.judge("english", "text", "Went.", "went")[0])
|
||||
|
||||
def test_english_one_letter_refused(self):
|
||||
self.assertIsNone(jd.judge("english", "text", "wemt", "went")[0])
|
||||
|
||||
def test_choice(self):
|
||||
self.assertTrue(jd.judge("english", "choice", "b", "B")[0])
|
||||
|
||||
def test_manual(self):
|
||||
self.assertIsNone(jd.judge("chinese", "manual", "随便", "答案")[0])
|
||||
|
||||
|
||||
class TestReport(Base):
|
||||
def test_weekly_and_a4(self):
|
||||
q = self.wrong_q()
|
||||
m = svc.import_mistakes(self.conn, self.sid, [q["id"]])
|
||||
mid = m["observing"][0]["id"]
|
||||
svc.attempt(self.conn, self.sid, mid, q["answer"])
|
||||
w = svc.weekly_report(self.conn, self.sid)
|
||||
for k in ("new_this_week", "graduated_this_week", "kill_rate", "in_queue"):
|
||||
self.assertIn(k, w["numbers"])
|
||||
html = svc.a4_sheet_html(self.conn, self.sid)
|
||||
self.assertIn("老师批阅", html)
|
||||
self.assertIn("家长签字", html)
|
||||
|
||||
def test_export_csv(self):
|
||||
self.wrong_q()
|
||||
csv_text = svc.export_csv(self.conn, self.sid)
|
||||
self.assertIn("学科", csv_text.splitlines()[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""知识点编号打通后的回归:题库有 kp、入库带 kp、接口返回 kp。
|
||||
|
||||
kp 是解析模板的索引键。它一旦丢在某一层(题库没标、入库没写、接口没返回),
|
||||
前端就会静默退回通用三步——不报错,但讲得空。所以三层都要钉住。
|
||||
"""
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import content, db, services # noqa: E402
|
||||
|
||||
|
||||
class BankKpTest(unittest.TestCase):
|
||||
def test_every_question_has_kp_key(self):
|
||||
for grade in range(1, 7):
|
||||
for q in content.MATH[grade] + content.CHINESE[grade]:
|
||||
self.assertIn("kp", q, f"这道题没标 kp:{q['stem']}")
|
||||
|
||||
def test_kp_format(self):
|
||||
for grade in range(1, 7):
|
||||
for q in content.MATH[grade]:
|
||||
if q["kp"]:
|
||||
self.assertRegex(q["kp"], r"^M\d{3}$")
|
||||
for q in content.CHINESE[grade]:
|
||||
if q["kp"]:
|
||||
self.assertRegex(q["kp"], r"^C\d{3}$")
|
||||
|
||||
def test_unset_is_none_not_empty_string(self):
|
||||
# 空字符串会让前端 `q.kp && KPT[q.kp]` 走进查表再落空,不如干脆 None
|
||||
for grade in range(1, 7):
|
||||
for q in content.MATH[grade] + content.CHINESE[grade]:
|
||||
self.assertIsNotNone(q["kp"]) if q["kp"] else self.assertIsNone(q["kp"])
|
||||
|
||||
def test_papers_for_keeps_kp(self):
|
||||
qs = content.papers_for(5, "math")
|
||||
self.assertTrue(all(q.get("kp") for q in qs), "五年级数学题应当都有 kp")
|
||||
self.assertEqual(qs[0]["kp"], "M077") # 2.5 × 4
|
||||
|
||||
|
||||
class KpThroughDbTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(__file__).resolve().parent / "_tmp"
|
||||
cls.tmp.mkdir(exist_ok=True)
|
||||
cls.db_path = cls.tmp / "kp.db"
|
||||
cls.conn = db.connect(str(cls.db_path))
|
||||
db.init_db(cls.conn)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.conn.close()
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def setUp(self):
|
||||
db.reset_db(self.conn)
|
||||
self.gid = services.login(self.conn, "demo")["guardian_id"]
|
||||
services.give_consent(self.conn, self.gid, "v1")
|
||||
self.child = services.create_child(self.conn, self.gid, "皮皮", 5)
|
||||
|
||||
def test_question_keeps_kp(self):
|
||||
cid = self.child["id"]
|
||||
paper = services.create_paper(self.conn, self.gid, cid, "math")
|
||||
qs = paper["questions"]
|
||||
self.assertTrue(all(q["kp"] for q in qs))
|
||||
self.assertEqual([q["kp"] for q in qs][:2], ["M077", "M078"])
|
||||
|
||||
def test_mistake_keeps_kp_and_queue_returns_it(self):
|
||||
cid = self.child["id"]
|
||||
paper = services.create_paper(self.conn, self.gid, cid, "chinese")
|
||||
qid = paper["questions"][0]["id"]
|
||||
services.import_mistakes(self.conn, self.gid, cid, [qid])
|
||||
# 第一次错进「观察中」,明天才到期
|
||||
services.dev_advance(self.conn, 1)
|
||||
queue = services.today_queue(self.conn, self.gid, cid)
|
||||
self.assertGreaterEqual(len(queue["items"]), 1)
|
||||
self.assertEqual(queue["items"][0]["kp"], paper["questions"][0]["kp"])
|
||||
|
||||
def test_attempt_returns_kp(self):
|
||||
cid = self.child["id"]
|
||||
paper = services.create_paper(self.conn, self.gid, cid, "math")
|
||||
q = paper["questions"][0]
|
||||
imp = services.import_mistakes(self.conn, self.gid, cid, [q["id"]])
|
||||
mid = imp["created"][0]["mistake_id"]
|
||||
services.dev_advance(self.conn, 1)
|
||||
res = services.attempt(self.conn, self.gid, cid, mid, str(q["answer"]))
|
||||
self.assertEqual(res["kp"], q["kp"])
|
||||
self.assertIsNotNone(res["answer"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,188 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""拍照识题的测试:OCR 文本清洗、切题、以及 OCR 不可用时的退路。
|
||||
|
||||
不依赖真机 OCR:验证「没装语言包 / 图糊」时行为是否诚实(要么退演示题库,要么明确报错)。
|
||||
真机 OCR 的连通性用 `python -m backend.ocr_check 图片路径` 手动验(见 backend/ocr.py)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import cut, ocr # noqa: E402
|
||||
from backend import db as dbm # noqa: E402
|
||||
from backend import services as svc # noqa: E402
|
||||
|
||||
|
||||
def line(text, y=0):
|
||||
return {"text": text, "x": 0, "y": y, "w": 100, "h": 20}
|
||||
|
||||
|
||||
class TidyTest(unittest.TestCase):
|
||||
def test_cjk_spaces_removed(self):
|
||||
self.assertEqual(ocr.tidy("1 . 计 算 : 36 + 47 = ( )"), "1.计算:36 + 47 =()")
|
||||
|
||||
def test_ascii_spaces_kept(self):
|
||||
self.assertEqual(ocr.tidy("72 - 38 = 34"), "72 - 38 = 34")
|
||||
|
||||
def test_empty(self):
|
||||
self.assertEqual(ocr.tidy(" "), "")
|
||||
self.assertEqual(ocr.tidy(" "), "") # 全角空格
|
||||
|
||||
|
||||
class SegmentTest(unittest.TestCase):
|
||||
LINES = [
|
||||
line("姓名:皮皮 班级:二年级三班", 0),
|
||||
line("1 . 计 算 : 36 + 47 = ( )", 30),
|
||||
line("2 . 用 竖 式 计 算 : 72 一 38 = ( )", 80),
|
||||
line("3 . 一 个 长 方 形 长 8 厘 米 , 宽 5 厘 米 , 面 积 是 多 少 ?", 130),
|
||||
line("4 . 看 拼 音 写 词 : x i ó n g m ā o ( )", 180),
|
||||
]
|
||||
|
||||
def test_count_and_seq(self):
|
||||
qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math")
|
||||
self.assertEqual([q["seq"] for q in qs], [1, 2, 3, 4])
|
||||
|
||||
def test_drop_header(self):
|
||||
qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math")
|
||||
self.assertFalse(any("姓名" in q["stem"] for q in qs))
|
||||
|
||||
def test_answers_computed(self):
|
||||
qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math")
|
||||
self.assertEqual(qs[0]["answer"], "83")
|
||||
self.assertEqual(qs[0]["judge_type"], "calc")
|
||||
# OCR 把减号认成一,也要能算对,并且题干显示成减号
|
||||
self.assertEqual(qs[1]["answer"], "34")
|
||||
self.assertIn("72-38", qs[1]["stem"])
|
||||
|
||||
def test_manual_for_word_problems(self):
|
||||
qs = cut.segment([{**l, "text": ocr.tidy(l["text"])} for l in self.LINES], "math")
|
||||
self.assertIsNone(qs[2]["answer"])
|
||||
self.assertEqual(qs[2]["judge_type"], "manual")
|
||||
self.assertEqual(qs[3]["subject"], "chinese")
|
||||
|
||||
def test_section_header_not_a_question(self):
|
||||
qs = cut.segment([line("一、填空"), line("1.3 + 4 =( )")], "math")
|
||||
self.assertEqual(len(qs), 1)
|
||||
self.assertEqual(qs[0]["answer"], "7")
|
||||
|
||||
def test_no_number_no_question(self):
|
||||
self.assertEqual(cut.segment([line("今天作业"), line("自己抄题")], "math"), [])
|
||||
|
||||
|
||||
class FallbackTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmpdir = Path(__file__).resolve().parent / "_tmp"
|
||||
self.tmpdir.mkdir(exist_ok=True)
|
||||
self.path = self.tmpdir / f"t_ocr_{id(self)}.db"
|
||||
self.conn = dbm.connect(self.path)
|
||||
dbm.init_db(self.conn)
|
||||
self.login = svc.login(self.conn, "demo")
|
||||
self.gid = self.login["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
self.child = svc.create_child(self.conn, self.gid, "小测", 3, ["math", "chinese"], "19:30")
|
||||
self.cid = self.child["id"]
|
||||
self._orig = svc.ocr.recognize
|
||||
|
||||
def tearDown(self):
|
||||
svc.ocr.recognize = self._orig
|
||||
self.conn.close()
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
f = Path(str(self.path) + suffix)
|
||||
if f.exists():
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_ocr_down_falls_back_to_demo(self):
|
||||
svc.ocr.recognize = lambda p: {"ok": False, "lines": [], "error": {"code": "NO_ENGINE", "message": "没有语言包"}}
|
||||
paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg",
|
||||
fallback_demo=True)
|
||||
self.assertEqual(paper["source"], "demo")
|
||||
self.assertEqual(paper["ocr"]["reason"], "没有语言包")
|
||||
self.assertTrue(paper["questions"])
|
||||
|
||||
def test_ocr_down_and_no_fallback_raises(self):
|
||||
svc.ocr.recognize = lambda p: {"ok": False, "lines": [], "error": {"code": "NO_ENGINE", "message": "没有语言包"}}
|
||||
with self.assertRaises(svc.ApiError) as ctx:
|
||||
svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg",
|
||||
fallback_demo=False)
|
||||
self.assertEqual(ctx.exception.code, "NO_ENGINE") # 把 OCR 自己的错码透出去,前端好判断
|
||||
|
||||
def test_ocr_ok_creates_real_questions(self):
|
||||
lines = [{"text": t, "x": 0, "y": i * 40, "w": 10, "h": 20}
|
||||
for i, t in enumerate(["1.36 + 47 =( )", "2.一个长方形长 8 厘米,宽 5 厘米,面积是多少?"])]
|
||||
svc.ocr.recognize = lambda p: {"ok": True, "lines": lines, "lang": "zh-Hans-CN"}
|
||||
paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg")
|
||||
self.assertEqual(paper["source"], "ocr")
|
||||
self.assertEqual(len(paper["questions"]), 2)
|
||||
self.assertEqual(paper["questions"][0]["answer"], "83")
|
||||
self.assertEqual(paper["questions"][1]["judge_type"], "manual")
|
||||
|
||||
def test_self_judge_moves_state(self):
|
||||
svc.ocr.recognize = lambda p: {"ok": True, "lines": [{"text": "1.36 + 47 =( )", "x": 0, "y": 0, "w": 1, "h": 1}],
|
||||
"lang": "zh-Hans-CN"}
|
||||
paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", b"fake-jpeg")
|
||||
qid = paper["questions"][0]["id"]
|
||||
imp = svc.import_mistakes(self.conn, self.gid, self.cid, [qid])
|
||||
mid = imp["created"][0]["mistake_id"]
|
||||
r = svc.self_judge(self.conn, self.gid, self.cid, mid, True)
|
||||
self.assertTrue(r["correct"])
|
||||
self.assertIn(r["status"], ("careless", "queued", "recalled"))
|
||||
with self.assertRaises(svc.ApiError):
|
||||
svc.self_judge(self.conn, self.gid, self.cid, mid, True) # 已离开队列
|
||||
|
||||
|
||||
class SmallImageTest(FallbackTest):
|
||||
"""短边 <1200 的图:先警告,别假装认得准。"""
|
||||
|
||||
def _tiny_jpeg(self):
|
||||
try:
|
||||
import io
|
||||
from PIL import Image
|
||||
except Exception:
|
||||
self.skipTest("没有 PIL")
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (400, 520), "white").save(buf, "JPEG")
|
||||
return buf.getvalue()
|
||||
|
||||
def test_small_image_sets_warn(self):
|
||||
svc.ocr.recognize = lambda p: {"ok": True, "width": 400, "height": 520, "ocr_width": 400,
|
||||
"lines": [{"text": "1.36 + 47 =( )", "x": 0, "y": 0, "w": 9, "h": 12}],
|
||||
"lang": "zh-Hans-CN"}
|
||||
paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", self._tiny_jpeg())
|
||||
self.assertTrue(paper["too_small"])
|
||||
self.assertIn("短边不到", paper["ocr"]["warn"])
|
||||
self.assertEqual(paper["ocr"]["size"], {"w": 400, "h": 520})
|
||||
|
||||
def test_big_image_no_warn(self):
|
||||
svc.ocr.recognize = lambda p: {"ok": True, "width": 2000, "height": 3000, "ocr_width": 2000,
|
||||
"lines": [{"text": "1.36 + 47 =( )", "x": 0, "y": 0, "w": 9, "h": 40}],
|
||||
"lang": "zh-Hans-CN"}
|
||||
try:
|
||||
import io
|
||||
from PIL import Image
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (1600, 2000), "white").save(buf, "JPEG")
|
||||
data = buf.getvalue()
|
||||
except Exception:
|
||||
self.skipTest("没有 PIL")
|
||||
paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", data)
|
||||
self.assertFalse(paper["too_small"])
|
||||
self.assertEqual(paper["ocr"]["warn"], "")
|
||||
|
||||
def test_demo_fallback_keeps_warn(self):
|
||||
svc.ocr.recognize = lambda p: {"ok": False, "lines": [], "error": {"code": "OCR_NOISY", "message": "糊"}}
|
||||
paper = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math", self._tiny_jpeg(),
|
||||
fallback_demo=True)
|
||||
self.assertEqual(paper["source"], "demo")
|
||||
self.assertTrue(paper["too_small"])
|
||||
self.assertIn("短边不到", paper["ocr"]["warn"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,134 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""HTTP OCR 后端:用一个本地假服务验证「接外部 OCR」这条路。
|
||||
|
||||
Linux 服务器上没有 Windows OCR,部署时必须靠 OCR_HTTP_URL;这里不测真实服务,
|
||||
只测协议约定与失败退回,保证换任何一家 OCR 都不会把接口打崩。
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import shutil
|
||||
import uuid
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from backend import db, ocr, services # noqa: E402
|
||||
|
||||
LINES = [
|
||||
"1.计算:36 + 47 =( )",
|
||||
"2.用竖式计算:72 - 38 =( )",
|
||||
]
|
||||
|
||||
|
||||
class _Stub(BaseHTTPRequestHandler):
|
||||
fail = False
|
||||
|
||||
def do_POST(self): # noqa: N802
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
body = json.loads(self.rfile.read(n) or b"{}")
|
||||
assert body.get("image_b64"), "应该带图片 base64"
|
||||
if _Stub.fail:
|
||||
self.send_response(500)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"boom")
|
||||
return
|
||||
payload = {"ok": True, "lang": "zh-Hans", "width": 1000, "height": 1400,
|
||||
"lines": [{"text": t, "x": 0, "y": i * 40, "w": 900, "h": 32}
|
||||
for i, t in enumerate(LINES)]}
|
||||
raw = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def log_message(self, *a): # 静音
|
||||
pass
|
||||
|
||||
|
||||
def _png() -> bytes:
|
||||
from PIL import Image
|
||||
im = Image.new("RGB", (900, 300), "white")
|
||||
buf = io.BytesIO()
|
||||
im.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
class HttpOcrTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), _Stub)
|
||||
cls.port = cls.srv.server_address[1]
|
||||
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.srv.shutdown()
|
||||
|
||||
def setUp(self):
|
||||
self._env = os.environ.get("OCR_HTTP_URL")
|
||||
os.environ["OCR_HTTP_URL"] = f"http://127.0.0.1:{self.port}/ocr"
|
||||
os.environ.pop("OCR_HTTP_KEY", None)
|
||||
_Stub.fail = False
|
||||
self.work = ROOT / "tests" / "_tmp_ocr" / uuid.uuid4().hex[:8]
|
||||
self.work.mkdir(parents=True, exist_ok=True)
|
||||
self.img = self.work / "page.png"
|
||||
self.img.write_bytes(_png())
|
||||
self.conn = db.connect(str(self.work / "t.db"))
|
||||
db.init_db(self.conn)
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
shutil.rmtree(self.work, ignore_errors=True)
|
||||
if self._env is None:
|
||||
os.environ.pop("OCR_HTTP_URL", None)
|
||||
else:
|
||||
os.environ["OCR_HTTP_URL"] = self._env
|
||||
|
||||
def test_available_true(self):
|
||||
self.assertTrue(ocr.available())
|
||||
|
||||
def test_recognize_returns_tidied_lines(self):
|
||||
r = ocr.recognize(self.img)
|
||||
self.assertTrue(r["ok"], r)
|
||||
self.assertEqual(len(r["lines"]), 2)
|
||||
self.assertIn("36 + 47", r["lines"][0]["text"])
|
||||
self.assertEqual(r["width"], 1000)
|
||||
|
||||
def test_service_cuts_questions_from_http_ocr(self):
|
||||
g = services.login(self.conn, "demo")["guardian_id"]
|
||||
services.give_consent(self.conn, g, "v1")
|
||||
child = services.create_child(self.conn, g, "皮皮", 2)["id"]
|
||||
paper = services.create_paper_from_image(
|
||||
self.conn, g, child, "math", _png(), filename="page.png", fallback_demo=False)
|
||||
self.assertEqual(paper["source"], "ocr")
|
||||
self.assertGreaterEqual(len(paper["questions"]), 2)
|
||||
stems = " ".join(q["stem"] for q in paper["questions"])
|
||||
self.assertIn("36 + 47", stems)
|
||||
|
||||
def test_http_error_marks_failed(self):
|
||||
_Stub.fail = True
|
||||
r = ocr.recognize(self.img)
|
||||
self.assertFalse(r["ok"])
|
||||
self.assertIn(r["error"]["code"], ("OCR_HTTP_FAILED", "OCR_READ_FAILED"))
|
||||
|
||||
def test_no_fallback_raises_ocr_http_failed(self):
|
||||
_Stub.fail = True
|
||||
g = services.login(self.conn, "demo")["guardian_id"]
|
||||
services.give_consent(self.conn, g, "v1")
|
||||
child = services.create_child(self.conn, g, "皮皮", 2)["id"]
|
||||
with self.assertRaises(services.ApiError) as ctx:
|
||||
services.create_paper_from_image(self.conn, g, child, "math", _png(),
|
||||
filename="page.png", fallback_demo=False)
|
||||
self.assertEqual(ctx.exception.code, "OCR_HTTP_FAILED")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""扫码登录(小程序确认)的测试。
|
||||
|
||||
覆盖:开码 → 待确认 → 手机确认 → 电脑拿到令牌(且只能用一次);
|
||||
过期、错码、重复确认;本地「模拟确认」只认演示账号。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import db as dbm # noqa: E402
|
||||
from backend import seed # noqa: E402
|
||||
from backend import services as svc # noqa: E402
|
||||
from backend.services import ApiError # noqa: E402
|
||||
|
||||
TMP = Path(__file__).resolve().parent / "_tmp_scan"
|
||||
|
||||
|
||||
class ScanBase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
TMP.mkdir(parents=True, exist_ok=True)
|
||||
self.db = TMP / (uuid.uuid4().hex[:8] + ".db")
|
||||
self.conn = dbm.connect(str(self.db))
|
||||
dbm.init_db(self.conn)
|
||||
self.data = seed.seed(self.conn)
|
||||
self.gid = self.data["guardian_id"]
|
||||
|
||||
def tearDown(self):
|
||||
try:
|
||||
self.conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.db.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
shutil.rmtree(TMP, ignore_errors=True)
|
||||
|
||||
|
||||
class ScanFlowTest(ScanBase):
|
||||
def test_start_pending(self):
|
||||
r = svc.scan_start(self.conn, "http://127.0.0.1:8000")
|
||||
self.assertEqual(len(r["code"]), 8)
|
||||
self.assertTrue(r["qr_url"].endswith("code=" + r["code"]))
|
||||
self.assertEqual(r["expires_in"], svc.SCAN_TTL)
|
||||
st = svc.scan_status(self.conn, r["code"])
|
||||
self.assertEqual(st["status"], "pending")
|
||||
self.assertGreater(st["expires_in"], 0)
|
||||
|
||||
def test_confirm_then_token_once(self):
|
||||
r = svc.scan_start(self.conn)
|
||||
code = r["code"]
|
||||
out = svc.scan_confirm(self.conn, self.gid, code)
|
||||
self.assertTrue(out["confirmed"])
|
||||
|
||||
st = svc.scan_status(self.conn, code)
|
||||
self.assertEqual(st["status"], "confirmed")
|
||||
self.assertTrue(st["token"])
|
||||
self.assertGreaterEqual(len(st["children"]), 1)
|
||||
# 令牌是家长的,且会话落库
|
||||
self.assertEqual(svc.parse_token(st["token"], kind="parent"), self.gid)
|
||||
alive = self.conn.execute("SELECT 1 FROM sessions WHERE token=?", (st["token"],)).fetchone()
|
||||
self.assertIsNotNone(alive)
|
||||
|
||||
# 同一个码不能换第二次令牌
|
||||
again = svc.scan_status(self.conn, code)
|
||||
self.assertEqual(again["status"], "consumed")
|
||||
self.assertNotIn("token", again)
|
||||
|
||||
def test_confirm_twice_is_idempotent(self):
|
||||
code = svc.scan_start(self.conn)["code"]
|
||||
svc.scan_confirm(self.conn, self.gid, code)
|
||||
again = svc.scan_confirm(self.conn, self.gid, code)
|
||||
self.assertTrue(again["confirmed"])
|
||||
# 仍然只能在第一次 status 时换到令牌
|
||||
st = svc.scan_status(self.conn, code)
|
||||
self.assertEqual(st["status"], "confirmed")
|
||||
self.assertEqual(svc.scan_status(self.conn, code)["status"], "consumed")
|
||||
|
||||
def test_small_case_code(self):
|
||||
code = svc.scan_start(self.conn)["code"]
|
||||
svc.scan_confirm(self.conn, self.gid, code.lower())
|
||||
self.assertEqual(svc.scan_status(self.conn, code.lower())["status"], "confirmed")
|
||||
|
||||
def test_unknown_code(self):
|
||||
with self.assertRaises(ApiError) as cm:
|
||||
svc.scan_status(self.conn, "ZZZZZZZZ")
|
||||
self.assertEqual(cm.exception.code, "SCAN_NOT_FOUND")
|
||||
with self.assertRaises(ApiError):
|
||||
svc.scan_confirm(self.conn, self.gid, "ZZZZZZZZ")
|
||||
|
||||
def test_expired(self):
|
||||
code = svc.scan_start(self.conn)["code"]
|
||||
self.conn.execute("UPDATE scan_logins SET expires_at=? WHERE code=?", (str(1), code))
|
||||
self.assertEqual(svc.scan_status(self.conn, code)["status"], "expired")
|
||||
with self.assertRaises(ApiError) as cm:
|
||||
svc.scan_confirm(self.conn, self.gid, code)
|
||||
self.assertEqual(cm.exception.code, "SCAN_EXPIRED")
|
||||
|
||||
def test_dev_confirm_binds_demo(self):
|
||||
code = svc.scan_start(self.conn)["code"]
|
||||
out = svc.dev_scan_confirm(self.conn, code)
|
||||
self.assertTrue(out["demo"])
|
||||
st = svc.scan_status(self.conn, code)
|
||||
self.assertEqual(st["status"], "confirmed")
|
||||
self.assertEqual(st["guardian_id"], self.gid)
|
||||
|
||||
def test_codes_are_unique(self):
|
||||
seen = set()
|
||||
for _ in range(30):
|
||||
seen.add(svc.scan_start(self.conn)["code"])
|
||||
self.assertEqual(len(seen), 30)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,164 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""TextIn 手写擦除:接口解析 + 接入拍照入库(全部本地打桩,不消耗额度)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import unittest
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from backend import db as dbm
|
||||
from backend import services as svc
|
||||
from backend import textin
|
||||
|
||||
TMP_ROOT = Path(__file__).resolve().parent / "_tmp_textin"
|
||||
|
||||
|
||||
def _paper_png(w=1600, h=1200, handwriting=True) -> bytes:
|
||||
im = Image.new("RGB", (w, h), "#FCFBF6")
|
||||
d = ImageDraw.Draw(im)
|
||||
d.text((60, 40), "1. 36 + 47 = ( )", fill="#111111")
|
||||
d.text((60, 160), "2. 72 - 38 = ( )", fill="#111111")
|
||||
if handwriting:
|
||||
d.text((520, 40), "83", fill="#27407A")
|
||||
buf = io.BytesIO()
|
||||
im.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
class TextinUnitTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._old = {k: os.environ.get(k) for k in ("TEXTIN_APP_ID", "TEXTIN_SECRET_CODE")}
|
||||
os.environ["TEXTIN_APP_ID"] = "id"
|
||||
os.environ["TEXTIN_SECRET_CODE"] = "sec"
|
||||
|
||||
def tearDown(self):
|
||||
for k, v in self._old.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
def test_mode_live(self):
|
||||
self.assertEqual(textin.mode(), "live")
|
||||
self.assertTrue(textin.available())
|
||||
|
||||
def test_erase_decodes_base64(self):
|
||||
png = _paper_png(300, 200)
|
||||
b64 = base64.b64encode(png).decode()
|
||||
|
||||
def fake(path, data, params=None, timeout=30):
|
||||
self.assertEqual(path, textin.P_ERASE)
|
||||
self.assertEqual(params["image_type"], 1)
|
||||
return {"ok": True, "data": {"image": b64}, "ms": 12}
|
||||
|
||||
old = textin._request
|
||||
textin._request = fake
|
||||
try:
|
||||
r = textin.erase_handwriting(b"x")
|
||||
finally:
|
||||
textin._request = old
|
||||
self.assertTrue(r["ok"])
|
||||
self.assertEqual(r["image"], png)
|
||||
self.assertEqual(r["ms"], 12)
|
||||
|
||||
def test_erase_surfaces_error(self):
|
||||
old = textin._request
|
||||
textin._request = lambda *a, **k: {"ok": False, "code": "TEXTIN_40003", "message": "余额不足"}
|
||||
try:
|
||||
r = textin.erase_handwriting(b"x")
|
||||
finally:
|
||||
textin._request = old
|
||||
self.assertFalse(r["ok"])
|
||||
self.assertEqual(r["code"], "TEXTIN_40003")
|
||||
self.assertIn("余额", r["message"])
|
||||
|
||||
|
||||
class EraseInPipelineTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
TMP_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
self.dir = TMP_ROOT / uuid.uuid4().hex[:8]
|
||||
self.dir.mkdir(parents=True, exist_ok=True)
|
||||
self.conn = dbm.connect(self.dir / "t.db")
|
||||
dbm.init_db(self.conn)
|
||||
g = svc.login(self.conn, "demo")
|
||||
self.gid = g["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
child = svc.create_child(self.conn, self.gid, "皮皮", 2)
|
||||
self.cid = child["id"]
|
||||
self._upload = svc.UPLOAD_DIR
|
||||
svc.UPLOAD_DIR = self.dir / "uploads"
|
||||
self._avail = textin.available
|
||||
self._erase = textin.erase_handwriting
|
||||
self._recognize = svc.ocr.recognize
|
||||
|
||||
def tearDown(self):
|
||||
svc.UPLOAD_DIR = self._upload
|
||||
textin.available = self._avail
|
||||
textin.erase_handwriting = self._erase
|
||||
svc.ocr.recognize = self._recognize
|
||||
try:
|
||||
self.conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
shutil.rmtree(self.dir, ignore_errors=True)
|
||||
|
||||
def _stub_ocr(self, lines):
|
||||
svc.ocr.recognize = lambda path: {
|
||||
"ok": True, "lines": lines, "lang": "zh-Hans",
|
||||
"width": 1600, "height": 1200, "ocr_width": 1600, "scaled": 1.0,
|
||||
}
|
||||
|
||||
def test_erase_runs_and_saves_clean_page(self):
|
||||
textin.available = lambda: True
|
||||
textin.erase_handwriting = lambda data, **kw: {
|
||||
"ok": True, "image": _paper_png(1200, 900, handwriting=False), "ms": 700, "bytes": 1234,
|
||||
}
|
||||
self._stub_ocr([
|
||||
{"text": "1. 36 + 47 = ( )", "x": 60, "y": 40, "w": 400, "h": 34},
|
||||
{"text": "2. 72 - 38 = ( )", "x": 60, "y": 160, "w": 400, "h": 34},
|
||||
])
|
||||
p = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math",
|
||||
_paper_png(1600, 1200), "page.png", fallback_demo=False)
|
||||
self.assertEqual(p["source"], "ocr")
|
||||
self.assertTrue(p["erase"]["used"])
|
||||
self.assertTrue(p["erase"]["ok"])
|
||||
self.assertIn("clean_url", p)
|
||||
row = self.conn.execute("SELECT clean_path FROM papers WHERE id=?", (p["paper"]["id"],)).fetchone()
|
||||
self.assertTrue(row["clean_path"].endswith("_clean.jpg"))
|
||||
clean_file = svc.UPLOAD_DIR / self.cid / f'{p["paper"]["id"]}_clean.jpg'
|
||||
self.assertTrue(clean_file.exists(), f"没落盘:{clean_file}")
|
||||
|
||||
def test_small_image_skips_erase(self):
|
||||
textin.available = lambda: True
|
||||
textin.erase_handwriting = lambda *a, **k: self.fail("小图不该调用擦除")
|
||||
self._stub_ocr([{"text": "1. 36 + 47 = ( )", "x": 10, "y": 10, "w": 300, "h": 12}])
|
||||
p = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math",
|
||||
_paper_png(800, 600), "page.png", fallback_demo=False)
|
||||
self.assertFalse(p["erase"]["used"])
|
||||
self.assertIn("短边", p["erase"]["reason"])
|
||||
self.assertNotIn("clean_url", p)
|
||||
|
||||
def test_erase_failure_leaves_paper_usable(self):
|
||||
textin.available = lambda: True
|
||||
textin.erase_handwriting = lambda *a, **k: {"ok": False, "code": "TEXTIN_40003", "message": "余额不足"}
|
||||
self._stub_ocr([
|
||||
{"text": "1. 36 + 47 = ( )", "x": 60, "y": 40, "w": 400, "h": 34},
|
||||
{"text": "2. 72 - 38 = ( )", "x": 60, "y": 160, "w": 400, "h": 34},
|
||||
])
|
||||
p = svc.create_paper_from_image(self.conn, self.gid, self.cid, "math",
|
||||
_paper_png(1600, 1200), "page.png", fallback_demo=False)
|
||||
self.assertEqual(p["source"], "ocr") # 擦除失败不影响入库
|
||||
self.assertFalse(p["erase"]["ok"])
|
||||
self.assertEqual(p["erase"]["reason"], "余额不足")
|
||||
self.assertNotIn("clean_url", p)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user