| 1 | import io |
| 2 | import json |
| 3 | import threading |
| 4 | import time |
| 5 | import urllib.error |
| 6 | from concurrent.futures import ThreadPoolExecutor |
| 7 | from unittest.mock import Mock |
| 8 | from urllib.parse import parse_qs, urlsplit |
| 9 | |
| 10 | import pytest |
| 11 | |
| 12 | from lib import health, http, instagram, pipeline, schema |
| 13 | |
| 14 | |
| 15 | def response(payload): |
| 16 | result = io.BytesIO(json.dumps(payload).encode()) |
| 17 | result.status = 200 |
| 18 | return result |
| 19 | |
| 20 | |
| 21 | def post(shortcode): |
| 22 | return {"data": {"xdt_shortcode_media": { |
| 23 | "id": shortcode, |
| 24 | "shortcode": shortcode, |
| 25 | "taken_at_timestamp": 1786900800, |
| 26 | "caption": "Coffee roasting guide", |
| 27 | "owner": {"username": "test_creator"}, |
| 28 | }}} |
| 29 | |
| 30 | |
| 31 | def test_stream_retains_completed_detail_before_its_deadline(monkeypatch): |
| 32 | release = threading.Event() |
| 33 | finished = threading.Event() |
| 34 | requests = [] |
| 35 | |
| 36 | def transport(request, timeout): |
| 37 | url = urlsplit(request.full_url) |
| 38 | query = parse_qs(url.query) |
| 39 | requests.append((url.path, timeout)) |
| 40 | if url.path == "/v2/instagram/reels/search": |
| 41 | raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}")) |
| 42 | if url.path == "/v1/google/search": |
| 43 | return response({"results": [ |
| 44 | {"url": "https://www.instagram.com/reel/SLOW/"}, |
| 45 | {"url": "https://www.instagram.com/reel/FAST/"}, |
| 46 | ]}) |
| 47 | if url.path == "/v1/instagram/post": |
| 48 | if "/SLOW/" in query["url"][0]: |
| 49 | try: |
| 50 | release.wait(3) |
| 51 | return response(post("SLOW")) |
| 52 | finally: |
| 53 | finished.set() |
| 54 | return response(post("FAST")) |
| 55 | raise AssertionError(f"Unexpected paid request: {url.path}") |
| 56 | |
| 57 | monkeypatch.setattr(http, "_open_request", transport) |
| 58 | config = { |
| 59 | "SCRAPECREATORS_API_KEY": "dummy-key", |
| 60 | "INCLUDE_SOURCES": "instagram,instagram_comments", |
| 61 | "_research_deadline": time.monotonic() + 1, |
| 62 | } |
| 63 | with ThreadPoolExecutor(max_workers=1) as executor: |
| 64 | future = executor.submit( |
| 65 | pipeline._retrieve_stream, |
| 66 | topic="coffee", |
| 67 | subquery=schema.SubQuery( |
| 68 | label="primary", search_query="coffee", ranking_query="coffee", |
| 69 | sources=["instagram"], weight=1.0, |
| 70 | ), |
| 71 | source="instagram", config=config, depth="default", |
| 72 | date_range=("2026-08-01", "2026-08-31"), runtime=Mock(), mock=False, |
| 73 | ) |
| 74 | try: |
| 75 | done, pending = pipeline._wait_for_research([future], config) |
| 76 | assert not pending, "Instagram must return its recovered reels before the stream expires" |
| 77 | items, artifact = future.result() |
| 78 | assert [item["video_id"] for item in items] == ["FAST"] |
| 79 | assert artifact["_source_outcome"]["state"] == health.PARTIAL |
| 80 | assert "timed out" in artifact["_source_outcome"]["detail"] |
| 81 | assert len(requests) == 4 |
| 82 | assert all(0 < timeout < 1 for _, timeout in requests) |
| 83 | finally: |
| 84 | release.set() |
| 85 | assert finished.wait(2) |
| 86 | |
| 87 | |
| 88 | @pytest.mark.parametrize("stage", ["creator", "query", "transcript"]) |
| 89 | def test_cancellation_retains_items_and_stops_later_requests(monkeypatch, stage): |
| 90 | cancel = threading.Event() |
| 91 | requests = [] |
| 92 | reel = { |
| 93 | "id": "EARLY", "shortcode": "EARLY", "caption": "Coffee roasting guide", |
| 94 | "taken_at": "2026-08-16T12:00:00Z", "owner": {"username": "test_creator"}, |
| 95 | } |
| 96 | |
| 97 | def transport(request, timeout): |
| 98 | path = urlsplit(request.full_url).path |
| 99 | requests.append(path) |
| 100 | if path == "/v1/instagram/user/reels": |
| 101 | if requests.count(path) == 2: |
| 102 | cancel.set() |
| 103 | return response({"items": [{"media": reel}]}) |
| 104 | if path == "/v2/instagram/reels/search": |
| 105 | if stage == "query" and requests.count(path) == 2: |
| 106 | cancel.set() |
| 107 | return response({"reels": [reel]}) |
| 108 | if path == "/v2/instagram/media/transcript": |
| 109 | cancel.set() |
| 110 | return response({"transcripts": [{"text": "Fresh transcript"}]}) |
| 111 | raise AssertionError(f"Unexpected paid request: {path}") |
| 112 | |
| 113 | monkeypatch.setattr(http, "_open_request", transport) |
| 114 | result = instagram.search_and_enrich( |
| 115 | "coffee", "2026-08-01", "2026-08-31", token="dummy-key", |
| 116 | depth="quick" if stage == "transcript" else "deep", |
| 117 | ig_creators=["first", "second", "third"] if stage == "creator" else None, |
| 118 | deadline=time.monotonic() + 2, cancel=cancel, |
| 119 | ) |
| 120 | assert [item["video_id"] for item in result["items"]] == ["EARLY"] |
| 121 | expected = { |
| 122 | "creator": ["/v1/instagram/user/reels"] * 2, |
| 123 | "query": ["/v2/instagram/reels/search"] * 2, |
| 124 | "transcript": ["/v2/instagram/reels/search", "/v2/instagram/media/transcript"], |
| 125 | } |
| 126 | assert requests == expected[stage] |
| 127 | assert "cancelled" in result["error"] |
| 128 | |
| 129 | |
| 130 | def test_transcript_timeout_preserves_free_captions_and_skips_next_transcript(monkeypatch): |
| 131 | release = threading.Event() |
| 132 | finished = threading.Event() |
| 133 | requests = [] |
| 134 | items = [ |
| 135 | {"video_id": name, "url": f"https://www.instagram.com/reel/{name}/", "text": f"Caption {name}"} |
| 136 | for name in ("FIRST", "SECOND") |
| 137 | ] |
| 138 | |
| 139 | def transport(request, timeout): |
| 140 | requests.append(request.full_url) |
| 141 | try: |
| 142 | release.wait(2) |
| 143 | return response({"transcripts": [{"text": "Too late"}]}) |
| 144 | finally: |
| 145 | finished.set() |
| 146 | |
| 147 | monkeypatch.setattr(http, "_open_request", transport) |
| 148 | try: |
| 149 | captions = instagram.fetch_captions(items, "dummy-key", deadline=time.monotonic() + 0.15) |
| 150 | assert captions == {"FIRST": "Caption FIRST", "SECOND": "Caption SECOND"} |
| 151 | assert len(requests) == 1 |
| 152 | finally: |
| 153 | release.set() |
| 154 | assert finished.wait(2) |
| 155 | |
| 156 | |
| 157 | def test_comment_timeout_keeps_completed_comments_without_late_mutation(monkeypatch): |
| 158 | release = threading.Event() |
| 159 | finished = threading.Event() |
| 160 | items = [ |
| 161 | {"video_id": name, "url": f"https://www.instagram.com/reel/{name}/", "engagement": {"likes": 10}} |
| 162 | for name in ("SLOW", "FAST") |
| 163 | ] |
| 164 | |
| 165 | def transport(request, timeout): |
| 166 | query = parse_qs(urlsplit(request.full_url).query) |
| 167 | if "/SLOW/" in query["url"][0]: |
| 168 | try: |
| 169 | release.wait(2) |
| 170 | return response({"comments": [{"text": "Too late", "comment_like_count": 100}]}) |
| 171 | finally: |
| 172 | finished.set() |
| 173 | return response({"comments": [{"text": "Helpful early comment", "comment_like_count": 50}]}) |
| 174 | |
| 175 | monkeypatch.setattr(http, "_open_request", transport) |
| 176 | try: |
| 177 | result = instagram.enrich_with_comments(items, "dummy-key", deadline=time.monotonic() + 0.15) |
| 178 | assert result is items |
| 179 | assert "top_comments" not in items[0] |
| 180 | assert items[1]["top_comments"][0]["text"] == "Helpful early comment" |
| 181 | snapshot = json.dumps(items) |
| 182 | finally: |
| 183 | release.set() |
| 184 | assert finished.wait(2) |
| 185 | assert json.dumps(items) == snapshot |
| 186 | |
| 187 | |
| 188 | def test_cancellation_stops_queued_detail_requests(monkeypatch): |
| 189 | cancel = threading.Event() |
| 190 | in_flight = threading.Barrier(4) |
| 191 | requests = [] |
| 192 | |
| 193 | def transport(request, timeout): |
| 194 | path = urlsplit(request.full_url).path |
| 195 | requests.append(path) |
| 196 | if path == "/v1/google/search": |
| 197 | return response({"results": [ |
| 198 | {"url": f"https://www.instagram.com/reel/POST{index}/"} |
| 199 | for index in range(9) |
| 200 | ]}) |
| 201 | in_flight.wait(timeout=2) |
| 202 | cancel.set() |
| 203 | return response(post("POST0")) |
| 204 | |
| 205 | monkeypatch.setattr(http, "_open_request", transport) |
| 206 | instagram._google_reel_fallback( |
| 207 | "coffee", "quick", "dummy-key", "2026-08-01", "2026-08-31", |
| 208 | deadline=time.monotonic() + 2, cancel=cancel, |
| 209 | ) |
| 210 | assert requests == ["/v1/google/search"] + ["/v1/instagram/post"] * 4 |
| 211 | |
| 212 | |
| 213 | @pytest.mark.parametrize("depth,pages,posts", [("quick", 1, 9), ("default", 2, 16), ("deep", 3, 27)]) |
| 214 | def test_deadline_enabled_recovery_preserves_paid_request_caps(monkeypatch, depth, pages, posts): |
| 215 | requests = [] |
| 216 | page_count = 0 |
| 217 | |
| 218 | def transport(request, timeout): |
| 219 | nonlocal page_count |
| 220 | url = urlsplit(request.full_url) |
| 221 | query = parse_qs(url.query) |
| 222 | requests.append(url.path) |
| 223 | if url.path == "/v2/instagram/reels/search": |
| 224 | raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}")) |
| 225 | if url.path == "/v1/google/search": |
| 226 | page_count += 1 |
| 227 | return response({"results": [ |
| 228 | {"url": f"https://www.instagram.com/reel/P{page_count}_{index}/"} |
| 229 | for index in range(40) |
| 230 | ]}) |
| 231 | if url.path == "/v1/instagram/post": |
| 232 | return response(post(urlsplit(query["url"][0]).path.split("/")[2])) |
| 233 | if url.path == "/v2/instagram/media/transcript": |
| 234 | return response({"transcripts": []}) |
| 235 | raise AssertionError(f"Unexpected paid request: {url.path}") |
| 236 | |
| 237 | monkeypatch.setattr(http, "_open_request", transport) |
| 238 | result = instagram.search_and_enrich( |
| 239 | "coffee", "2026-08-01", "2026-08-31", token="dummy-key", depth=depth, |
| 240 | deadline=time.monotonic() + 5, |
| 241 | ) |
| 242 | assert len(result["items"]) == posts |
| 243 | assert not result["error"] |
| 244 | assert requests.count("/v1/google/search") == pages |
| 245 | assert requests.count("/v1/instagram/post") == posts |
| 246 |