from datetime import date from zoneinfo import ZoneInfo from larkx.storage import 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 larkx.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