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()