Files

173 lines
7.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""迷你先修图:图别坏、退一层别退错、没有前置就别瞎给建议。
跑:python -m unittest tests.test_kp_graph -v
"""
from __future__ import annotations
import json
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _tmpdir import workdir as _workdir # noqa: E402
from backend import db as dbm # noqa: E402
from backend import kp_graph # noqa: E402
from backend import services as svc # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
class GraphShapeTest(unittest.TestCase):
def test_validate_is_clean(self):
"""自检要干净:没有未知 id、没有环、前置不比本节点年级高。"""
self.assertEqual(kp_graph.validate(), [])
def test_every_node_exists_in_kpt(self):
"""图里的 id 必须在工作台知识点表里,否则前端取不到名字。"""
kpt = json.loads((ROOT / "prototype" / "workbench" / "kpt.json").read_text(encoding="utf-8"))
topics, _ = kp_graph._load()
missing = sorted(set(topics) - set(kpt))
self.assertEqual(missing, [], f"这些知识点在 kpt.json 里找不到:{missing}")
def test_size_is_mini(self):
"""先修图:1–3 年级已审、4–6 年级是草稿;规模 60–90 个点、80–120 条边。"""
topics, par = kp_graph._load()
self.assertTrue(60 <= len(topics) <= 90, len(topics))
self.assertTrue(80 <= sum(len(v) for v in par.values()) <= 120)
def test_every_edge_has_reason(self):
"""每条边都要写人话理由——家长点开要能看懂「为什么退到这」。"""
_, par = kp_graph._load()
for tid, lst in par.items():
for p in lst:
self.assertTrue(p["reason"].strip(), f"{tid}←{p['id']} 没写理由")
class ParentsTest(unittest.TestCase):
def test_hard_first(self):
ps = kp_graph.parents("M041") # 两位数乘两位数
self.assertEqual(ps[0]["id"], "M039") # 多位数乘一位数
self.assertEqual(ps[0]["strength"], "hard")
def test_filter_by_strength(self):
soft = kp_graph.parents("M044", "soft") # 小数的初步认识
self.assertTrue(soft)
self.assertTrue(all(p["strength"] == "soft" for p in soft))
def test_no_parents_for_root(self):
self.assertEqual(kp_graph.parents("M001"), [])
def test_unknown_kp_is_empty(self):
self.assertEqual(kp_graph.parents("NOPE"), [])
self.assertIsNone(kp_graph.topic("NOPE"))
class RetreatTest(unittest.TestCase):
def test_retreat_points_to_prerequisite(self):
r = kp_graph.retreat("M041")
self.assertEqual(r["step"]["id"], "M039")
self.assertEqual(r["step"]["name"], "多位数乘一位数")
self.assertEqual(r["name"], "两位数乘两位数")
self.assertIn("多位数乘一位数", r["tip"])
self.assertIn("讲不清", r["tip"])
def test_root_has_no_retreat(self):
"""最底层的知识点没有前置,就别给建议(给了也是空话)。"""
self.assertIsNone(kp_graph.retreat("M001"))
self.assertIsNone(kp_graph.retreat(None))
self.assertIsNone(kp_graph.retreat("NOPE"))
def test_chain_is_ordered_from_root(self):
ch = kp_graph.chain("M059") # 三位数乘两位数
self.assertEqual([c["id"] for c in ch], ["M005", "M022", "M039", "M041"])
grades = [c["grade"] for c in ch]
self.assertEqual(grades, sorted(grades))
def test_chain_respects_limit(self):
self.assertLessEqual(len(kp_graph.chain("M059", limit=2)), 2)
class ExplainRetreatTest(unittest.TestCase):
"""讲不清时接口要把「退一层」带出来;讲清了就别带。"""
def setUp(self):
tmp = _workdir("shared")
tmp.mkdir(exist_ok=True)
self.path = tmp / f"kpg_{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, "皮皮", 3)["id"]
svc.add_manual_mistake(self.conn, self.gid, self.cid, "math",
"36 × 24 =", answer="864", kp="M041")
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):
"""连错三次 → 入库;再模拟两天各做对一次 → 到「讲清」。"""
mid = self.conn.execute("SELECT id FROM mistakes WHERE child_id=?", (self.cid,)).fetchone()["id"]
for _ in range(3):
svc.attempt(self.conn, self.gid, self.cid, mid, "800")
for _ in range(2):
self.conn.execute("UPDATE attempts SET created_at=? WHERE mistake_id=?",
(dbm.add_days(-2) + "T20:00:00", mid))
svc.attempt(self.conn, self.gid, self.cid, mid, "864")
svc.dev_advance(self.conn, 2)
row = self.conn.execute("SELECT * FROM mistakes WHERE id=?", (mid,)).fetchone()
return mid, row
def test_failed_explain_carries_retreat(self):
mid, row = self._ready()
self.assertEqual(row["status"], "to_explain")
self.assertEqual(row["kp"], "M041")
r = svc.explain(self.conn, self.gid, self.cid, mid, "steps", "我不会")
self.assertFalse(r["passed"])
self.assertIsNotNone(r["retreat"])
self.assertEqual(r["retreat"]["step"]["id"], "M039")
def test_no_kp_means_no_retreat(self):
"""没有知识点归类的题,不给退一层——宁可不说,也别乱指。"""
svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", "涂一涂", answer="略")
mid = self.conn.execute("SELECT id FROM mistakes WHERE stem=?", ("涂一涂",)).fetchone()["id"]
self.conn.execute("UPDATE mistakes SET status='to_explain', stage=2 WHERE id=?", (mid,))
r = svc.explain(self.conn, self.gid, self.cid, mid, "steps", "我不会")
self.assertFalse(r["passed"])
self.assertIsNone(r["retreat"])
class GraphMissingTest(unittest.TestCase):
"""数据文件缺失时不能 500——「退一层」只是建议。"""
def test_missing_file_degrades_to_empty(self):
import tempfile
from backend import kp_graph
orig = kp_graph.GRAPH_PATH
try:
kp_graph.GRAPH_PATH = Path(tempfile.gettempdir()) / "no_such_kp_graph.json"
kp_graph._load.cache_clear()
self.assertIsNone(kp_graph.topic("M041"))
self.assertEqual(kp_graph.parents("M041"), [])
self.assertIsNone(kp_graph.retreat("M041"))
self.assertEqual(kp_graph.validate(), [])
finally:
kp_graph.GRAPH_PATH = orig
kp_graph._load.cache_clear()
if __name__ == "__main__":
unittest.main()