test: 给令牌白名单与额度后扣钉测试;README 记录三条加固规则

This commit is contained in:
agent
2026-11-18 20:33:06 +08:00
parent 1aaff9f679
commit 05347e04f8
3 changed files with 112 additions and 3 deletions
+88
View File
@@ -0,0 +1,88 @@
# -*- coding: utf-8 -*-
"""这一轮加固的两条规则,各自钉一个测试。
1) 令牌只允许出现在「要贴到新标签页/发给他人的链接」的 query 上;
2) 一次性订阅额度必须是「发成功了才扣」——发失败要留着,下次还能用。
"""
from __future__ import annotations
import sys
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _tmpdir import workdir as _workdir # noqa: E402
from backend import app as appmod # noqa: E402
from backend import db as dbm # noqa: E402
from backend import services as svc # noqa: E402
from backend import wechat # noqa: E402
class QueryTokenTest(unittest.TestCase):
def test_link_endpoints_allow_query_token(self):
for p in ("/api/export/csv", "/api/print/weekly", "/api/papers/p_1/clean"):
self.assertTrue(appmod.query_token_ok(p), p)
def test_other_endpoints_reject_query_token(self):
for p in ("/api/today", "/api/me", "/api/mistakes",
"/api/export/csv2", "/api/papers/p_1", "/apipapers/x"):
self.assertFalse(appmod.query_token_ok(p), p)
class GrantTest(unittest.TestCase):
def setUp(self):
self.conn = dbm.connect(_workdir("hardening") / f"{self._testMethodName}.db")
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")
child = svc.create_child(self.conn, self.gid, "皮皮", 2)
self.cid = child["id"]
self.tmpl = svc.subscribe_template("daily")
svc.record_subscribe(self.conn, self.gid, [self.tmpl])
# 给这个孩子排几道今天到期的题,提醒才有东西可发
paper = svc.create_paper(self.conn, self.gid, self.cid, "math")
ids = [q["id"] for q in paper["questions"]]
imp = svc.import_mistakes(self.conn, self.gid, self.cid, ids[:3])
for m in imp["created"]:
self.conn.execute(
"UPDATE mistakes SET status='queued', next_due=? WHERE id=?",
(dbm.today(), m["mistake_id"]))
def tearDown(self):
self.conn.close()
def _grants_left(self):
return self.conn.execute(
"SELECT COUNT(*) c FROM subscribe_grants WHERE guardian_id=? AND used_at IS NULL",
(self.gid,)).fetchone()["c"]
def test_send_failure_keeps_the_grant(self):
before = self._grants_left()
origin = wechat.send_subscribe
wechat.send_subscribe = lambda openid, payload: {"sent": False, "dev": False, "message": "模拟失败"}
try:
res = svc.notifications_tick(self.conn)
finally:
wechat.send_subscribe = origin
self.assertEqual(self._grants_left(), before, "发失败了不该扣额度")
self.assertTrue(res["failed"], "失败要出现在返回值里,不能悄悄吞掉")
def test_send_success_consumes_the_grant(self):
before = self._grants_left()
origin = wechat.send_subscribe
wechat.send_subscribe = lambda openid, payload: {"sent": True, "dev": False}
try:
res = svc.notifications_tick(self.conn)
finally:
wechat.send_subscribe = origin
self.assertTrue(res["queued"], "发出去了要记账")
self.assertEqual(self._grants_left(), before - 1)
if __name__ == "__main__":
unittest.main()