Files
worklog/tests/test_maillog.py
T
azzz 5c4b8d84ed 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 项全覆盖(注册/登录/活动/通知/备份/日志/安全)
2026-10-29 19:00:48 +08:00

69 lines
2.5 KiB
Python

"""发信日志(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()