87 lines
3.0 KiB
Python
87 lines
3.0 KiB
Python
from __future__ import annotations
|
|
|
|
import io
|
|
import json
|
|
import tempfile
|
|
import unittest
|
|
import zipfile
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
from fetch_daily import (
|
|
CmbMailError,
|
|
classify_failure,
|
|
download_link_from_body,
|
|
fetch,
|
|
safe_extract,
|
|
)
|
|
|
|
|
|
class FetchDailyTest(unittest.TestCase):
|
|
def test_extracts_download_link_and_date_range(self) -> None:
|
|
body = """
|
|
<p>链接:
|
|
<a href="s3gw.cmbimg.com/example/file.zip?filename=%E8%B4%A6%E5%8D%95-20261101-20261124.zip">
|
|
点击此处下载文件
|
|
</a>
|
|
</p>
|
|
"""
|
|
|
|
link = download_link_from_body(body)
|
|
|
|
self.assertIsNotNone(link)
|
|
self.assertEqual("20261101", link.date_start)
|
|
self.assertEqual("20261124", link.date_end)
|
|
|
|
def test_rejects_unsafe_zip_member(self) -> None:
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
root = Path(temporary)
|
|
archive = root / "statement.zip"
|
|
with zipfile.ZipFile(archive, "w") as output:
|
|
output.writestr("../outside.xlsx", b"bad")
|
|
|
|
with self.assertRaises(CmbMailError):
|
|
safe_extract(archive, root / "contents")
|
|
|
|
def test_extracts_supported_statement_file(self) -> None:
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
root = Path(temporary)
|
|
archive = root / "statement.zip"
|
|
with zipfile.ZipFile(archive, "w") as output:
|
|
output.writestr("企业账户交易明细.xlsx", b"fixture")
|
|
|
|
files = safe_extract(archive, root / "contents")
|
|
|
|
self.assertEqual(1, len(files))
|
|
self.assertEqual("企业账户交易明细.xlsx", files[0]["name"])
|
|
self.assertTrue(Path(files[0]["path"]).is_file())
|
|
|
|
def test_classifies_mailbox_and_statement_failures(self) -> None:
|
|
self.assertEqual("auth", classify_failure("b'[AUTHENTICATIONFAILED] LOGIN failed'"))
|
|
self.assertEqual("not_found", classify_failure("2026-11-24 的招商银行账单邮件未找到。"))
|
|
self.assertEqual("download", classify_failure("招商银行账单下载为空。"))
|
|
self.assertEqual("archive", classify_failure("招商银行 ZIP 包含不安全文件路径。"))
|
|
|
|
def test_writes_a_safe_failure_state_when_configuration_is_missing(self) -> None:
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
root = Path(temporary)
|
|
run_dir = root / "run"
|
|
args = SimpleNamespace(
|
|
config=str(root / "missing-config.json"),
|
|
date="2026-11-24",
|
|
out=str(root / "exports"),
|
|
run_dir=str(run_dir),
|
|
)
|
|
|
|
with self.assertRaises(CmbMailError):
|
|
fetch(args)
|
|
|
|
state = json.loads((run_dir / "last-fetch.json").read_text(encoding="utf-8"))
|
|
self.assertFalse(state["ok"])
|
|
self.assertEqual("config", state["error_type"])
|
|
self.assertIn("配置", state["reason"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|