Files
cuotibiye/tests/test_scan_flow.py
T

199 lines
8.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""整页拍 → 点选 → 入库(scanflow)的单元测试。
腾讯云不在这里真调:把它 mock 成固定返回,只验证我们自己的逻辑——
框过滤、只入库选中的块、空 picks 报错、草稿不存在报错。
"""
import json
import unittest
from pathlib import Path
from unittest import mock
from backend import db as dbm
from backend import scanflow, services as svc
from backend.services import ApiError
from ._tmpdir import workdir
# 1 张 200x300 的纯色图就够了,识别被 mock 掉
def _png_bytes(w=200, h=300):
from PIL import Image
import io
buf = io.BytesIO()
Image.new("RGB", (w, h), (250, 250, 250)).save(buf, "PNG")
return buf.getvalue(), f"t{w}.png"
def _fake_split(image, *a, **kw):
return {
"ok": True,
"questions": [
{
"stem": "1. 计算:36 + 47 =()",
"judge_type": "calc",
"detected_as": "calc",
"answer": "83",
"page_answer": None,
"options": None,
"box": {"x": 10, "y": 10, "w": 160, "h": 60},
},
{
"stem": "2. 一个长方形长 8 厘米,宽 5 厘米,面积是多少?",
"judge_type": "manual",
"detected_as": "manual",
"answer": None,
"page_answer": "40 平方厘米",
"options": None,
"box": {"x": 10, "y": 90, "w": 160, "h": 60},
},
{
# 太小,应当被丢掉
"stem": "3. 边角料",
"judge_type": "manual",
"detected_as": "manual",
"answer": None,
"page_answer": None,
"options": None,
"box": {"x": 10, "y": 160, "w": 12, "h": 12},
},
],
}
class ScanFlowTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = workdir("scanflow")
cls.db = cls.dir / "scan.db"
def setUp(self):
if self.db.exists():
self.db.unlink()
self.conn = dbm.connect(self.db)
dbm.init_db(self.conn)
lg = svc.login(self.conn, "demo")
self.gid = lg["guardian_id"]
svc.give_consent(self.conn, self.gid, "v1")
self.cid = svc.create_child(self.conn, self.gid, "小满", 5)["id"]
def tearDown(self):
self.conn.close()
def _detect(self):
raw, name = _png_bytes()
with mock.patch.object(scanflow.tencent_ocr, "split_questions", _fake_split):
return scanflow.detect(raw, name)
def test_detect_drops_tiny_block(self):
d = self._detect()
self.assertEqual(len(d["blocks"]), 2, "12x12 的小框应当被过滤")
self.assertEqual(d["width"], 200)
self.assertTrue(all(b["box"]["w"] >= scanflow.MIN_BOX_SIDE for b in d["blocks"]))
meta = Path(scanflow.DRAFT_DIR) / f"{d['draft_id']}.json"
self.assertTrue(meta.exists())
def test_import_only_picked(self):
d = self._detect()
with mock.patch.object(scanflow.tencent_ocr, "split_questions", _fake_split):
paper = svc.import_scan_picks(
self.conn, self.gid, self.cid, "math", d["draft_id"], [1]
)
self.assertEqual(len(paper["questions"]), 1)
q = paper["questions"][0]
self.assertIn("长方形", q["stem"])
self.assertEqual(paper["ocr"]["picked"], 1)
# 入库即「观察中」:今天不复习,明天才进队列
rows = self.conn.execute(
"SELECT stem, status FROM mistakes WHERE child_id=?", (self.cid,)
).fetchall()
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["status"], "observing")
self.assertIn("长方形", rows[0]["stem"])
self.assertEqual(svc.today_queue(self.conn, self.gid, self.cid)["items"], [])
def test_empty_picks_rejected(self):
d = self._detect()
with self.assertRaises(ApiError) as ctx:
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", d["draft_id"], [])
self.assertEqual(ctx.exception.status, 400)
self.assertEqual(ctx.exception.code, "NO_PICKS")
def test_unknown_draft(self):
with self.assertRaises(ApiError) as ctx:
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", "deadbeefdeadbeef", [0])
self.assertEqual(ctx.exception.status, 404)
self.assertEqual(ctx.exception.code, "DRAFT_NOT_FOUND")
def test_picks_out_of_range_ignored(self):
d = self._detect()
with self.assertRaises(ApiError) as ctx:
svc.import_scan_picks(self.conn, self.gid, self.cid, "math", d["draft_id"], [9, 10])
self.assertEqual(ctx.exception.code, "NO_PICKS")
def test_multi_question_block_expands(self):
"""勾一块竖式区(6 行),应当入库 6 道,不是 1 道。"""
d = self._detect()
subs = [{"stem": f"{e} =", "answer": a, "judge_type": "calc"}
for e, a in [("1.8+0.6", "2.4"), ("6.5-2.9", "3.6"), ("40×65", "2600")]]
block = d["blocks"][0]
with mock.patch.object(
scanflow, "recognize_block",
return_value={"stem": "1.8+0.6\n6.5-2.9\n40×65", "judge_type": "card",
"options": None, "answer": None, "page_answer": None,
"source": "page", "subs": subs},
):
paper = svc.import_scan_picks(
self.conn, self.gid, self.cid, "math", d["draft_id"], [block["i"]]
)
self.assertEqual(len(paper["questions"]), 3)
self.assertEqual(paper["ocr"]["picked"], 1, "调用方勾的是 1 块")
got = [r["stem"] for r in self.conn.execute(
"SELECT stem FROM mistakes WHERE child_id=? ORDER BY id", (self.cid,))]
self.assertEqual(len(got), 3)
self.assertTrue(any("40×65" in s for s in got))
if __name__ == "__main__":
unittest.main()
class NoWastefulCropTest(unittest.TestCase):
"""整页读得够好的块,不该再花钱裁出来识别第二次。"""
def test_complete_block_skips_crop(self):
from backend import scanflow
block = {"i": 0, "box": {"x": 10, "y": 10, "w": 300, "h": 200},
"stem": "小明有 12 个苹果,给了小红 5 个,还剩多少个?",
"judge_type": "manual", "options": None, "page_answer": "", "subs": []}
with mock.patch("backend.tencent_ocr.split_questions") as sp:
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
sp.assert_not_called()
self.assertEqual(r["source"], "page")
self.assertIn("苹果", r["stem"])
def test_broken_block_still_crops(self):
from backend import scanflow
block = {"i": 0, "box": {"x": 10, "y": 10, "w": 300, "h": 200},
"stem": "1、", "judge_type": "manual", "options": None,
"page_answer": "", "subs": []}
with mock.patch("backend.scanflow._crop_bytes", return_value=b"jpg"), \
mock.patch("backend.tencent_ocr.split_questions",
return_value={"ok": True, "questions": [
{"stem": "1、6+5-10=", "judge_type": "calc", "options": None,
"answer": "1", "page_answer": "", "subs": []}]}) as sp:
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
sp.assert_called_once()
self.assertEqual(r["source"], "crop")
def test_card_block_skips_crop(self):
from backend import scanflow
block = {"i": 0, "box": {"x": 1, "y": 1, "w": 300, "h": 300}, "stem": "10-6= 7+8=",
"judge_type": "card", "options": None, "page_answer": "",
"subs": [{"stem": "10-6 =", "answer": "4"}]}
with mock.patch("backend.tencent_ocr.split_questions") as sp:
r = scanflow.recognize_block(Path("data/bench/raw/x.jpg"), block)
sp.assert_not_called()
self.assertEqual(len(r["subs"]), 1)