feat: track duty email confirmations and add throttled account email tests

This commit is contained in:
2026-11-06 15:07:48 +08:00
parent 867443163a
commit 0a7a641430
11 changed files with 352 additions and 16 deletions
+41 -1
View File
@@ -89,13 +89,53 @@ class ApiTestCase(unittest.IsolatedAsyncioTestCase):
class WorkLogApiTests(ApiTestCase):
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
self.assertEqual((await self.client.get(url)).status_code, 200)
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)
self.assertEqual((await self.client.post(url)).status_code, 200)
self.assertEqual((await self.client.post('/api/duty/remind', json=request, headers=auth(u['token']))).status_code, 429)
self.assertEqual(send.await_count, 1)
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") as clock:
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)
+1
View File
@@ -81,6 +81,7 @@ class DutyTests(unittest.IsolatedAsyncioTestCase):
import sqlite3
with closing(sqlite3.connect(self.state)) as db:
db.execute("UPDATE deliveries SET updated=0")
db.execute("UPDATE duty_receipts SET last_attempt=0")
db.commit()
result = await send_due(self.schedule, self.now, self.accounts[:1], send, self.state)
self.assertEqual(result["sent"], 1)
+51
View File
@@ -0,0 +1,51 @@
import asyncio
import tempfile
import unittest
from pathlib import Path
from unittest.mock import AsyncMock
from server import duty_receipts as r
class ReceiptsTests(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.path = Path(self.tmp.name) / 'state.db'
def tearDown(self):
self.tmp.cleanup()
async def test_three_attempts_and_confirmation_suppresses_reminders(self):
names = {'同学': ['一二节']}
send = AsyncMock()
tokens = []
for now in [1000, 1061, 1122]:
self.assertTrue(await r.send_notice(self.path, '2026-11-06', names, 'a@example.test', 9999, send, '提醒', '正文', 'https://example.test', now))
tokens.append(send.await_args.args[2].split('/duty-confirm/')[1].split()[0])
self.assertFalse(await r.send_notice(self.path, '2026-11-06', names, 'a@example.test', 9999, send, '提醒', '正文', 'https://example.test', 1200))
state = r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1200)
self.assertEqual(state['sent_count'], 3)
self.assertEqual(state['last_sent_at'], 1122000)
# 邮件扫描 GET 不确认,POST 确认可重复调用且不改变首次确认时间。
self.assertIsNotNone(r.confirmation(self.path, tokens[0], 1200))
self.assertIsNone(r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1200)['confirmed_at'])
r.confirmation(self.path, tokens[0], 1200, True)
r.confirmation(self.path, tokens[0], 1250, True)
self.assertEqual(r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1250)['confirmed_at'], 1200000)
self.assertIsNone(r.confirmation(self.path, tokens[0], 10000, True))
self.assertIsNone(r.confirmation(self.path, 'invalid', 1200, True))
async def test_confirmed_person_stops_early_and_concurrent_sends_cannot_bypass_limit(self):
names = {'同学': ['一二节']}
async def attempt():
return await asyncio.to_thread(r.reserve, self.path, '2026-11-06', names, 'a@example.test', 9999, 1000)
results = await asyncio.gather(*(attempt() for _ in range(5)))
self.assertEqual(sum(bool(token) for token, _ in results), 1)
token = next(token for token, _ in results if token)
r.confirmation(self.path, token, 1010, True)
self.assertEqual(r.reserve(self.path, '2026-11-06', names, 'a@example.test', 9999, 1100), (None, {}))
self.assertIsNotNone(r.reserve(self.path, '2026-11-06', {'同学': ['三四节']}, 'a@example.test', 9999, 1100)[0])
async def test_test_mail_limit_is_persistent_and_case_insensitive(self):
self.assertTrue(r.reserve_test(self.path, 'Student@example.test', 1000))
self.assertFalse(r.reserve_test(self.path, 'student@example.test', 1119))
self.assertTrue(r.reserve_test(self.path, 'student@example.test', 1120))