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