from types import SimpleNamespace import pytest from snooper_membership import ( MembershipError, fetch_self_join_times, filter_rows_by_membership, ) def row(chat_id, chat_type, create_time): return SimpleNamespace( chat_id=chat_id, chat_type=chat_type, create_time=create_time ) def test_membership_filter_excludes_prejoin_and_unknown_group_history(): rows = [ row("group-a", 2, 99), row("group-a", 2, 100), row("group-a", 2, 101), row("group-unknown", 2, 101), row("private-a", 1, 1), ] filtered, stats = filter_rows_by_membership(rows, {"group-a": 100}) assert [row.create_time for row in filtered] == [100, 101, 1] assert stats["excluded_before_join"] == 1 assert stats["excluded_unknown"] == 1 assert stats["excluded_chats"] == 2 def test_fetch_join_time_paginates_and_caches_positive_evidence(tmp_path): client = SimpleNamespace( auth=SimpleNamespace(user_id="self"), responses=[ {"joinTimesSec": {"other": 1}, "nextCursor": "next"}, {"joinTimesSec": {"self": 123}, "nextCursor": None}, ], calls=[], ) def api(name, request): client.calls.append(request) return client.responses.pop(0) client.api = api cache = tmp_path / "join-times.json" first = fetch_self_join_times(client, {"chat-a"}, cache) second = fetch_self_join_times(client, {"chat-a"}, cache) assert first["chat-a"] == 123 assert second["chat-a"] == 123 assert len(client.calls) == 2 assert client.calls[1]["cursor"] == "next" def test_missing_user_id_fails_closed(tmp_path): client = SimpleNamespace(auth=SimpleNamespace(user_id="")) with pytest.raises(MembershipError): fetch_self_join_times(client, {"chat-a"}, tmp_path / "cache.json") def test_batch_prefetch_marks_inaccessible_group_unknown(tmp_path): client = SimpleNamespace(auth=SimpleNamespace(user_id="self")) def fail_api(name, request): raise RuntimeError("synthetic inaccessible group") client.api = fail_api result = fetch_self_join_times( client, {"chat-old"}, tmp_path / "cache.json", strict=False ) assert result["chat-old"] == 0