| 1 | """Tests for instagram.py — ScrapeCreators Instagram search module.""" |
| 2 | |
| 3 | import io |
| 4 | import json |
| 5 | import os |
| 6 | import unittest |
| 7 | import urllib.error |
| 8 | from urllib.parse import parse_qs, urlsplit |
| 9 | from unittest.mock import MagicMock, patch |
| 10 | |
| 11 | # Add lib to path |
| 12 | |
| 13 | from lib import instagram |
| 14 | from lib.relevance import tokenize as _tokenize |
| 15 | |
| 16 | |
| 17 | class TestTokenize(unittest.TestCase): |
| 18 | """Tests for tokenize() from relevance module.""" |
| 19 | |
| 20 | def test_strips_stopwords(self): |
| 21 | tokens = _tokenize("how to use the AI tools") |
| 22 | self.assertNotIn("how", tokens) |
| 23 | self.assertNotIn("the", tokens) |
| 24 | self.assertNotIn("to", tokens) |
| 25 | |
| 26 | def test_expands_synonyms(self): |
| 27 | tokens = _tokenize("ai tools") |
| 28 | self.assertTrue("artificial" in tokens or "intelligence" in tokens) |
| 29 | |
| 30 | def test_removes_single_char(self): |
| 31 | tokens = _tokenize("a b c python") |
| 32 | self.assertNotIn("a", tokens) |
| 33 | self.assertNotIn("b", tokens) |
| 34 | self.assertIn("python", tokens) |
| 35 | |
| 36 | def test_lowercases(self): |
| 37 | tokens = _tokenize("Python REACT") |
| 38 | self.assertIn("python", tokens) |
| 39 | self.assertIn("react", tokens) |
| 40 | |
| 41 | def test_strips_punctuation(self): |
| 42 | tokens = _tokenize("hello, world!") |
| 43 | self.assertIn("hello", tokens) |
| 44 | self.assertIn("world", tokens) |
| 45 | |
| 46 | |
| 47 | class TestComputeRelevance(unittest.TestCase): |
| 48 | """Tests for _compute_relevance().""" |
| 49 | |
| 50 | def test_exact_match_high(self): |
| 51 | rel = instagram._compute_relevance("claude code", "Claude Code tricks and tips") |
| 52 | self.assertGreaterEqual(rel, 0.8) |
| 53 | |
| 54 | def test_partial_match_lower(self): |
| 55 | rel = instagram._compute_relevance("claude code tips", "Best AI tools for coding") |
| 56 | self.assertLess(rel, 0.5) |
| 57 | |
| 58 | def test_hashtag_boost(self): |
| 59 | base = instagram._compute_relevance("claude code", "random video about stuff") |
| 60 | boosted = instagram._compute_relevance("claude code", "random video about stuff", ["claudecode", "ai"]) |
| 61 | self.assertGreater(boosted, base) |
| 62 | |
| 63 | def test_no_match_returns_zero(self): |
| 64 | rel = instagram._compute_relevance("quantum physics", "cat dancing video") |
| 65 | self.assertEqual(rel, 0.0) |
| 66 | |
| 67 | def test_empty_query_returns_default(self): |
| 68 | rel = instagram._compute_relevance("", "Some video title") |
| 69 | self.assertEqual(rel, 0.5) |
| 70 | |
| 71 | |
| 72 | class TestInstagramDepthConfig(unittest.TestCase): |
| 73 | """Tests for DEPTH_CONFIG.""" |
| 74 | |
| 75 | def test_all_depths_exist(self): |
| 76 | for depth in ("quick", "default", "deep"): |
| 77 | self.assertIn(depth, instagram.DEPTH_CONFIG) |
| 78 | |
| 79 | def test_required_keys(self): |
| 80 | for depth, config in instagram.DEPTH_CONFIG.items(): |
| 81 | self.assertIn("results_per_page", config) |
| 82 | self.assertIn("max_captions", config) |
| 83 | |
| 84 | def test_deep_has_more_results(self): |
| 85 | self.assertGreater( |
| 86 | instagram.DEPTH_CONFIG["deep"]["results_per_page"], |
| 87 | instagram.DEPTH_CONFIG["quick"]["results_per_page"], |
| 88 | ) |
| 89 | |
| 90 | |
| 91 | class TestHashtagFormCollapse(unittest.TestCase): |
| 92 | """Tests for _to_hashtag_form() — the multi-word retry workaround.""" |
| 93 | |
| 94 | def test_collapses_spaces(self): |
| 95 | self.assertEqual(instagram._to_hashtag_form("toronto real estate"), "torontorealestate") |
| 96 | |
| 97 | def test_lowercases(self): |
| 98 | self.assertEqual(instagram._to_hashtag_form("Toronto REAL Estate"), "torontorealestate") |
| 99 | |
| 100 | def test_idempotent_on_single_word(self): |
| 101 | self.assertEqual(instagram._to_hashtag_form("ozempic"), "ozempic") |
| 102 | |
| 103 | def test_handles_extra_whitespace(self): |
| 104 | self.assertEqual(instagram._to_hashtag_form(" toronto real estate "), "torontorealestate") |
| 105 | |
| 106 | |
| 107 | class TestSearchRetryOn500(unittest.TestCase): |
| 108 | """Tests for the multi-word -> hashtag retry on SC's flaky 500 path. |
| 109 | |
| 110 | SC's /v2/instagram/reels/search wraps Google Search and is documented |
| 111 | to be unreliable on multi-token queries. The retry collapses to a |
| 112 | hashtag form which hits the stable hashtag-page lookup path. |
| 113 | """ |
| 114 | |
| 115 | def test_multiword_500_triggers_retry_with_hashtag_form(self): |
| 116 | """Multi-word query 500 -> retry with collapsed hashtag form.""" |
| 117 | from lib import http as http_module |
| 118 | first_error = http_module.HTTPError("HTTP 500: Server Error", 500, "") |
| 119 | second_payload = { |
| 120 | "reels": [{"id": "retry-result", "taken_at": "2026-04-15T12:00:00Z"}] |
| 121 | } |
| 122 | with patch.object(http_module, "get") as mock_http_get: |
| 123 | mock_http_get.side_effect = [first_error, second_payload] |
| 124 | instagram.search_instagram( |
| 125 | "toronto real estate", "2026-04-01", "2026-05-04", |
| 126 | depth="default", token="fake-token", |
| 127 | ) |
| 128 | self.assertEqual(mock_http_get.call_count, 2) |
| 129 | # First call: original multi-word query |
| 130 | first_params = mock_http_get.call_args_list[0].kwargs["params"] |
| 131 | self.assertEqual(first_params["query"], "toronto real estate") |
| 132 | # Second call: collapsed hashtag form |
| 133 | second_params = mock_http_get.call_args_list[1].kwargs["params"] |
| 134 | self.assertEqual(second_params["query"], "torontorealestate") |
| 135 | |
| 136 | def test_singleword_500_does_not_retry(self): |
| 137 | """Single-word query 500 has no spaces to collapse - no retry.""" |
| 138 | from lib import http as http_module |
| 139 | only_error = http_module.HTTPError("HTTP 500: Server Error", 500, "") |
| 140 | with patch.object(http_module, "get") as mock_http_get: |
| 141 | mock_http_get.side_effect = only_error |
| 142 | result = instagram.search_instagram( |
| 143 | "ozempic", "2026-04-01", "2026-05-04", |
| 144 | depth="default", token="fake-token", |
| 145 | ) |
| 146 | self.assertEqual(mock_http_get.call_count, 1) |
| 147 | self.assertIn("error", result) |
| 148 | self.assertEqual(result["items"], []) |
| 149 | |
| 150 | def test_first_call_succeeds_no_retry(self): |
| 151 | """200 on first call -> retry path is never entered.""" |
| 152 | from lib import http as http_module |
| 153 | ok_payload = { |
| 154 | "reels": [{"id": "search-result", "taken_at": "2026-04-15T12:00:00Z"}] |
| 155 | } |
| 156 | with patch.object(http_module, "get") as mock_http_get: |
| 157 | mock_http_get.return_value = ok_payload |
| 158 | instagram.search_instagram( |
| 159 | "toronto real estate", "2026-04-01", "2026-05-04", |
| 160 | depth="default", token="fake-token", |
| 161 | ) |
| 162 | self.assertEqual(mock_http_get.call_count, 1) |
| 163 | |
| 164 | def test_no_token_short_circuits(self): |
| 165 | """No SCRAPECREATORS_API_KEY -> error returned without HTTP call.""" |
| 166 | from lib import http as http_module |
| 167 | with patch.object(http_module, "get") as mock_http_get: |
| 168 | result = instagram.search_instagram( |
| 169 | "toronto real estate", "2026-04-01", "2026-05-04", |
| 170 | depth="default", token=None, |
| 171 | ) |
| 172 | mock_http_get.assert_not_called() |
| 173 | self.assertIn("error", result) |
| 174 | self.assertIn("SCRAPECREATORS_API_KEY", result["error"]) |
| 175 | |
| 176 | |
| 177 | class TestGoogleSearchFallback(unittest.TestCase): |
| 178 | """The Google-indexed post lane recovers when reels search is empty.""" |
| 179 | |
| 180 | @staticmethod |
| 181 | def _no_reels_error(): |
| 182 | from lib import http as http_module |
| 183 | |
| 184 | return http_module.HTTPError( |
| 185 | "HTTP 404: Not Found", |
| 186 | 404, |
| 187 | json.dumps({ |
| 188 | "success": False, |
| 189 | "error": "not_found", |
| 190 | "errorStatus": 404, |
| 191 | "message": ( |
| 192 | "No reels found for that query. " |
| 193 | "You were not charged for this request." |
| 194 | ), |
| 195 | }), |
| 196 | ) |
| 197 | |
| 198 | def _post_payload(self): |
| 199 | return { |
| 200 | "data": { |
| 201 | "xdt_shortcode_media": { |
| 202 | "id": "post-1020", |
| 203 | "shortcode": "ABC1020", |
| 204 | "taken_at_timestamp": 1786900800, |
| 205 | "edge_media_to_caption": { |
| 206 | "edges": [{"node": {"text": "AI automation for small business"}}] |
| 207 | }, |
| 208 | "video_play_count": 900, |
| 209 | "edge_media_preview_like": {"count": 80}, |
| 210 | "edge_media_to_parent_comment": {"count": 12}, |
| 211 | "owner": {"username": "creator1020"}, |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | def test_404_search_falls_back_to_google_reel_urls_and_post_details(self): |
| 217 | from lib import http as http_module |
| 218 | |
| 219 | not_found = http_module.HTTPError( |
| 220 | 'HTTP 404: No scrapeable reels found for that query', 404, "" |
| 221 | ) |
| 222 | with patch.object( |
| 223 | http_module, |
| 224 | "get", |
| 225 | side_effect=[ |
| 226 | not_found, |
| 227 | { |
| 228 | "results": [ |
| 229 | {"url": "https://www.instagram.com/reel/ABC1020/"}, |
| 230 | {"url": "https://www.instagram.com/reel/ABC1020/"}, |
| 231 | ] |
| 232 | }, |
| 233 | self._post_payload(), |
| 234 | ], |
| 235 | ) as mock_http_get: |
| 236 | result = instagram.search_instagram( |
| 237 | "AI automation for small business", |
| 238 | "2026-08-01", |
| 239 | "2026-08-31", |
| 240 | depth="quick", |
| 241 | token="fake-token", |
| 242 | ) |
| 243 | |
| 244 | self.assertNotIn("error", result) |
| 245 | self.assertEqual(1, len(result["items"])) |
| 246 | item = result["items"][0] |
| 247 | self.assertEqual("post-1020", item["video_id"]) |
| 248 | self.assertEqual("creator1020", item["author_name"]) |
| 249 | self.assertEqual("AI automation for small business", item["text"]) |
| 250 | self.assertEqual("2026-08-16", item["date"]) |
| 251 | self.assertEqual( |
| 252 | {"views": 900, "likes": 80, "comments": 12}, item["engagement"] |
| 253 | ) |
| 254 | self.assertEqual(3, mock_http_get.call_count) |
| 255 | google_call = mock_http_get.call_args_list[1] |
| 256 | self.assertEqual( |
| 257 | "site:instagram.com/reel ai automation for small business " |
| 258 | "after:2026-08-01 before:2026-09-01", |
| 259 | google_call.kwargs["params"]["query"], |
| 260 | ) |
| 261 | self.assertNotIn("date_posted", google_call.kwargs["params"]) |
| 262 | self.assertEqual(1, google_call.kwargs["params"]["page"]) |
| 263 | post_call = mock_http_get.call_args_list[2] |
| 264 | self.assertEqual( |
| 265 | "https://www.instagram.com/reel/ABC1020/", |
| 266 | post_call.kwargs["params"]["url"], |
| 267 | ) |
| 268 | self.assertEqual(1, post_call.kwargs["retries"]) |
| 269 | |
| 270 | def test_404_is_preserved_when_google_fallback_has_no_results(self): |
| 271 | from lib import http as http_module |
| 272 | |
| 273 | not_found = http_module.HTTPError("HTTP 404: no reels", 404, "") |
| 274 | with patch.object( |
| 275 | http_module, "get", side_effect=[not_found, {"results": []}] |
| 276 | ): |
| 277 | result = instagram.search_instagram( |
| 278 | "AI automation", "2026-08-01", "2026-08-31", |
| 279 | depth="quick", token="fake-token", |
| 280 | ) |
| 281 | |
| 282 | self.assertEqual([], result["items"]) |
| 283 | self.assertIn("404", result["error"]) |
| 284 | |
| 285 | def test_documented_404_no_reels_is_clean_empty_after_google_fallback(self): |
| 286 | from lib import http as http_module |
| 287 | |
| 288 | with patch.object( |
| 289 | http_module, |
| 290 | "get", |
| 291 | side_effect=[self._no_reels_error(), {"results": []}], |
| 292 | ) as mock_http_get: |
| 293 | result = instagram.search_instagram( |
| 294 | "unknown niche topic", "2026-08-01", "2026-08-31", |
| 295 | depth="quick", token="fake-token", |
| 296 | ) |
| 297 | |
| 298 | self.assertEqual({"items": []}, result) |
| 299 | self.assertEqual(2, mock_http_get.call_count) |
| 300 | |
| 301 | @staticmethod |
| 302 | def _http_response(status, body): |
| 303 | response = MagicMock() |
| 304 | response.status = status |
| 305 | response.read.return_value = body |
| 306 | response.__enter__.return_value = response |
| 307 | response.__exit__.return_value = False |
| 308 | return response |
| 309 | |
| 310 | def _search_with_captured_failures(self, topic, reels_responses, google_response=None): |
| 311 | """Run a search over the real transport; reels_responses maps query -> (status, body).""" |
| 312 | from lib import http as http_module |
| 313 | |
| 314 | def urlopen(request, *args, **kwargs): |
| 315 | url = request.full_url |
| 316 | if "/reels/search" not in url: |
| 317 | if google_response is not None: |
| 318 | status, body = google_response |
| 319 | if status != 200: |
| 320 | raise urllib.error.HTTPError(url, status, "Error", {}, io.BytesIO(body)) |
| 321 | return self._http_response(status, body) |
| 322 | return self._http_response(200, b'{"results": []}') |
| 323 | query = parse_qs(urlsplit(url).query)["query"][0] |
| 324 | status, body = reels_responses[query] |
| 325 | if status == 200: |
| 326 | return self._http_response(200, body) |
| 327 | raise urllib.error.HTTPError(url, status, "Error", {}, io.BytesIO(body)) |
| 328 | |
| 329 | with patch("lib.http.urllib.request.urlopen", side_effect=urlopen), \ |
| 330 | patch("lib.http.time.sleep"): |
| 331 | with http_module.capture_failures() as failures: |
| 332 | result = instagram.search_instagram( |
| 333 | topic, "2026-08-01", "2026-08-31", |
| 334 | depth="quick", token="fake-token", |
| 335 | ) |
| 336 | return result, failures |
| 337 | |
| 338 | def test_documented_404_no_reels_is_not_captured_as_source_failure(self): |
| 339 | no_reels = self._no_reels_error().body.encode("utf-8") |
| 340 | result, failures = self._search_with_captured_failures( |
| 341 | "unknown niche topic", {"unknown niche topic": (404, no_reels)}, |
| 342 | ) |
| 343 | |
| 344 | self.assertEqual({"items": []}, result) |
| 345 | self.assertEqual([], failures) |
| 346 | |
| 347 | def test_google_discovery_404_is_clean_no_results(self): |
| 348 | """A fallback 404 after a documented primary 404 is a clean miss. |
| 349 | |
| 350 | Both searches found nothing, so the result is an empty list with no |
| 351 | error and nothing captured as a source failure (issue #1356). |
| 352 | """ |
| 353 | no_reels = self._no_reels_error().body.encode("utf-8") |
| 354 | result, failures = self._search_with_captured_failures( |
| 355 | "unknown niche topic", {"unknown niche topic": (404, no_reels)}, |
| 356 | google_response=(404, b'{}'), |
| 357 | ) |
| 358 | |
| 359 | self.assertEqual({"items": []}, result) |
| 360 | self.assertEqual([], failures) |
| 361 | |
| 362 | def test_google_discovery_failure_is_explicit_and_keeps_its_typed_outcome(self): |
| 363 | from lib import health, pipeline |
| 364 | |
| 365 | # A fallback 404 is a clean miss, not an explicit failure (see |
| 366 | # test_google_discovery_404_is_clean_no_results below), so only |
| 367 | # non-404 failures are asserted here. |
| 368 | no_reels = self._no_reels_error().body.encode("utf-8") |
| 369 | for status, state in [(401, health.AUTH_FAILED), (429, health.RATE_LIMITED)]: |
| 370 | with self.subTest(status=status): |
| 371 | result, failures = self._search_with_captured_failures( |
| 372 | "unknown niche topic", {"unknown niche topic": (404, no_reels)}, |
| 373 | google_response=(status, b'{}'), |
| 374 | ) |
| 375 | |
| 376 | self.assertEqual([], result["items"]) |
| 377 | self.assertIn("Google Instagram discovery fallback", result.get("error", "")) |
| 378 | self.assertIn(str(status), result["error"]) |
| 379 | self.assertEqual(1, len(failures)) |
| 380 | self.assertEqual(status, failures[0].status_code) |
| 381 | self.assertEqual("{}", failures[0].body) |
| 382 | self.assertEqual(state, failures[0].outcome_state) |
| 383 | self.assertIn("Google Instagram discovery fallback", str(failures[0])) |
| 384 | outcome = pipeline._resolve_stream_outcome( |
| 385 | "instagram", pipeline._result_outcome_artifact("instagram", result), failures, |
| 386 | ) |
| 387 | self.assertEqual(state, outcome["state"]) |
| 388 | self.assertIn("Google Instagram discovery fallback", outcome["detail"]) |
| 389 | |
| 390 | def test_google_discovery_network_failure_is_not_a_clean_empty(self): |
| 391 | from lib import http as http_module |
| 392 | |
| 393 | def urlopen(request, *args, **kwargs): |
| 394 | if "/reels/search" in request.full_url: |
| 395 | return self._http_response(200, b'{"reels": []}') |
| 396 | raise urllib.error.URLError("timed out") |
| 397 | |
| 398 | with patch("lib.http.urllib.request.urlopen", side_effect=urlopen), \ |
| 399 | patch("lib.http.time.sleep"), http_module.capture_failures() as failures: |
| 400 | result = instagram.search_instagram( |
| 401 | "unknown niche topic", "2026-08-01", "2026-08-31", |
| 402 | depth="quick", token="fake-token", |
| 403 | ) |
| 404 | |
| 405 | self.assertEqual([], result["items"]) |
| 406 | self.assertIn("Google Instagram discovery fallback", result.get("error", "")) |
| 407 | self.assertEqual(1, len(failures)) |
| 408 | self.assertIn("Google Instagram discovery fallback", str(failures[0])) |
| 409 | |
| 410 | def test_404_with_other_not_found_message_remains_error(self): |
| 411 | from lib import http as http_module |
| 412 | |
| 413 | outage = http_module.HTTPError( |
| 414 | "HTTP 404: Not Found", 404, |
| 415 | json.dumps({"error": "not_found", "message": "Instagram reels endpoint removed"}), |
| 416 | ) |
| 417 | with patch.object( |
| 418 | http_module, "get", side_effect=[outage, {"results": []}] |
| 419 | ): |
| 420 | result = instagram.search_instagram( |
| 421 | "unknown niche topic", "2026-08-01", "2026-08-31", |
| 422 | depth="quick", token="fake-token", |
| 423 | ) |
| 424 | |
| 425 | self.assertEqual([], result["items"]) |
| 426 | self.assertIn("404", result["error"]) |
| 427 | |
| 428 | def test_hashtag_retry_answer_clears_the_500_it_replaced(self): |
| 429 | no_reels = self._no_reels_error().body.encode("utf-8") |
| 430 | for retry_response in [(404, no_reels), (200, b'{"reels": []}')]: |
| 431 | with self.subTest(retry_status=retry_response[0]): |
| 432 | result, failures = self._search_with_captured_failures( |
| 433 | "niche topic", |
| 434 | {"niche topic": (500, b"{}"), "nichetopic": retry_response}, |
| 435 | ) |
| 436 | |
| 437 | self.assertEqual({"items": []}, result) |
| 438 | self.assertEqual([], failures) |
| 439 | |
| 440 | def test_500_stays_captured_when_hashtag_retry_also_fails(self): |
| 441 | result, failures = self._search_with_captured_failures( |
| 442 | "niche topic", |
| 443 | {"niche topic": (500, b"{}"), "nichetopic": (500, b"{}")}, |
| 444 | ) |
| 445 | |
| 446 | self.assertEqual([], result["items"]) |
| 447 | self.assertIn("500", result["error"]) |
| 448 | self.assertEqual([500, 500], [f.status_code for f in failures]) |
| 449 | |
| 450 | def test_404_is_preserved_when_google_search_fails(self): |
| 451 | from lib import http as http_module |
| 452 | |
| 453 | not_found = http_module.HTTPError("HTTP 404: no reels", 404, "") |
| 454 | google_error = http_module.HTTPError("HTTP 503: unavailable", 503, "") |
| 455 | with patch.object( |
| 456 | http_module, "get", side_effect=[not_found, google_error] |
| 457 | ): |
| 458 | result = instagram.search_instagram( |
| 459 | "AI automation", "2026-08-01", "2026-08-31", |
| 460 | depth="quick", token="fake-token", |
| 461 | ) |
| 462 | |
| 463 | self.assertEqual([], result["items"]) |
| 464 | self.assertIn("404", result["error"]) |
| 465 | |
| 466 | def test_google_fallback_rejects_non_instagram_and_non_reel_urls(self): |
| 467 | from lib import http as http_module |
| 468 | |
| 469 | not_found = http_module.HTTPError("HTTP 404: no reels", 404, "") |
| 470 | results = { |
| 471 | "results": [ |
| 472 | {"url": "https://example.com/reel/EXAMPLE/"}, |
| 473 | {"url": "http://instagram.com/reel/HTTP/"}, |
| 474 | {"url": "https://instagram.com.example.org/reel/LOOKALIKE/"}, |
| 475 | {"url": "https://instagram.com/p/POST/"}, |
| 476 | {"url": "https://instagram.com/not/reel/PREFIX/"}, |
| 477 | {"url": "https://[invalid/reel/MALFORMED/"}, |
| 478 | ] |
| 479 | } |
| 480 | with patch.object( |
| 481 | http_module, "get", side_effect=[not_found, results] |
| 482 | ) as mock_http_get: |
| 483 | result = instagram.search_instagram( |
| 484 | "AI automation", "2026-08-01", "2026-08-31", |
| 485 | depth="quick", token="fake-token", |
| 486 | ) |
| 487 | |
| 488 | self.assertEqual([], result["items"]) |
| 489 | self.assertIn("404", result["error"]) |
| 490 | self.assertEqual(2, mock_http_get.call_count) |
| 491 | |
| 492 | def test_google_fallback_drops_posts_outside_requested_date_range(self): |
| 493 | from lib import http as http_module |
| 494 | |
| 495 | with patch.object( |
| 496 | http_module, |
| 497 | "get", |
| 498 | side_effect=[ |
| 499 | {"reels": []}, |
| 500 | {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]}, |
| 501 | self._post_payload(), |
| 502 | ], |
| 503 | ): |
| 504 | result = instagram.search_instagram( |
| 505 | "AI automation", "2025-08-01", "2025-08-31", |
| 506 | depth="quick", token="fake-token", |
| 507 | ) |
| 508 | |
| 509 | self.assertEqual([], result["items"]) |
| 510 | self.assertNotIn("error", result) |
| 511 | |
| 512 | def test_empty_reels_search_uses_google_fallback(self): |
| 513 | from lib import http as http_module |
| 514 | |
| 515 | with patch.object( |
| 516 | http_module, |
| 517 | "get", |
| 518 | side_effect=[ |
| 519 | {"reels": []}, |
| 520 | {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]}, |
| 521 | self._post_payload(), |
| 522 | ], |
| 523 | ) as mock_http_get: |
| 524 | result = instagram.search_instagram( |
| 525 | "AI automation for small business", |
| 526 | "2026-08-01", |
| 527 | "2026-08-31", |
| 528 | depth="quick", |
| 529 | token="fake-token", |
| 530 | ) |
| 531 | |
| 532 | self.assertEqual(1, len(result["items"])) |
| 533 | self.assertEqual(3, mock_http_get.call_count) |
| 534 | |
| 535 | def test_later_discovery_failure_keeps_recovered_reels_usable(self): |
| 536 | from lib import http as http_module |
| 537 | |
| 538 | failure = http_module.HTTPError("HTTP 503: unavailable", 503, "") |
| 539 | with patch.object(http_module, "get", side_effect=[ |
| 540 | {"reels": []}, |
| 541 | {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]}, |
| 542 | failure, |
| 543 | self._post_payload(), |
| 544 | ]): |
| 545 | result = instagram.search_instagram( |
| 546 | "AI automation", "2026-08-01", "2026-08-31", |
| 547 | depth="default", token="fake-token", |
| 548 | ) |
| 549 | |
| 550 | self.assertEqual(1, len(result["items"])) |
| 551 | self.assertNotIn("error", result) |
| 552 | self.assertIn("Google Instagram discovery fallback failed on page 2", str(failure)) |
| 553 | self.assertEqual(503, failure.status_code) |
| 554 | |
| 555 | def test_default_depth_fallback_searches_the_second_page(self): |
| 556 | from lib import http as http_module |
| 557 | |
| 558 | with patch.object( |
| 559 | http_module, |
| 560 | "get", |
| 561 | side_effect=[ |
| 562 | {"reels": []}, |
| 563 | {"results": []}, |
| 564 | {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]}, |
| 565 | self._post_payload(), |
| 566 | ], |
| 567 | ) as mock_http_get: |
| 568 | result = instagram.search_instagram( |
| 569 | "AI automation", "2026-08-01", "2026-08-31", |
| 570 | depth="default", token="fake-token", |
| 571 | ) |
| 572 | |
| 573 | self.assertEqual(1, len(result["items"])) |
| 574 | google_calls = [ |
| 575 | call for call in mock_http_get.call_args_list |
| 576 | if call.args[0].endswith("/v1/google/search") |
| 577 | ] |
| 578 | self.assertEqual( |
| 579 | [1, 2], [call.kwargs["params"]["page"] for call in google_calls] |
| 580 | ) |
| 581 | |
| 582 | def test_expanded_queries_share_the_depth_fallback_budget(self): |
| 583 | from lib import http as http_module |
| 584 | |
| 585 | not_found = http_module.HTTPError("HTTP 404: no reels", 404, "") |
| 586 | with ( |
| 587 | patch.object( |
| 588 | instagram, |
| 589 | "expand_instagram_queries", |
| 590 | return_value=["first", "second"], |
| 591 | ), |
| 592 | patch.object(instagram, "fetch_captions", return_value={}), |
| 593 | patch.object( |
| 594 | http_module, |
| 595 | "get", |
| 596 | side_effect=[ |
| 597 | not_found, |
| 598 | {"results": []}, |
| 599 | not_found, |
| 600 | {"results": []}, |
| 601 | ], |
| 602 | ) as mock_http_get, |
| 603 | ): |
| 604 | result = instagram.search_and_enrich( |
| 605 | "AI automation", "2026-08-01", "2026-08-31", |
| 606 | depth="default", token="fake-token", |
| 607 | ) |
| 608 | |
| 609 | self.assertEqual([], result["items"]) |
| 610 | google_calls = [ |
| 611 | call for call in mock_http_get.call_args_list |
| 612 | if call.args[0].endswith("/v1/google/search") |
| 613 | ] |
| 614 | self.assertEqual(2, len(google_calls)) |
| 615 | self.assertEqual( |
| 616 | [1, 1], [call.kwargs["params"]["page"] for call in google_calls] |
| 617 | ) |
| 618 | |
| 619 | def test_expanded_queries_fetch_each_reel_shortcode_once(self): |
| 620 | from lib import http as http_module |
| 621 | |
| 622 | not_found = http_module.HTTPError("HTTP 404: no reels", 404, "") |
| 623 | with ( |
| 624 | patch.object( |
| 625 | instagram, |
| 626 | "expand_instagram_queries", |
| 627 | return_value=["first", "second"], |
| 628 | ), |
| 629 | patch.object(instagram, "fetch_captions", return_value={}), |
| 630 | patch.object( |
| 631 | http_module, |
| 632 | "get", |
| 633 | side_effect=[ |
| 634 | not_found, |
| 635 | {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]}, |
| 636 | self._post_payload(), |
| 637 | not_found, |
| 638 | {"results": [{"url": "https://instagram.com/reel/ABC1020"}]}, |
| 639 | ], |
| 640 | ) as mock_http_get, |
| 641 | ): |
| 642 | result = instagram.search_and_enrich( |
| 643 | "AI automation", "2026-08-01", "2026-08-31", |
| 644 | depth="default", token="fake-token", |
| 645 | ) |
| 646 | |
| 647 | detail_calls = [ |
| 648 | call for call in mock_http_get.call_args_list |
| 649 | if call.args[0].endswith("/v1/instagram/post") |
| 650 | ] |
| 651 | self.assertEqual(1, len(result["items"])) |
| 652 | self.assertEqual(1, len(detail_calls)) |
| 653 | |
| 654 | def test_expanded_queries_retry_a_failed_detail_within_the_budget(self): |
| 655 | from lib import http as http_module |
| 656 | |
| 657 | not_found = http_module.HTTPError("HTTP 404: no reels", 404, "") |
| 658 | temporary_error = http_module.HTTPError("HTTP 503: unavailable", 503, "") |
| 659 | with ( |
| 660 | patch.object( |
| 661 | instagram, |
| 662 | "expand_instagram_queries", |
| 663 | return_value=["first", "second"], |
| 664 | ), |
| 665 | patch.object(instagram, "fetch_captions", return_value={}), |
| 666 | patch.object( |
| 667 | http_module, |
| 668 | "get", |
| 669 | side_effect=[ |
| 670 | not_found, |
| 671 | {"results": [{"url": "https://www.instagram.com/reel/ABC1020/"}]}, |
| 672 | temporary_error, |
| 673 | not_found, |
| 674 | {"results": [{"url": "https://instagram.com/reel/ABC1020"}]}, |
| 675 | self._post_payload(), |
| 676 | ], |
| 677 | ) as mock_http_get, |
| 678 | ): |
| 679 | result = instagram.search_and_enrich( |
| 680 | "AI automation", "2026-08-01", "2026-08-31", |
| 681 | depth="default", token="fake-token", |
| 682 | ) |
| 683 | |
| 684 | detail_calls = [ |
| 685 | call for call in mock_http_get.call_args_list |
| 686 | if call.args[0].endswith("/v1/instagram/post") |
| 687 | ] |
| 688 | self.assertEqual(1, len(result["items"])) |
| 689 | self.assertEqual(2, len(detail_calls)) |
| 690 | |
| 691 | |
| 692 | class TestTranscriptTimeoutConfig(unittest.TestCase): |
| 693 | """Tests for LAST30DAYS_TRANSCRIPT_TIMEOUT configuration. |
| 694 | |
| 695 | SC's /v2/instagram/media/transcript endpoint regularly takes >15s, |
| 696 | so the timeout must be configurable. Default is DEFAULT_TRANSCRIPT_TIMEOUT |
| 697 | (30s); the env var or per-call kwarg overrides it. |
| 698 | """ |
| 699 | |
| 700 | def setUp(self): |
| 701 | # Snapshot any pre-existing env so we don't leak across tests |
| 702 | self._saved_env = os.environ.pop("LAST30DAYS_TRANSCRIPT_TIMEOUT", None) |
| 703 | |
| 704 | def tearDown(self): |
| 705 | os.environ.pop("LAST30DAYS_TRANSCRIPT_TIMEOUT", None) |
| 706 | if self._saved_env is not None: |
| 707 | os.environ["LAST30DAYS_TRANSCRIPT_TIMEOUT"] = self._saved_env |
| 708 | |
| 709 | def _ok_payload(self): |
| 710 | return {"transcripts": [{"text": "hello world"}]} |
| 711 | |
| 712 | def _video_item(self, vid="abc123"): |
| 713 | return { |
| 714 | "video_id": vid, |
| 715 | "url": f"https://www.instagram.com/reel/{vid}/", |
| 716 | "text": "", |
| 717 | } |
| 718 | |
| 719 | def test_default_timeout_is_30s_when_nothing_set(self): |
| 720 | """No env var, no kwarg -> request uses 30s, not the legacy 15s.""" |
| 721 | from lib import http as http_module |
| 722 | items = [self._video_item()] |
| 723 | with patch.object(http_module, "get") as mock_http_get: |
| 724 | mock_http_get.return_value = self._ok_payload() |
| 725 | instagram.fetch_captions(items, token="fake-token") |
| 726 | kwargs = mock_http_get.call_args.kwargs |
| 727 | self.assertEqual(kwargs["timeout"], 30.0) |
| 728 | |
| 729 | def test_env_var_override(self): |
| 730 | """LAST30DAYS_TRANSCRIPT_TIMEOUT='60' -> request uses 60s.""" |
| 731 | from lib import http as http_module |
| 732 | os.environ["LAST30DAYS_TRANSCRIPT_TIMEOUT"] = "60" |
| 733 | items = [self._video_item()] |
| 734 | with patch.object(http_module, "get") as mock_http_get: |
| 735 | mock_http_get.return_value = self._ok_payload() |
| 736 | instagram.fetch_captions(items, token="fake-token") |
| 737 | kwargs = mock_http_get.call_args.kwargs |
| 738 | self.assertEqual(kwargs["timeout"], 60.0) |
| 739 | |
| 740 | def test_explicit_timeout_kwarg_wins_over_env(self): |
| 741 | """Explicit timeout= kwarg trumps the env var.""" |
| 742 | from lib import http as http_module |
| 743 | os.environ["LAST30DAYS_TRANSCRIPT_TIMEOUT"] = "60" |
| 744 | items = [self._video_item()] |
| 745 | with patch.object(http_module, "get") as mock_http_get: |
| 746 | mock_http_get.return_value = self._ok_payload() |
| 747 | instagram.fetch_captions(items, token="fake-token", timeout=10) |
| 748 | kwargs = mock_http_get.call_args.kwargs |
| 749 | self.assertEqual(kwargs["timeout"], 10.0) |
| 750 | |
| 751 | def test_config_dict_fallback_when_env_unset(self): |
| 752 | """config={'LAST30DAYS_TRANSCRIPT_TIMEOUT': '45'} -> request uses 45s.""" |
| 753 | from lib import http as http_module |
| 754 | items = [self._video_item()] |
| 755 | with patch.object(http_module, "get") as mock_http_get: |
| 756 | mock_http_get.return_value = self._ok_payload() |
| 757 | instagram.fetch_captions( |
| 758 | items, |
| 759 | token="fake-token", |
| 760 | config={"LAST30DAYS_TRANSCRIPT_TIMEOUT": "45"}, |
| 761 | ) |
| 762 | kwargs = mock_http_get.call_args.kwargs |
| 763 | self.assertEqual(kwargs["timeout"], 45.0) |
| 764 | |
| 765 | def test_invalid_env_value_falls_back_to_default(self): |
| 766 | """Garbage env var doesn't crash; falls back to 30s.""" |
| 767 | from lib import http as http_module |
| 768 | os.environ["LAST30DAYS_TRANSCRIPT_TIMEOUT"] = "not-a-number" |
| 769 | items = [self._video_item()] |
| 770 | with patch.object(http_module, "get") as mock_http_get: |
| 771 | mock_http_get.return_value = self._ok_payload() |
| 772 | instagram.fetch_captions(items, token="fake-token") |
| 773 | kwargs = mock_http_get.call_args.kwargs |
| 774 | self.assertEqual(kwargs["timeout"], 30.0) |
| 775 | |
| 776 | class TestInstagramArabicTopicEncoding(unittest.TestCase): |
| 777 | """Regression for issue #817 across the Instagram search path.""" |
| 778 | |
| 779 | def _sent_url(self, mock_urlopen) -> str: |
| 780 | return mock_urlopen.call_args[0][0].full_url |
| 781 | |
| 782 | @patch("lib.http.urllib.request.urlopen") |
| 783 | def test_arabic_topic_returns_success_with_ascii_encoded_url(self, mock_urlopen): |
| 784 | resp = MagicMock() |
| 785 | resp.__enter__ = MagicMock(return_value=resp) |
| 786 | resp.__exit__ = MagicMock(return_value=False) |
| 787 | resp.read.return_value = ( |
| 788 | b'{"reels": [{"id": "arabic-result", ' |
| 789 | b'"taken_at": "2026-06-10T00:00:00Z"}]}' |
| 790 | ) |
| 791 | resp.status = 200 |
| 792 | mock_urlopen.return_value = resp |
| 793 | |
| 794 | topic = "اسعار التمريض المنزلي السعودية" |
| 795 | result = instagram.search_instagram( |
| 796 | topic, |
| 797 | "2026-06-01", |
| 798 | "2026-07-13", |
| 799 | depth="quick", |
| 800 | token="dummy-key", |
| 801 | ) |
| 802 | self.assertNotIn("error", result) |
| 803 | sent_url = self._sent_url(mock_urlopen) |
| 804 | sent_url.encode("ascii") |
| 805 | self.assertEqual(parse_qs(urlsplit(sent_url).query)["query"], [topic]) |
| 806 | |
| 807 | |
| 808 | if __name__ == "__main__": |
| 809 | unittest.main() |
| 810 |