chore: 首次纳入版本控制(审查前基线,v1.2.0)

This commit is contained in:
errortopic
2026-11-18 20:13:37 +08:00
commit f7b28e1740
441 changed files with 31220 additions and 0 deletions
+578
View File
@@ -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)