Files
worklog/tests/test_api.py
T

579 lines
32 KiB
Python

"""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
from sqlalchemy import select
# 测试口令每次运行随机生成(仅用于本机内存库,非真实凭据)
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_button_test_emails_are_private_throttled_and_do_not_change_real_records(self):
from unittest.mock import AsyncMock
import re
self.assertEqual((await self.client.post('/api/auth/test-button-email', json={'kind':'duty'})).status_code, 401)
owner = await register(self.client, 'buttontester')
for kind in ('duty', 'activity'):
with tempfile.TemporaryDirectory() as directory:
with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send:
response = await self.client.post('/api/auth/test-button-email', headers=auth(owner['token']), json={'kind':kind,'email':'other@example.test'})
self.assertEqual(response.status_code, 200)
self.assertEqual(send.await_args.args[0], owner['user']['email'])
token = send.await_args.args[2].split('/mail-test/')[1].split()[0]
url = '/mail-test/' + token
page = await self.client.get(url)
self.assertEqual(page.status_code, 200)
nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1)
self.assertEqual((await self.client.post(url, headers={'Origin':'null','Sec-Fetch-Site':'cross-site'})).status_code, 403)
response = await self.client.post(url, data={'confirmation_token':nonce}, headers={'Origin':'null','Sec-Fetch-Site':'cross-site'})
self.assertEqual(response.status_code, 200)
self.assertIn('按钮测试确认成功', response.text)
self.assertEqual((await self.client.post('/api/auth/test-email', headers=auth(owner['token']))).status_code, 429)
self.assertEqual((await self.client.post('/api/auth/test-button-email', headers=auth(owner['token']), json={'kind':kind})).status_code, 429)
self.assertEqual(send.await_count, 1)
async with self.sessions() as db:
self.assertFalse((await db.execute(select(self.m.activities))).all())
self.assertFalse((await db.execute(select(self.m.participations))).all())
async def test_confirm_own_duty_on_site_without_email(self):
from datetime import datetime
from unittest.mock import AsyncMock
from server.duty import BEIJING, ROOT, load_schedule, duty_status
schedule = load_schedule(ROOT / 'duty/schedule.json')
data = duty_status(schedule, datetime.now(BEIJING))
shift = data['current'] or data['next']
name = shift['names'][0]
owner = await register(self.client, name)
other = await register(self.client, '非本轮同学')
request = {'start_at': shift['start_at']}
with tempfile.TemporaryDirectory() as directory:
with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send:
self.assertEqual((await self.client.post('/api/duty/confirm', json=request)).status_code, 401)
self.assertEqual((await self.client.post('/api/duty/confirm', headers=auth(other['token']), json=request)).status_code, 403)
self.assertEqual((await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json={**request, 'name': other['user']['display_name']})).status_code, 422)
self.assertEqual((await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json={'start_at': 1})).status_code, 409)
before = (await self.client.get('/api/duty/current', headers=auth(owner['token']))).json()
own_shift = next(s for s in (before['current'], before['next']) if s and s['start_at'] == shift['start_at'])
self.assertTrue(next(r for r in own_shift['reminders'] if r['name'] == name)['can_confirm'])
response = await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json=request)
self.assertEqual(response.status_code, 200, response.text)
repeat = await self.client.post('/api/duty/confirm', headers=auth(owner['token']), json=request)
self.assertEqual(response.json()['confirmed_at'], repeat.json()['confirmed_at'])
after = (await self.client.get('/api/duty/current', headers=auth(owner['token']))).json()
own_shift = next(s for s in (after['current'], after['next']) if s and s['start_at'] == shift['start_at'])
receipt = next(r for r in own_shift['reminders'] if r['name'] == name)
self.assertFalse(receipt['can_confirm'])
self.assertFalse(receipt['can_remind'])
self.assertEqual(receipt['attempts'], 0)
self.assertEqual(receipt['sent_count'], 0)
send.assert_not_called()
import sqlite3
with sqlite3.connect(Path(directory) / 'state.db') as state:
self.assertFalse(state.execute("SELECT 1 FROM sqlite_master WHERE name IN ('duty_absences','duty_audit_state')").fetchall())
state.close()
async with self.sessions() as db:
self.assertFalse((await db.execute(select(self.m.activities))).all())
self.assertFalse((await db.execute(select(self.m.participations))).all())
async def test_same_named_accounts_cannot_claim_duty(self):
from datetime import datetime
from server.duty import BEIJING, ROOT, load_schedule, duty_status
data = duty_status(load_schedule(ROOT / 'duty/schedule.json'), datetime.now(BEIJING))
shift = data['current'] or data['next']
name = shift['names'][0]
first = await register(self.client, name)
await register(self.client, name, email='same-name@example.test', phone='13900009999')
with tempfile.TemporaryDirectory() as directory:
with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'):
response = await self.client.post('/api/duty/confirm', headers=auth(first['token']), json={'start_at': shift['start_at']})
self.assertEqual(response.status_code, 403)
async def test_duty_reminder_and_confirmation_flow(self):
from datetime import datetime
from unittest.mock import AsyncMock
from server.duty import BEIJING, duty_status, load_schedule, ROOT
status = duty_status(load_schedule(ROOT / 'duty/schedule.json'), datetime.now(BEIJING))
shift = status['current'] or status['next']
name = shift['names'][0]
u = await register(self.client, name)
with tempfile.TemporaryDirectory() as directory:
with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send:
request = {'name': name, 'start_at': shift['start_at']}
response = await self.client.post('/api/duty/remind', json=request, headers=auth(u['token']))
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(send.await_args.args[0], u['user']['email'])
self.assertIn('确认已知晓', send.await_args.args[3])
token = send.await_args.args[2].split('/duty-confirm/')[1].split()[0]
url = '/duty-confirm/' + token
page = await self.client.get(url)
self.assertEqual(page.status_code, 200)
self.assertIn('值班邮件确认', page.text)
self.assertNotIn('确认参加', page.text)
import re
nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1)
self.assertEqual((await self.client.post(url, headers={'Origin': 'null', 'Sec-Fetch-Site': 'cross-site'})).status_code, 410)
state = (await self.client.get('/api/duty/current', headers=auth(u['token']))).json()
selected = next(s for s in (state['current'], state['next']) if s and s['start_at'] == shift['start_at'])
row = next(r for r in selected['reminders'] if r['name'] == name)
self.assertIsNone(row['confirmed_at'])
self.assertEqual(row['sent_count'], 1)
confirmed = await self.client.post(url, data={'confirmation_token': nonce}, headers={'Origin': 'null', 'Sec-Fetch-Site': 'cross-site'})
self.assertEqual(confirmed.status_code, 200)
self.assertIn('已确认值班安排', confirmed.text)
self.assertEqual(confirmed.headers['Cache-Control'], 'no-store')
# 值班确认不会创建活动或参加记录。
async with self.sessions() as db:
self.assertFalse((await db.execute(select(self.m.activities))).all())
self.assertFalse((await db.execute(select(self.m.participations))).all())
self.assertEqual((await self.client.post('/api/duty/remind', json=request, headers={**auth(u['token']), 'Origin': 'null', 'Sec-Fetch-Site': 'cross-site'})).status_code, 403)
self.assertEqual((await self.client.post('/api/duty/remind', json=request, headers=auth(u['token']))).status_code, 429)
self.assertEqual(send.await_count, 1)
self.assertEqual((await self.client.get('/api/duty/absences')).status_code, 401)
absence_response = await self.client.get('/api/duty/absences', headers=auth(u['token']))
self.assertEqual(absence_response.status_code, 200)
self.assertFalse(absence_response.json()['recording_enabled'])
self.assertNotIn('email', absence_response.text)
async def test_test_email_only_uses_current_account_and_limits_two_minutes(self):
from unittest.mock import AsyncMock
c = self.client
self.assertEqual((await c.post('/api/auth/test-email')).status_code, 401)
u = await register(c, 'mailtester')
with tempfile.TemporaryDirectory() as directory:
with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send:
response = await c.post('/api/auth/test-email', headers=auth(u['token']), json={'email': 'other@example.test'})
self.assertEqual(response.status_code, 200)
self.assertEqual(send.await_args.args[0], u['user']['email'])
self.assertEqual((await c.post('/api/auth/test-email', headers=auth(u['token']))).status_code, 429)
self.assertEqual(send.await_count, 1)
async def test_wall_duty_requires_login_and_only_exposes_schedule(self):
from datetime import datetime
from server.duty import BEIJING
c = self.client
self.assertEqual((await c.get("/api/duty/current")).status_code, 401)
u = await register(c, "dutyviewer")
with patch.object(self.m, "datetime", wraps=datetime) as clock:
clock.now.return_value = datetime(2026, 11, 6, 8, 30, tzinfo=BEIJING)
r = await c.get("/api/duty/current", headers=auth(u["token"]))
self.assertEqual(r.status_code, 200)
self.assertEqual(r.json()["current"]["names"], ["华秋豪"])
self.assertEqual(r.json()["current"]["end_at"] - r.json()["current"]["start_at"], 105 * 60000)
self.assertNotIn("email", r.text)
self.assertNotIn("phone", r.text)
# ------------------------------------------------------------- 账号
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()