Files

213 lines
9.8 KiB
Python

"""邮件通知与一键参加功能测试。
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)
import re
nonce = re.search(r'name="confirmation_token" value="([^"]+)"', r.text).group(1)
r = await c.post(f"/join/{token}", data={'confirmation_token': nonce}, headers={'Origin': 'null', 'Sec-Fetch-Site': 'cross-site'})
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"))
page = await c.get(carol_url)
nonce = re.search(r'name="confirmation_token" value="([^"]+)"', page.text).group(1)
r = await c.post(carol_url, data={'confirmation_token': nonce})
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))