WorkLog 全量合并:密码登录体系、每日自动备份、发信日志、活动邮件通知一键参加

- 认证:注册设密码(双次确认,>=10 位)、密码/验证码双模式登录、邮箱验证码找回重置密码
- 备份:服务内置每天 23:00 自动备份到 data/backups/(默认保留 14 份),backup_db.py 支持手动/crontab
- 发信日志:logs/mail-YYYYMM.log 记录每次发信成败与失败原因(535 认证失败/断连细分),按月滚动保留 6 个月
- 通知:发起活动群发邮件(参与不发),邮件内一键参加(一次性令牌、7 天有效、私密活动不群发)
- 前端:报错细分(字段/类型/状态码全中文)、验证码按钮 60 秒防连点
- 部署:Dockerfile + entrypoint(seed 机制)、限流/唯一索引/令牌摘要等安全加固
- 工具:repair_db/clear_db 的 SQL 全部常量化,无动态拼接
- 测试:43 项全覆盖(注册/登录/活动/通知/备份/日志/安全)
This commit is contained in:
2026-10-29 19:00:48 +08:00
commit 5c4b8d84ed
35 changed files with 5361 additions and 0 deletions
+423
View File
@@ -0,0 +1,423 @@
"""WorkLog API 回归测试:账号(邮箱+验证码)、活动直接生效、防重复提交、"我也参加过"、状态备注、可见性与统计。
Run with: python -m unittest discover -s tests -v
"""
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
# 测试口令每次运行随机生成(仅用于本机内存库,非真实凭据)
TEST_PASSWORD = f"Tp{uuid4().hex}Aa1!"
async def get_code(client: AsyncClient, email: str, purpose: str = "register") -> str:
r = await client.post("/api/auth/send-code", json={"email": email, "purpose": purpose})
assert r.status_code == 200, r.text
return r.json()["dev_code"]
async def register(client: AsyncClient, name: str, **kw) -> dict:
"""走完整流程:要验证码(开发模式直接返回)→ 注册。"""
email = kw.pop("email", f"{name.lower()}@example.test")
phone = kw.pop("phone", f"138{abs(hash(name)) % 10**8:08d}")
code = await get_code(client, email, "register")
password = kw.pop("password", TEST_PASSWORD)
confirmation = kw.pop("confirm_password", password)
body = {"display_name": name, "department": "综合部", "email": email, "phone": phone,
"email_code": code, "password": password, "confirm_password": confirmation, **kw}
r = await client.post("/api/auth/register", json=body)
assert r.status_code == 200, r.text
return r.json()
async def login(client: AsyncClient, email: str) -> dict:
code = await get_code(client, email, "login")
r = await client.post("/api/auth/login", json={"email": email, "email_code": code})
assert r.status_code == 200, r.text
return r.json()
def auth(token: str) -> dict:
return {"Authorization": f"Bearer {token}"}
class ApiTestCase(unittest.IsolatedAsyncioTestCase):
@classmethod
def setUpClass(cls):
cls.directory = Path(tempfile.gettempdir()) / f"worklog-test-{uuid4().hex}"
cls.directory.mkdir()
with patch.dict(os.environ, {
"WORKLOG_DB": str(cls.directory / "test.db"),
"WORKLOG_PORT": "34199",
}):
import server.main as m
cls.m = m
@classmethod
def tearDownClass(cls):
import shutil
if cls.directory.resolve().parent != Path(tempfile.gettempdir()).resolve():
raise RuntimeError("Refusing to remove a test directory outside the temp root")
shutil.rmtree(cls.directory)
def setUp(self):
self.patch_dev = patch.object(self.m, "DEV_MODE", True)
self.patch_dev.start()
# 每个用例一个独立内存库
self.engine = self.m.create_async_engine("sqlite+aiosqlite:///:memory:", future=True)
self.sessions = self.m.async_sessionmaker(self.engine, expire_on_commit=False)
self.patch_session = patch.object(self.m, "SessionLocal", self.sessions)
self.patch_session.start()
def tearDown(self):
self.patch_session.stop()
self.patch_dev.stop()
async def asyncSetUp(self):
async with self.engine.begin() as conn:
await conn.run_sync(self.m.metadata.create_all)
self.client = AsyncClient(transport=ASGITransport(app=self.m.app), base_url="http://localhost")
async def asyncTearDown(self):
await self.client.aclose()
await self.engine.dispose()
class WorkLogApiTests(ApiTestCase):
# ------------------------------------------------------------- 账号
async def test_register_login_profile(self):
c = self.client
u = await register(c, "张三", department="综合部", phone="13800000001")
self.assertEqual(u["user"]["display_name"], "张三")
self.assertEqual(u["user"]["department"], "综合部")
self.assertEqual(u["user"]["phone"], "13800000001")
# 重复邮箱:注册用途的验证码直接被拒(重复注册的第一道拦截)
r = await c.post("/api/auth/send-code", json={"email": u["user"]["email"], "purpose": "register"})
self.assertEqual(r.status_code, 409)
# 重复手机号:注册被拒
code = await get_code(c, "other@example.test", "register")
r = await c.post("/api/auth/register", json={
"display_name": "李四", "department": "综合部", "email": "other@example.test", "phone": "13800000001",
"email_code": code, "password": TEST_PASSWORD, "confirm_password": TEST_PASSWORD,
})
self.assertEqual(r.status_code, 409)
# 手机号格式非法
code = await get_code(c, "bad@example.test", "register")
r = await c.post("/api/auth/register", json={
"display_name": "王五", "department": "综合部", "email": "bad@example.test", "phone": "12345",
"email_code": code, "password": TEST_PASSWORD, "confirm_password": TEST_PASSWORD,
})
self.assertEqual(r.status_code, 422)
# 邮箱+验证码登录成功 / 错误验证码被拒
code = await get_code(c, u["user"]["email"], "login")
r = await c.post("/api/auth/login", json={"email": u["user"]["email"], "email_code": "000000"})
self.assertEqual(r.status_code, 400)
r = await c.post("/api/auth/login", json={"email": u["user"]["email"], "email_code": code})
self.assertEqual(r.status_code, 200)
token = r.json()["token"]
# 未登录被拒
r = await c.get("/api/auth/me")
self.assertEqual(r.status_code, 401)
# 改资料(姓名/部门/手机号)
r = await c.patch("/api/auth/me", headers=auth(token), json={"display_name": "张三丰", "department": "新媒体部"})
self.assertEqual(r.json()["user"]["display_name"], "张三丰")
self.assertEqual(r.json()["user"]["department"], "新媒体部")
r = await c.patch("/api/auth/me", headers=auth(token), json={"phone": "13900000001"})
self.assertEqual(r.json()["user"]["phone"], "13900000001")
# 手机号不能改成别人的
await register(c, "占用者", phone="13900000002")
r = await c.patch("/api/auth/me", headers=auth(token), json={"phone": "13900000002"})
self.assertEqual(r.status_code, 409)
async def test_department_register_and_filter(self):
c = self.client
# 部门随注册写入
u = await register(c, "deptA", department="综合部")
self.assertEqual(u["user"]["department"], "综合部")
# 新注册必填部门;未选择不能绕过前端校验。
r = await c.post("/api/auth/register", json={
"display_name": "deptB", "email": "deptB@example.test", "phone": "13800000123", "email_code": "123456",
"password": TEST_PASSWORD, "confirm_password": TEST_PASSWORD,
})
self.assertEqual(r.status_code, 422)
v = await register(c, "deptB", department="综合部")
self.assertEqual(v["user"]["department"], "综合部")
# 设置页可改部门
r = await c.patch("/api/auth/me", headers=auth(u["token"]), json={"department": "新媒体部"})
self.assertEqual(r.json()["user"]["department"], "新媒体部")
# 成员列表按姓名搜索可见部门
r = await c.get("/api/users?q=deptA", headers=auth(v["token"]))
self.assertEqual(r.json()["items"][0]["department"], "新媒体部")
# 部门筛选:deptB 记录一场活动,deptA(新媒体部)加入后,按部门过滤可见
tok2 = v["token"]
r = await c.post("/api/activities", headers=auth(tok2), json={
"title": "周会", "start_at": self.m.now_ms(),
})
aid = r.json()["activity"]["id"]
r = await c.post(f"/api/activities/{aid}/claim", headers=auth(u["token"]))
self.assertEqual(r.status_code, 200)
r = await c.get("/api/activities?department=新媒体部", headers=auth(tok2))
self.assertEqual(r.json()["count"], 1)
r = await c.get("/api/activities?department=不存在的部门", headers=auth(tok2))
self.assertEqual(r.json()["count"], 0)
# overview 的部门统计
r = await c.get("/api/stats/overview", headers=auth(tok2))
deps = {d["department"]: d["count"] for d in r.json()["departments"]}
self.assertEqual(deps.get("新媒体部"), 1)
self.assertNotIn("", deps)
async def test_email_verification_flow(self):
c = self.client
# 重复邮箱:第二个注册请求验证码被拒
r = await c.post("/api/auth/send-code", json={"email": "dup@example.test", "purpose": "register"})
self.assertEqual(r.status_code, 200)
code = r.json()["dev_code"]
await c.post("/api/auth/register", json={
"display_name": "maila", "department": "综合部", "email": "dup@example.test", "phone": "13811111111", "email_code": code,
"password": TEST_PASSWORD, "confirm_password": TEST_PASSWORD,
})
r = await c.post("/api/auth/send-code", json={"email": "dup@example.test", "purpose": "register"})
self.assertEqual(r.status_code, 409)
# 错误验证码注册被拒
r = await c.post("/api/auth/send-code", json={"email": "fresh@example.test", "purpose": "register"})
self.assertEqual(r.status_code, 200)
r = await c.post("/api/auth/register", json={
"display_name": "mailb", "department": "综合部", "email": "fresh@example.test", "phone": "13811111112",
"email_code": "000000", "password": TEST_PASSWORD, "confirm_password": TEST_PASSWORD,
})
self.assertEqual(r.status_code, 400)
# 正确验证码注册成功
r = await c.post("/api/auth/send-code", json={"email": "fresh@example.test", "purpose": "register"})
code = r.json()["dev_code"]
r = await c.post("/api/auth/register", json={
"display_name": "mailb", "department": "综合部", "email": "fresh@example.test", "phone": "13811111112",
"email_code": code, "password": TEST_PASSWORD, "confirm_password": TEST_PASSWORD,
})
self.assertEqual(r.status_code, 200)
self.assertEqual(r.json()["user"]["email"], "fresh@example.test")
# 用邮箱登录
r = await c.post("/api/auth/login", json={"email": "fresh@example.test", "email_code": "000000"})
self.assertEqual(r.status_code, 400) # purpose=login 的验证码不存在
# 邮箱格式非法
r = await c.post("/api/auth/send-code", json={"email": "not-an-email"})
self.assertEqual(r.status_code, 422)
async def test_logout_invalidates_token(self):
c = self.client
u = await register(c, "bob")
r = await c.post("/api/auth/logout", headers=auth(u["token"]))
self.assertEqual(r.json()["ok"], True)
r = await c.get("/api/auth/me", headers=auth(u["token"]))
self.assertEqual(r.status_code, 401)
# ------------------------------------------------------------- 活动:直接生效 + 共同参加
async def test_activity_publish_and_claim(self):
c = self.client
alice = await register(c, "alice2")
bob = await register(c, "bob2")
# bob 记录活动:立即生效,无需审核
r = await c.post("/api/activities", headers=auth(bob["token"]), json={
"title": "周末羽毛球", "start_at": self.m.now_ms() + 86_400_000,
"location": "体育馆", "visibility": "public",
})
self.assertEqual(r.status_code, 200, r.text)
act = r.json()["activity"]
self.assertFalse(r.json().get("pending_review", False))
self.assertEqual(act["participant_count"], 1) # 只有记录人自己
aid = act["id"]
# 其他人(carol)立即可见
carol = await register(c, "carol0")
r = await c.get("/api/activities", headers=auth(carol["token"]))
self.assertEqual([a["id"] for a in r.json()["items"]], [aid])
# alice 申请"我也参加过" → 直接加入
r = await c.post(f"/api/activities/{aid}/claim", headers=auth(alice["token"]))
self.assertEqual(r.status_code, 200)
me_row = next(p for p in r.json()["activity"]["participants"] if p["user_id"] == alice["user"]["id"])
self.assertEqual(me_row["status"], "joined")
# 重复申请被拒
r = await c.post(f"/api/activities/{aid}/claim", headers=auth(alice["token"]))
self.assertEqual(r.status_code, 409)
# 加入后 alice 统计 +1
r = await c.get("/api/auth/me", headers=auth(alice["token"]))
self.assertEqual(r.json()["stats"]["total"], 1)
# alice 退出 → 记录消失
r = await c.post(f"/api/activities/{aid}/leave", headers=auth(alice["token"]))
self.assertEqual(r.status_code, 200)
r = await c.get("/api/auth/me", headers=auth(alice["token"]))
self.assertEqual(r.json()["stats"]["total"], 0)
async def test_duplicate_submit_returns_same_activity(self):
c = self.client
alice = await register(c, "dupA")
body = {"title": "晨跑", "start_at": self.m.now_ms() + 3_600_000, "visibility": "public"}
r1 = await c.post("/api/activities", headers=auth(alice["token"]), json=body)
self.assertEqual(r1.json()["duplicate"], False)
# 连续点击提交:同名活动在窗口期内直接返回第一条,不再新建
r2 = await c.post("/api/activities", headers=auth(alice["token"]), json=body)
self.assertEqual(r2.status_code, 200)
self.assertEqual(r2.json()["duplicate"], True)
self.assertEqual(r2.json()["activity"]["id"], r1.json()["activity"]["id"])
# 不同标题不受影响
r3 = await c.post("/api/activities", headers=auth(alice["token"]),
json={**body, "title": "夜跑"})
self.assertEqual(r3.json()["duplicate"], False)
# 别人用同名标题不受影响
bob = await register(c, "dupB")
r4 = await c.post("/api/activities", headers=auth(bob["token"]), json=body)
self.assertEqual(r4.json()["duplicate"], False)
self.assertNotEqual(r4.json()["activity"]["id"], r1.json()["activity"]["id"])
# ------------------------------------------------------------- 编辑 / 删除 / 状态
async def test_edit_delete_and_status(self):
c = self.client
alice = await register(c, "alice3")
bob = await register(c, "bob3")
r = await c.post("/api/activities", headers=auth(alice["token"]), json={
"title": "志愿讲解", "start_at": self.m.now_ms() - 3_600_000,
})
act = r.json()["activity"]
aid = act["id"]
# bob 申请共同参加 → 直接加入
r = await c.post(f"/api/activities/{aid}/claim", headers=auth(bob["token"]))
me_row = next(p for p in r.json()["activity"]["participants"] if p["user_id"] == bob["user"]["id"])
self.assertEqual(me_row["status"], "joined")
# bob 自己标记状态/备注
r = await c.patch(f"/api/activities/{aid}/participants/{bob['user']['id']}",
headers=auth(bob["token"]), json={"status": "attended", "note": "讲了两场"})
self.assertEqual(r.status_code, 200)
me_row = next(p for p in r.json()["activity"]["participants"] if p["user_id"] == bob["user"]["id"])
self.assertEqual(me_row["status"], "attended")
self.assertEqual(me_row["note"], "讲了两场")
# bob 不能改 alice 的状态
r = await c.patch(f"/api/activities/{aid}/participants/{alice['user']['id']}",
headers=auth(bob["token"]), json={"status": "absent"})
self.assertEqual(r.status_code, 403)
# 非记录人不能编辑/删除
r = await c.patch(f"/api/activities/{aid}", headers=auth(bob["token"]), json={"title": "x"})
self.assertEqual(r.status_code, 403)
r = await c.delete(f"/api/activities/{aid}", headers=auth(bob["token"]))
self.assertEqual(r.status_code, 403)
# 记录人编辑
r = await c.patch(f"/api/activities/{aid}", headers=auth(alice["token"]), json={"title": "志愿讲解局"})
self.assertEqual(r.json()["activity"]["title"], "志愿讲解局")
# 列表 scope
r = await c.get("/api/activities?scope=joined", headers=auth(bob["token"]))
self.assertEqual(r.json()["count"], 1)
r = await c.get("/api/activities?scope=mine", headers=auth(alice["token"]))
self.assertEqual(r.json()["count"], 1)
r = await c.get("/api/activities?q=讲解", headers=auth(bob["token"]))
self.assertEqual(r.json()["count"], 1)
# 删除
r = await c.delete(f"/api/activities/{aid}", headers=auth(alice["token"]))
self.assertEqual(r.json()["ok"], True)
r = await c.get(f"/api/activities/{aid}", headers=auth(alice["token"]))
self.assertEqual(r.status_code, 404)
# ------------------------------------------------------------- 可见性
async def test_visibility_and_user_pages(self):
c = self.client
alice = await register(c, "alice4")
bob = await register(c, "bob4")
carol = await register(c, "carol4")
pub = (await c.post("/api/activities", headers=auth(alice["token"]), json={
"title": "公开讲座", "start_at": self.m.now_ms() - 86_400_000, "visibility": "public",
})).json()["activity"]
pri = (await c.post("/api/activities", headers=auth(alice["token"]), json={
"title": "私密聚餐", "start_at": self.m.now_ms() - 86_400_000, "visibility": "private",
})).json()["activity"]
# bob 加入公开活动;私密活动无法申请
r = await c.post(f"/api/activities/{pub['id']}/claim", headers=auth(bob["token"]))
self.assertEqual(r.status_code, 200)
r = await c.post(f"/api/activities/{pri['id']}/claim", headers=auth(bob["token"]))
self.assertEqual(r.status_code, 403)
# carol 能看到 alice 的公开活动,不能看到私密的
r = await c.get("/api/activities?user_id=" + alice["user"]["id"], headers=auth(carol["token"]))
titles = [a["title"] for a in r.json()["items"]]
self.assertIn("公开讲座", titles)
self.assertNotIn("私密聚餐", titles)
r = await c.get(f"/api/activities/{pri['id']}", headers=auth(carol["token"]))
self.assertEqual(r.status_code, 403)
# carol 查看 alice 主页:只算公开记录
r = await c.get(f"/api/users/{alice['user']['id']}", headers=auth(carol["token"]))
stats = r.json()["stats"]
self.assertEqual(stats["organized"], 1)
self.assertEqual(stats["total"], 1)
# bob 自己看自己:公开记录 1 条
r = await c.get(f"/api/users/{bob['user']['id']}", headers=auth(bob["token"]))
self.assertTrue(r.json()["is_self"])
self.assertEqual(r.json()["stats"]["total"], 1)
# 成员列表统计
r = await c.get("/api/users?q=alice4", headers=auth(carol["token"]))
row = r.json()["items"][0]
self.assertEqual(row["organized"], 1)
# ------------------------------------------------------------- 统计
async def test_stats_overview(self):
c = self.client
alice = await register(c, "alice5")
bob = await register(c, "bob5")
r = await c.post("/api/activities", headers=auth(bob["token"]), json={
"title": "晨跑", "start_at": self.m.now_ms() + 3_600_000, "visibility": "public",
})
r = await c.get("/api/stats/overview", headers=auth(bob["token"]))
ov = r.json()
self.assertEqual(ov["members"], 2)
self.assertEqual(ov["activities"], 1)
self.assertEqual(ov["upcoming"], 1)
self.assertEqual(ov["records"], 1)
async def test_private_activity_hidden_from_feed(self):
c = self.client
alice = await register(c, "alice6")
carol = await register(c, "carol6")
await c.post("/api/activities", headers=auth(alice["token"]), json={
"title": "私密局", "start_at": self.m.now_ms(), "visibility": "private",
})
r = await c.get("/api/activities", headers=auth(carol["token"]))
self.assertEqual([a["title"] for a in r.json()["items"]], [])
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -0,0 +1,97 @@
"""定时备份功能测试:备份内容一致性、保留策略、调度时间计算。
Run with: python -m unittest discover -s tests -p "test_backup.py" -v
"""
import shutil
import sqlite3
import tempfile
import time
import unittest
from contextlib import closing
from datetime import datetime
from pathlib import Path
from uuid import uuid4
from server.backup import _backup_once_sync, parse_time, seconds_until
def make_db(path: Path) -> None:
with closing(sqlite3.connect(str(path))) as conn:
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)")
conn.executemany("INSERT INTO t (name) VALUES (?)", [(f"row{i}",) for i in range(50)])
conn.commit()
class BackupTests(unittest.TestCase):
def setUp(self):
self.directory = Path(tempfile.gettempdir()) / f"worklog-backup-{uuid4().hex}"
self.directory.mkdir()
self.db = self.directory / "worklog.db"
make_db(self.db)
def tearDown(self):
shutil.rmtree(self.directory)
def test_backup_creates_consistent_copy(self):
dest = _backup_once_sync(self.db, self.directory / "backups", keep=14)
self.assertTrue(dest.exists())
self.assertEqual(dest.parent.name, "backups")
with closing(sqlite3.connect(str(self.db))) as src:
src_count = src.execute("SELECT COUNT(*) FROM t").fetchone()[0]
with closing(sqlite3.connect(str(dest))) as copy:
copy_count = copy.execute("SELECT COUNT(*) FROM t").fetchone()[0]
self.assertEqual(copy_count, 50)
self.assertEqual(src_count, copy_count)
def test_backup_runs_while_db_in_wal_mode_with_uncommitted_wal(self):
# 模拟服务运行中:开一个 WAL 连接写入但不 checkpoint
with closing(sqlite3.connect(str(self.db))) as conn:
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("INSERT INTO t (name) VALUES ('wal-only-row')")
conn.commit()
try:
dest = _backup_once_sync(self.db, self.directory / "backups", keep=14)
finally:
pass
with closing(sqlite3.connect(str(dest))) as copy:
copy_count = copy.execute(
"SELECT COUNT(*) FROM t WHERE name='wal-only-row'"
).fetchone()[0]
self.assertEqual(copy_count, 1, "备份应包含 WAL 里未合并的数据")
def test_retention_keeps_only_latest(self):
bdir = self.directory / "backups"
for _ in range(5):
_backup_once_sync(self.db, bdir, keep=3)
time.sleep(0.05) # 同秒会加 -2/-3 序号,不会被覆盖
files = sorted(bdir.glob("worklog-*.db"))
self.assertEqual(len(files), 3, f"应只保留 3 份,实际 {len(files)}")
def test_prune_does_not_touch_foreign_files(self):
bdir = self.directory / "backups"
bdir.mkdir()
stranger = bdir / "other-20260101-000000.db"
stranger.write_bytes(b"x")
_backup_once_sync(self.db, bdir, keep=1)
self.assertTrue(stranger.exists(), "不匹配命名规则的文件不应被清理")
def test_seconds_until(self):
base = datetime(2026, 10, 27, 22, 0, 0)
self.assertEqual(seconds_until(23, 0, base), 3600.0)
# 已过目标点:算明天
late = datetime(2026, 10, 27, 23, 30, 0)
self.assertEqual(seconds_until(23, 0, late), 23.5 * 3600)
# 恰好等于目标点:算明天(避免 0 延迟重复触发)
exact = datetime(2026, 10, 27, 23, 0, 0)
self.assertEqual(seconds_until(23, 0, exact), 24 * 3600)
def test_parse_time(self):
self.assertEqual(parse_time("23:00"), (23, 0))
self.assertEqual(parse_time("0:05"), (0, 5))
self.assertEqual(parse_time("25:00"), (23, 0), "非法时间回退 23:00")
self.assertEqual(parse_time("abc"), (23, 0))
self.assertEqual(parse_time(""), (23, 0))
if __name__ == "__main__":
unittest.main()
+68
View File
@@ -0,0 +1,68 @@
"""发信日志(maillog)测试。
Run with: python -m unittest discover -s tests -p "test_maillog.py" -v
"""
import shutil
import tempfile
import unittest
from contextlib import closing
from datetime import datetime
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4
from server import maillog
class MailLogTests(unittest.TestCase):
def setUp(self):
self.directory = Path(tempfile.gettempdir()) / f"worklog-maillog-{uuid4().hex}"
self.directory.mkdir()
# 把日志目录指到临时位置
self.patch_dir = patch.object(maillog, "LOG_DIR", self.directory / "logs")
self.patch_dir.start()
def tearDown(self):
self.patch_dir.stop()
shutil.rmtree(self.directory)
def read_log(self) -> str:
path = self.directory / "logs" / f"mail-{datetime.now():%Y%m}.log"
return path.read_text(encoding="utf-8")
def test_log_write_and_rotate_name(self):
maillog.log_mail("OK", "a@t.test", "测试邮件", "1.2s tls=ssl")
line = self.read_log().strip()
self.assertIn("OK", line)
self.assertIn("a@t.test", line)
self.assertIn("测试邮件", line)
self.assertIn("1.2s", line)
# 滚动文件名带当月标记
expected = f"mail-{datetime.now():%Y%m}.log"
files = [p.name for p in (self.directory / "logs").glob("mail-*.log")]
self.assertEqual(files, [expected], f"应为当月滚动文件,实际 {files}")
def test_fail_line_with_exception_text(self):
maillog.log_mail("FAIL", "b@t.test", "验证码", "SMTPServerDisconnected(3.0s): Unexpected EOF")
line = self.read_log().strip()
self.assertIn("FAIL", line)
self.assertIn("Unexpected EOF", line)
self.assertIn("b@t.test", line)
def test_log_never_raises(self):
# 日志目录指到一个文件上,写入必然失败,但调用绝不能抛
(self.directory / "blocker").write_text("x")
with patch.object(maillog, "LOG_DIR", self.directory / "blocker"):
maillog.log_mail("OK", "c@t.test", "x") # 不应抛 OSError
def test_prune_removes_old_months(self):
logs = self.directory / "logs"
logs.mkdir(exist_ok=True)
old = logs / "mail-202401.log"
old.write_text("old\n", encoding="utf-8")
maillog.log_mail("OK", "d@t.test", "x")
self.assertFalse(old.exists(), "超过保留期的日志应被删除")
if __name__ == "__main__":
unittest.main()
+208
View File
@@ -0,0 +1,208 @@
"""邮件通知与一键参加功能测试。
Run with: python -m unittest discover -s tests -p "test_notify.py" -v
"""
import asyncio
import os
import tempfile
import unittest
from contextlib import contextmanager
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from test_api import get_code, register
class NotifyTests(unittest.IsolatedAsyncioTestCase):
@classmethod
def setUpClass(cls):
cls.directory = Path(tempfile.gettempdir()) / f"worklog-notify-{uuid4().hex}"
cls.directory.mkdir()
with patch.dict(os.environ, {
"WORKLOG_DB": str(cls.directory / "test.db"),
"WORKLOG_PORT": "34199",
}):
import server.main as m
cls.m = m
@classmethod
def tearDownClass(cls):
import shutil
shutil.rmtree(cls.directory)
def setUp(self):
self.patch_dev = patch.object(self.m, "DEV_MODE", True)
self.patch_dev.start()
self.engine = self.m.create_async_engine("sqlite+aiosqlite:///:memory:", future=True)
self.sessions = self.m.async_sessionmaker(self.engine, expire_on_commit=False)
self.patch_session = patch.object(self.m, "SessionLocal", self.sessions)
self.patch_session.start()
# 注意:通知任务自己开 SessionLocal,也被上面的 patch 覆盖,能用同一个内存库
self.sent: list[tuple[str, str, str, str | None]] = []
async def fake_send(to, subject, body, html=None):
self.sent.append((to, subject, body, html))
self.patch_send = patch.object(self.m, "_send_email", fake_send)
self.patch_send.start()
def tearDown(self):
self.patch_send.stop()
self.patch_session.stop()
self.patch_dev.stop()
async def asyncSetUp(self):
async with self.engine.begin() as conn:
await conn.run_sync(self.m.metadata.create_all)
self.client = AsyncClient(transport=ASGITransport(app=self.m.app), base_url="http://localhost")
async def asyncTearDown(self):
await self.client.aclose()
await self.engine.dispose()
# 让后台通知任务跑完,避免事件循环关闭时报警
await asyncio.sleep(0.15)
@contextmanager
def real_notify_mode(self):
"""发活动时临时切到"已配置 SMTP"的形态,让通知逻辑被触发(发信本身仍是 mock)。"""
with patch.object(self.m, "DEV_MODE", False):
yield
async def publish(self, token: str, **fields) -> dict:
body = {"title": fields.pop("title"), "start_at": 1792000000000,
"location": fields.pop("location", "三楼会议室"),
"description": fields.pop("description", ""), "visibility": fields.pop("visibility", "public"),
**fields}
r = await self.client.post("/api/activities", headers={"Authorization": f"Bearer {token}"}, json=body)
self.assertEqual(r.status_code, 200, r.text)
data = r.json()
self.m_activity_id = data["activity"]["id"]
return data
@staticmethod
async def wait_notify():
await asyncio.sleep(0.25)
@staticmethod
def join_url(plain_text: str) -> str:
return next(p for p in plain_text.split() if "/join/" in p)
async def test_publish_notifies_everyone_with_one_click_join(self):
c = self.client
# 三个用户
alice = await register(c, "甲", email="a@example.test", phone="13800000001", department="综合部")
bob = await register(c, "乙", email="b@example.test", phone="13800000002", department="新媒体部")
carol = await register(c, "丙", email="c@example.test", phone="13800000003", department="培训宣讲部")
# 甲发活动:应通知乙和丙,不通知甲自己
with self.real_notify_mode():
await self.publish(alice["token"], title="客户答谢会", description="带名片")
await self.wait_notify()
tos = [to for to, *_ in self.sent]
self.assertEqual(sorted(tos), ["b@example.test", "c@example.test"], f"实际发给: {tos}")
for _to, subject, plain, html in self.sent:
self.assertIn("客户答谢会", subject)
self.assertIn("客户答谢会", plain)
self.assertIn("/join/", plain)
self.assertIsNotNone(html)
self.assertIn("我也参加过", html)
self.assertIn("/join/", html)
def mail_to(email: str) -> str:
return next(plain for to, _s, plain, _h in self.sent if to == email)
# 乙邮件里的一键链接,模拟点开
token = self.join_url(mail_to("b@example.test")).rsplit("/", 1)[-1]
r = await c.get(f"/join/{token}")
self.assertEqual(r.status_code, 200)
self.assertIn("确认参加", r.text)
# 预览或邮件扫描只做 GET,不应写入参加记录。
async with self.sessions() as db:
people = await self.m._require_participant(db, self.m_activity_id, bob["user"]["id"])
self.assertIsNone(people)
r = await c.post(f"/join/{token}")
self.assertIn("记录成功", r.text)
self.assertIn("客户答谢会", r.text)
# 乙真的进了活动
r = await c.get("/api/activities", headers={"Authorization": f"Bearer {bob['token']}"})
act = next(a for a in r.json()["items"] if a["title"] == "客户答谢会")
self.assertIn(bob["user"]["id"], {p["user_id"] for p in act["participants"]})
# 同一链接再点:一次性,提示已处理,不再重复添加
r = await c.get(f"/join/{token}")
self.assertIn("已经使用过", r.text)
r = await c.get("/api/activities", headers={"Authorization": f"Bearer {bob['token']}"})
act = next(a for a in r.json()["items"] if a["title"] == "客户答谢会")
self.assertEqual(sum(1 for p in act["participants"] if p["user_id"] == bob["user"]["id"]), 1)
# 丙的链接仍可用(每人一个独立 token)
carol_url = self.join_url(mail_to("c@example.test"))
r = await c.post(carol_url)
self.assertIn("记录成功", r.text)
async def test_private_activity_no_notify(self):
c = self.client
alice = await register(c, "甲", email="p-a@example.test", phone="13800000011", department="综合部")
await register(c, "乙", email="p-b@example.test", phone="13800000012", department="综合部")
with self.real_notify_mode():
await self.publish(alice["token"], title="私密活动", visibility="private")
await self.wait_notify()
self.assertEqual(self.sent, [], "私密活动不应群发通知")
async def test_notify_disabled_switch(self):
c = self.client
alice = await register(c, "甲", email="n-a@example.test", phone="13800000021", department="综合部")
await register(c, "乙", email="n-b@example.test", phone="13800000022", department="综合部")
with patch.object(self.m, "NOTIFY_ENABLED", False), self.real_notify_mode():
await self.publish(alice["token"], title="不通知活动")
await self.wait_notify()
self.assertEqual(self.sent, [], "开关关闭时不应发通知")
async def test_smtp_failure_does_not_break_publish(self):
c = self.client
alice = await register(c, "甲", email="f-a@example.test", phone="13800000031", department="综合部")
async def broken_send(to, subject, body, html=None):
raise RuntimeError("SMTP down")
with self.real_notify_mode(), patch.object(self.m, "_send_email", broken_send):
r = await self.client.post(
"/api/activities", headers={"Authorization": f"Bearer {alice['token']}"},
json={"title": "SMTP坏也要建", "start_at": 1792000000000,
"location": "x", "description": "", "visibility": "public"})
self.assertEqual(r.status_code, 200, "发信失败不应影响活动创建")
await self.wait_notify()
# 活动确实存在
r = await c.get("/api/activities", headers={"Authorization": f"Bearer {alice['token']}"})
self.assertTrue(any(a["title"] == "SMTP坏也要建" for a in r.json()["items"]))
async def test_claim_link_invalid_and_expired(self):
c = self.client
alice = await register(c, "甲", email="e-a@example.test", phone="13800000041", department="综合部")
bob = await register(c, "乙", email="e-b@example.test", phone="13800000042", department="综合部")
# 不存在的 token
r = await c.get("/join/notexist-token")
self.assertIn("无效", r.text)
# 过期 token
with self.real_notify_mode():
await self.publish(alice["token"], title="过期测试")
await self.wait_notify()
expired_token = self.join_url(self.sent[0][2]).rsplit("/", 1)[-1]
# 乙在网页上先手动记了,再点邮件链接:应提示"已在记录里",不重复添加
r = await c.post("/api/activities", headers={"Authorization": f"Bearer {bob['token']}"})
r = await c.post(
f"/api/activities/{self.m_activity_id}/claim",
headers={"Authorization": f"Bearer {bob['token']}"},
)
self.assertEqual(r.status_code, 200)
r = await c.get(f"/join/{expired_token}")
self.assertIn("已经", r.text)
# 甲(组织者)没收到任何邮件
self.assertFalse(any(to == "e-a@example.test" for to, *_ in self.sent))
+64
View File
@@ -0,0 +1,64 @@
"""注册字段校验与历史账号兼容性。"""
from sqlalchemy import select, update
from test_api import ApiTestCase, TEST_PASSWORD, auth, get_code, register
class RegistrationTests(ApiTestCase):
async def test_required_fields_and_format_errors_do_not_create_users(self):
valid = {"display_name": "新成员", "department": "综合部", "email": "new@example.test",
"phone": "13812345678", "email_code": "123456", "password": TEST_PASSWORD,
"confirm_password": TEST_PASSWORD}
for field in valid:
with self.subTest(missing=field):
payload = {key: value for key, value in valid.items() if key != field}
response = await self.client.post("/api/auth/register", json=payload)
self.assertEqual(response.status_code, 422)
invalid = {"display_name": [" ", "名" * 33], "department": ["", " ", "不存在的部门"],
"email": ["not-an-email"], "phone": ["12345", "13812345678"],
"email_code": ["1234", "1234567", "abcdef", "123456", 123456],
"password": ["short", TEST_PASSWORD * 3],
"confirm_password": ["Different" + TEST_PASSWORD]}
for field, values in invalid.items():
for value in values:
with self.subTest(field=field, value=value):
response = await self.client.post("/api/auth/register", json={**valid, field: value})
self.assertEqual(response.status_code, 422)
async with self.sessions() as db:
self.assertEqual(len((await db.execute(select(self.m.users))).all()), 0)
async def test_registration_normalizes_input_and_keeps_legacy_columns(self):
code = await get_code(self.client, "New.Member@Example.Test", "register")
response = await self.client.post("/api/auth/register", json={
"display_name": " 新成员 ", "department": " 综合部 ", "email": " New.Member@Example.Test ",
"phone": "13812345678", "email_code": f" {code} ",
"password": TEST_PASSWORD, "confirm_password": TEST_PASSWORD,
})
self.assertEqual(response.status_code, 200, response.text)
user = response.json()["user"]
self.assertEqual(user["display_name"], "新成员")
self.assertEqual(user["email"], "new.member@example.test")
self.assertEqual(user["department"], "综合部")
async with self.sessions() as db:
row = (await db.execute(select(self.m.users))).mappings().one()
self.assertTrue(row["username"])
self.assertTrue(row["password_hash"])
self.assertEqual(row["role"], "member")
async def test_old_accounts_with_blank_department_and_phone_still_login(self):
user = await register(self.client, "历史账号")
async with self.sessions() as db:
await db.execute(update(self.m.users).where(self.m.users.c.id == user["user"]["id"]).values(department="", phone=""))
await db.commit()
code = await get_code(self.client, user["user"]["email"], "login")
response = await self.client.post("/api/auth/login", json={"email": user["user"]["email"], "email_code": code})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["user"]["department"], "")
self.assertEqual(response.json()["user"]["phone"], "")
response = await self.client.get("/api/auth/me", headers=auth(response.json()["token"]))
self.assertEqual(response.status_code, 200)
async def test_login_requires_six_ascii_digits(self):
for code in ("1234", "abcdef", "123456", "1234567"):
response = await self.client.post("/api/auth/login", json={"email": "user@example.test", "email_code": code})
self.assertEqual(response.status_code, 422)
+222
View File
@@ -0,0 +1,222 @@
"""安全回归:只使用隔离数据库,不发送真实邮件。"""
import asyncio
from unittest.mock import patch
from httpx import ASGITransport, AsyncClient
from sqlalchemy import insert, select, update
from starlette.requests import Request
from test_api import ApiTestCase, auth, get_code, register
class SecurityTests(ApiTestCase):
async def test_code_storage_attempt_limit_and_resend(self):
user = await register(self.client, "attempts")
email = user["user"]["email"]
code = await get_code(self.client, email, "login")
async with self.sessions() as db:
row = (await db.execute(select(self.m.email_verifications).where(
self.m.email_verifications.c.email == email,
self.m.email_verifications.c.purpose == "login",
))).mappings().one()
self.assertNotEqual(row["code"], code)
self.assertTrue(self.m.verify_password(code, row["code"]))
wrong = "111111" if code == "000000" else "000000"
for _ in range(5):
response = await self.client.post("/api/auth/login", json={"email": email, "email_code": wrong})
self.assertEqual(response.status_code, 400)
response = await self.client.post("/api/auth/login", json={"email": email, "email_code": code})
self.assertEqual(response.status_code, 429)
fresh = await get_code(self.client, email, "login")
response = await self.client.post("/api/auth/login", json={"email": email, "email_code": fresh})
self.assertEqual(response.status_code, 200)
response = await self.client.post("/api/auth/login", json={"email": email, "email_code": fresh})
self.assertEqual(response.status_code, 400)
async def test_resend_invalidates_old_code_and_purpose_isolated(self):
user = await register(self.client, "resend")
email = user["user"]["email"]
with patch.object(self.m, "_random_code", side_effect=["123456", "654321"]):
old = await get_code(self.client, email, "login")
fresh = await get_code(self.client, email, "login")
for code, expected in ((old, 400), (fresh, 200)):
response = await self.client.post("/api/auth/login", json={"email": email, "email_code": code})
self.assertEqual(response.status_code, expected)
code = await get_code(self.client, "purpose@example.test", "register")
async with self.sessions() as db:
with self.assertRaises(self.m.HTTPException):
await self.m._consume_email_code(db, "purpose@example.test", code, "login")
async def test_missing_smtp_never_reveals_code(self):
with patch.object(self.m, "DEV_MODE", False), patch.object(self.m, "SMTP_PASSWORD", ""):
response = await self.client.post("/api/auth/send-code", json={"email": "safe@example.test"})
self.assertEqual(response.status_code, 503)
self.assertNotIn("dev_code", response.json())
async with AsyncClient(transport=ASGITransport(app=self.m.app, client=("203.0.113.10", 1234)), base_url="http://test") as remote:
response = await remote.post("/api/auth/send-code", json={"email": "remote@example.test"})
self.assertEqual(response.status_code, 403)
async with AsyncClient(transport=ASGITransport(app=self.m.app), base_url="http://evil.example") as rebound:
response = await rebound.post("/api/auth/send-code", json={"email": "rebound@example.test"})
self.assertEqual(response.status_code, 403)
async def test_ip_limits_cover_changing_emails_and_forwarded_headers(self):
async with self.sessions() as db:
for _ in range(30):
await self.m._auth_limit(db, "send-ip:127.0.0.1", 30)
response = await self.client.post("/api/auth/send-code", headers={"X-Forwarded-For": "203.0.113.99"}, json={"email": "other@example.test"})
self.assertEqual(response.status_code, 429)
self.assertEqual(response.headers["Retry-After"], "600")
async def test_token_hash_cannot_authenticate_and_expiry_logout_work(self):
user = await register(self.client, "sessions")
async with self.sessions() as db:
stored = (await db.execute(select(self.m.sessions.c.token))).scalar_one()
self.assertNotEqual(stored, user["token"])
self.assertEqual(stored, self.m.token_digest(user["token"]))
self.assertEqual((await self.client.get("/api/auth/me", headers=auth(stored))).status_code, 401)
async with self.sessions() as db:
await db.execute(update(self.m.sessions).values(expires_at=1))
await db.commit()
self.assertEqual((await self.client.get("/api/auth/me", headers=auth(user["token"]))).status_code, 401)
async def test_contacts_and_private_statistics_hidden(self):
owner = await register(self.client, "private-owner")
viewer = await register(self.client, "private-viewer")
for visibility in ("public", "private"):
await self.client.post("/api/activities", headers=auth(owner["token"]), json={
"title": visibility, "start_at": self.m.now_ms(), "visibility": visibility,
})
headers = auth(viewer["token"])
members = (await self.client.get("/api/users", headers=headers)).json()["items"]
member = next(u for u in members if u["id"] == owner["user"]["id"])
self.assertNotIn("email", member)
self.assertNotIn("phone", member)
self.assertEqual(member["total"], 1)
overview = (await self.client.get("/api/stats/overview", headers=headers)).json()
self.assertEqual(overview["records"], 1)
profile = (await self.client.get(f"/api/users/{owner['user']['id']}", headers=headers)).json()
self.assertNotIn("email", profile["user"])
activity = profile["items"][0]
self.assertNotIn("email", activity["organizer"])
own = (await self.client.get("/api/auth/me", headers=auth(owner["token"]))).json()
self.assertEqual(own["user"]["email"], owner["user"]["email"])
async def test_cross_origin_requests_and_headers(self):
response = await self.client.post("/api/auth/send-code", headers={"Origin": "https://evil.example"}, json={"email": "x@example.test"})
self.assertEqual(response.status_code, 403)
response = await self.client.options("/api/auth/send-code", headers={"Origin": "https://evil.example", "Access-Control-Request-Method": "POST"})
self.assertNotIn("access-control-allow-origin", response.headers)
response = await self.client.get("/api/health")
self.assertEqual(response.headers["Cache-Control"], "no-store")
self.assertEqual(response.headers["Referrer-Policy"], "no-referrer")
self.assertEqual(response.headers["X-Frame-Options"], "DENY")
self.assertIn("script-src 'self'", response.headers["Content-Security-Policy"])
async def test_mail_html_and_join_page_escape_user_content(self):
evil = '<img src=x onerror="alert(1)">'
activity = {"title": evil, "location": evil, "description": evil, "start_at": self.m.now_ms()}
html = self.m._notify_mail_html(evil, activity, 'https://safe.example/join/a" onmouseover="x', "https://safe.example/")
self.assertNotIn("<img", html)
self.assertIn("&lt;img", html)
self.assertNotIn('" onmouseover="', html)
page = self.m._join_page(evil, "ok", evil)
self.assertNotIn("<img", page)
async def test_email_links_ignore_request_host_headers(self):
request = Request({"type": "http", "scheme": "http", "server": ("test", 80), "path": "/", "headers": [
(b"host", b"evil.example"), (b"x-forwarded-host", b"evil.example"), (b"x-forwarded-proto", b"javascript"),
]})
with patch.object(self.m, "BASE_URL", ""):
self.assertEqual(self.m._site_base_url(request), f"http://127.0.0.1:{self.m.PORT}")
with patch.object(self.m, "BASE_URL", "https://safe.example"):
self.assertEqual(self.m._site_base_url(request), "https://safe.example")
async def make_link(self):
owner = await register(self.client, "link-owner")
viewer = await register(self.client, "link-viewer")
activity = (await self.client.post("/api/activities", headers=auth(owner["token"]), json={
"title": "链接测试", "start_at": self.m.now_ms(),
})).json()["activity"]
token = self.m.new_token()
async with self.m.SessionLocal() as db:
await db.execute(insert(self.m.join_links).values(
id=self.m.new_id(), token=self.m.token_digest(token), activity_id=activity["id"],
user_id=viewer["user"]["id"], created_at=self.m.now_ms(), expires_at=self.m.now_ms() + 60000, used=0,
))
await db.commit()
return owner, viewer, activity, token
async def test_private_or_expired_email_links_rejected(self):
owner, viewer, activity, token = await self.make_link()
url = f"/join/{token}"
await self.client.patch(f"/api/activities/{activity['id']}", headers=auth(owner["token"]), json={"visibility": "private"})
for method in ("get", "post"):
response = await getattr(self.client, method)(url)
self.assertIn("已失效", response.text)
self.assertNotIn(activity["title"], response.text)
async with self.sessions() as db:
self.assertIsNone(await self.m._require_participant(db, activity["id"], viewer["user"]["id"]))
await db.execute(update(self.m.join_links).values(expires_at=1))
await db.commit()
response = await self.client.post(url)
self.assertIn("已过期", response.text)
async def test_private_leave_response_does_not_expose_activity(self):
owner, viewer, activity, token = await self.make_link()
await self.client.post(f"/join/{token}")
await self.client.patch(f"/api/activities/{activity['id']}", headers=auth(owner["token"]), json={"visibility": "private"})
response = await self.client.post(f"/api/activities/{activity['id']}/leave", headers=auth(viewer["token"]))
self.assertEqual(response.json(), {"ok": True})
response = await self.client.get(f"/api/activities/{activity['id']}", headers=auth(viewer["token"]))
self.assertEqual(response.status_code, 403)
async def test_path_traversal_cannot_read_sibling_directory(self):
frontend = self.directory / "dist"
frontend.mkdir()
(frontend / "index.html").write_text("safe index", encoding="utf-8")
sibling = self.directory / "dist-private"
sibling.mkdir()
(sibling / "secret.txt").write_text("sibling secret", encoding="utf-8")
with patch.object(self.m, "FRONTEND_DIR", frontend):
response = await self.client.get("/%2e%2e%2fdist-private/secret.txt")
self.assertNotIn("sibling secret", response.text)
async def test_concurrent_code_and_join_link_only_consumed_once(self):
# 文件库提供独立连接,真实验证 SQLite 并发写入下的一次性语义。
file_engine = self.m.create_async_engine(f"sqlite+aiosqlite:///{(self.directory / 'concurrency.db').as_posix()}")
file_sessions = self.m.async_sessionmaker(file_engine, expire_on_commit=False)
try:
async with file_engine.begin() as conn:
await conn.run_sync(self.m.metadata.create_all)
with patch.object(self.m, "SessionLocal", file_sessions):
owner, viewer, activity, token = await self.make_link()
email = viewer["user"]["email"]
code = await get_code(self.client, email, "login")
replies = await asyncio.gather(*[
self.client.post("/api/auth/login", json={"email": email, "email_code": code}) for _ in range(2)
])
self.assertEqual(sorted(r.status_code for r in replies), [200, 400])
replies = await asyncio.gather(*[self.client.post(f"/join/{token}") for _ in range(2)])
self.assertEqual(sum("记录成功" in r.text for r in replies), 1)
async with file_sessions() as db:
rows = (await db.execute(select(self.m.participations).where(
self.m.participations.c.activity_id == activity["id"],
self.m.participations.c.user_id == viewer["user"]["id"],
))).all()
self.assertEqual(len(rows), 1)
finally:
await file_engine.dispose()
async def test_legacy_migration_is_idempotent(self):
owner, viewer, activity, token = await self.make_link()
plain = self.m.new_token()
async with self.engine.begin() as conn:
await conn.execute(insert(self.m.sessions).values(token=plain, user_id=owner["user"]["id"], created_at=1, expires_at=self.m.now_ms() + 60000))
await conn.execute(insert(self.m.email_verifications).values(id="legacy", email="legacy@example.test", code="123456", purpose="login", used=0, created_at=1, expires_at=self.m.now_ms() + 60000))
await conn.execute(update(self.m.join_links).values(token=token))
await self.m._migrate_legacy(conn)
await self.m._migrate_legacy(conn)
self.assertEqual((await self.client.get("/api/auth/me", headers=auth(plain))).status_code, 200)
self.assertIn("确认参加", (await self.client.get(f"/join/{token}")).text)
async with self.sessions() as db:
self.assertIsNone((await db.execute(select(self.m.email_verifications).where(self.m.email_verifications.c.id == "legacy"))).first())