Files
Lark-Snooper/tests/test_history.py
Benature c8658ad064 feat: 历史同步优化与消息已读属性
- 历史同步: 本地缓存优先、断点续传、按月批量同步
- 新增 sync_monthly.py: 支持逐月往前推进同步
- 消息表新增 is_read 字段,默认 false
- Obsidian 文档 frontmatter 自动补充 is_read: false
- 新增 migrate_add_is_read.py / migrate_obsidian_is_read.py 迁移脚本
- 总结 prompt 补充: 不记录腾讯会议号
- 历史同步失败时记录日志到 ~/.larkx/logs/history-failures.jsonl
2026-11-08 11:31:18 +08:00

193 lines
6.0 KiB
Python

import json
import stat
from datetime import date
from zoneinfo import ZoneInfo
from snooper_storage import SnifferStorage as Storage
class FakeClient:
def __init__(self, start_ts):
self.start_ts = start_ts
self.feed_calls = []
self.history_calls = []
def api(self, name, data):
assert name == "feed.PullFeedCardsRequest"
self.feed_calls.append(data)
if data["pullType"] == "REFRESH":
return {
"cards": [{"id": "group-a", "type": 1}],
"chats": {
"group-a": {
"id": "group-a",
"name": "合成群",
"type": 2,
"lastMessagePosition": 2,
"firstChatMessagePosition": 1,
}
},
"nextCursor": 2,
}
assert data["pullType"] == "LOAD_MORE"
assert data["cursor"] == 2
return {
"cards": [{"id": "private-b", "type": 1}],
"chats": {
"private-b": {
"id": "private-b",
"name": "合成同事",
"type": 1,
"lastMessagePosition": 1,
"firstChatMessagePosition": 1,
}
},
}
def pull_history(self, chat_id, positions, **kwargs):
self.history_calls.append((chat_id, positions, kwargs))
messages = {
("group-a", 1): {
"msg_id": "old",
"chat_id": "group-a",
"chat_type": 2,
"from_id": "other",
"create_time": self.start_ts - 1,
"content": "合成旧消息",
},
("group-a", 2): {
"msg_id": "incoming",
"chat_id": "group-a",
"chat_type": 2,
"from_id": "other",
"create_time": self.start_ts + 10,
"content": "合成收到",
},
("private-b", 1): {
"msg_id": "outgoing",
"chat_id": "private-b",
"chat_type": 1,
"from_id": "self",
"create_time": self.start_ts + 20,
"content": "合成发出",
},
}
return [
messages[(chat_id, position)]
for position in positions
if (chat_id, position) in messages
]
def test_sync_all_chats_for_day_saves_only_dated_messages_with_direction():
from snooper_history import sync_all_chats_for_day
tz = ZoneInfo("Asia/Shanghai")
start_ts = 1_792_000_000
client = FakeClient(start_ts)
client.auth = type("Auth", (), {"user_id": "self"})()
storage = Storage(url="sqlite:///:memory:")
stats = sync_all_chats_for_day(
client,
storage,
date(2026, 11, 3),
tz,
batch_size=2,
start_ts=start_ts,
end_ts=start_ts + 86_400,
)
assert stats["chats"] == 2
assert stats["matched"] == 2
assert stats["saved"] == 2
assert stats["failed"] == 0
rows = storage.get_received_messages(start_ts, start_ts + 86_400)
assert [row.msg_id for row in rows] == ["incoming"]
assert rows[0].chat_name == "合成群"
outgoing = storage.get_messages("private-b")
assert [row.direction for row in outgoing] == ["out"]
assert len(client.feed_calls) == 2
assert client.history_calls[0][2]["visible_only"] is True
def test_sync_all_chats_for_day_excludes_configured_chat_before_history_pull():
from snooper_history import sync_all_chats_for_day
tz = ZoneInfo("Asia/Shanghai")
start_ts = 1_792_000_000
client = FakeClient(start_ts)
client.auth = type("Auth", (), {"user_id": "self"})()
storage = Storage(url="sqlite:///:memory:")
stats = sync_all_chats_for_day(
client,
storage,
date(2026, 11, 3),
tz,
batch_size=2,
start_ts=start_ts,
end_ts=start_ts + 86_400,
exclude_chat_ids=["private-b"],
)
assert stats["chats"] == 1
assert stats["matched"] == 1
assert stats["saved"] == 1
assert [call[0] for call in client.history_calls] == ["group-a"]
assert storage.get_messages("private-b") == []
def test_history_failure_log_identifies_chat_without_sensitive_error_body(tmp_path):
from snooper_history import (
format_history_failures,
sync_all_chats_for_day,
write_history_failures,
)
class FailingClient(FakeClient):
def pull_history(self, chat_id, positions, **kwargs):
if chat_id == "group-a":
raise RuntimeError("敏感合成上游响应正文")
return super().pull_history(chat_id, positions, **kwargs)
tz = ZoneInfo("Asia/Shanghai")
start_ts = 1_792_000_000
client = FailingClient(start_ts)
client.auth = type("Auth", (), {"user_id": "self"})()
storage = Storage(url="sqlite:///:memory:")
target_day = date(2026, 11, 3)
stats = sync_all_chats_for_day(
client,
storage,
target_day,
tz,
batch_size=2,
start_ts=start_ts,
end_ts=start_ts + 86_400,
)
assert stats["failed"] == 1
assert stats["failures"] == [
{
"chat_id": "group-a",
"chat_name": "合成群",
"error_type": "RuntimeError",
}
]
assert "合成群 (group-a): RuntimeError" in format_history_failures(
stats["failures"]
)
log_path = write_history_failures(
target_day, stats["failures"], tmp_path / "history-failures.jsonl"
)
record = json.loads(log_path.read_text(encoding="utf-8"))
assert record["date"] == "2026-11-03"
assert record["logged_at"].endswith("+00:00")
assert record["chat_id"] == "group-a"
assert record["chat_name"] == "合成群"
assert record["error_type"] == "RuntimeError"
assert "敏感合成上游响应正文" not in log_path.read_text(encoding="utf-8")
assert stat.S_IMODE(log_path.stat().st_mode) == 0o600