| 1 | import io |
| 2 | import threading |
| 3 | import urllib.error |
| 4 | import unittest |
| 5 | import time |
| 6 | from urllib.parse import parse_qs, unquote, urlsplit |
| 7 | from unittest.mock import patch, MagicMock |
| 8 | |
| 9 | from lib import http |
| 10 | |
| 11 | http_lib = http |
| 12 | |
| 13 | |
| 14 | class TestCutOffBody(unittest.TestCase): |
| 15 | """A body cut off mid-read is a failed request, never a crash.""" |
| 16 | |
| 17 | @patch("lib.http.urllib.request.urlopen") |
| 18 | @patch("lib.http.time.sleep") |
| 19 | def test_incomplete_read_is_retried_then_raised_as_an_http_error(self, mock_sleep, mock_urlopen): |
| 20 | import http.client |
| 21 | |
| 22 | response = MagicMock() |
| 23 | response.__enter__.return_value = response |
| 24 | response.status = 200 |
| 25 | response.read.side_effect = http.client.IncompleteRead(b"partial") |
| 26 | mock_urlopen.return_value = response |
| 27 | |
| 28 | with self.assertRaises(http_lib.HTTPError) as ctx: |
| 29 | http_lib.request("GET", "https://www.example.com/", retries=2, raw=True) |
| 30 | self.assertIn("IncompleteRead", str(ctx.exception)) |
| 31 | self.assertEqual(mock_urlopen.call_count, 2) |
| 32 | # ``get_text`` answers the same failure with None. |
| 33 | self.assertIsNone(http_lib.get_text("https://www.example.com/", retries=1)) |
| 34 | |
| 35 | |
| 36 | class Test429RetryLimit(unittest.TestCase): |
| 37 | """429 retries must be capped at max_429_retries to avoid wasting latency.""" |
| 38 | |
| 39 | @patch("lib.http.urllib.request.urlopen") |
| 40 | @patch("lib.http.time.sleep") # Don't actually sleep in tests |
| 41 | def test_429_retries_limited_to_2_by_default(self, mock_sleep, mock_urlopen): |
| 42 | """With default max_429_retries=2, should attempt 2 times then raise.""" |
| 43 | error = urllib.error.HTTPError( |
| 44 | "http://example.com", 429, "Too Many Requests", {}, None |
| 45 | ) |
| 46 | mock_urlopen.side_effect = error |
| 47 | |
| 48 | with self.assertRaises(http.HTTPError) as ctx: |
| 49 | http.request("GET", "http://example.com", retries=5) |
| 50 | |
| 51 | self.assertEqual(ctx.exception.status_code, 429) |
| 52 | # Should be called exactly 2 times (initial + 1 retry), not 5 |
| 53 | self.assertEqual(mock_urlopen.call_count, 2) |
| 54 | |
| 55 | @patch("lib.http.urllib.request.urlopen") |
| 56 | @patch("lib.http.time.sleep") |
| 57 | def test_non_429_errors_still_use_full_retries(self, mock_sleep, mock_urlopen): |
| 58 | """500 errors should still retry up to the full retries count.""" |
| 59 | error = urllib.error.HTTPError( |
| 60 | "http://example.com", 500, "Internal Server Error", {}, None |
| 61 | ) |
| 62 | mock_urlopen.side_effect = error |
| 63 | |
| 64 | with self.assertRaises(http.HTTPError): |
| 65 | http.request("GET", "http://example.com", retries=3) |
| 66 | |
| 67 | self.assertEqual(mock_urlopen.call_count, 3) |
| 68 | |
| 69 | @patch("lib.http.urllib.request.urlopen") |
| 70 | @patch("lib.http.time.sleep") |
| 71 | @patch("lib.http.time.monotonic", return_value=0.5) |
| 72 | def test_shared_deadline_stops_retry_before_backoff_crosses_it( |
| 73 | self, |
| 74 | _mock_monotonic, |
| 75 | mock_sleep, |
| 76 | mock_urlopen, |
| 77 | ): |
| 78 | mock_urlopen.side_effect = urllib.error.HTTPError( |
| 79 | "http://example.com", 500, "Internal Server Error", {}, None |
| 80 | ) |
| 81 | |
| 82 | with self.assertRaises(http.HTTPError) as caught: |
| 83 | http.request( |
| 84 | "GET", |
| 85 | "http://example.com", |
| 86 | retries=3, |
| 87 | deadline_monotonic=1.0, |
| 88 | ) |
| 89 | |
| 90 | self.assertEqual(http.health.TIMEOUT, caught.exception.outcome_state) |
| 91 | self.assertEqual(1, mock_urlopen.call_count) |
| 92 | mock_sleep.assert_not_called() |
| 93 | |
| 94 | @patch("lib.http.urllib.request.urlopen") |
| 95 | @patch("lib.http.time.monotonic", side_effect=[0.0, 0.5, 1.5]) |
| 96 | def test_shared_deadline_rejects_response_that_finishes_late( |
| 97 | self, |
| 98 | _mock_monotonic, |
| 99 | mock_urlopen, |
| 100 | ): |
| 101 | mock_urlopen.return_value = _mock_response() |
| 102 | |
| 103 | with self.assertRaises(http.DeadlineExceeded): |
| 104 | http.request( |
| 105 | "GET", |
| 106 | "http://example.com", |
| 107 | retries=1, |
| 108 | deadline_monotonic=1.0, |
| 109 | ) |
| 110 | |
| 111 | @patch("lib.http.urllib.request.urlopen") |
| 112 | def test_shared_deadline_stops_waiting_during_slow_body_read( |
| 113 | self, |
| 114 | mock_urlopen, |
| 115 | ): |
| 116 | response = _mock_response() |
| 117 | |
| 118 | def slow_read(size=-1): |
| 119 | time.sleep(0.2) |
| 120 | return b'{"ok": true}' |
| 121 | |
| 122 | response.read.side_effect = slow_read |
| 123 | mock_urlopen.return_value = response |
| 124 | started = time.monotonic() |
| 125 | |
| 126 | with self.assertRaises(http.DeadlineExceeded): |
| 127 | http.request( |
| 128 | "GET", |
| 129 | "http://example.com", |
| 130 | retries=1, |
| 131 | deadline_monotonic=started + 0.02, |
| 132 | ) |
| 133 | |
| 134 | self.assertLess(time.monotonic() - started, 0.12) |
| 135 | |
| 136 | @patch("lib.http.urllib.request.urlopen") |
| 137 | def test_shared_deadline_stops_waiting_during_error_body_read(self, mock_urlopen): |
| 138 | release = threading.Event() |
| 139 | read_started = threading.Event() |
| 140 | |
| 141 | class SlowBody(io.BytesIO): |
| 142 | def read(self, *args, **kwargs): |
| 143 | read_started.set() |
| 144 | release.wait(1) |
| 145 | return super().read(*args, **kwargs) |
| 146 | |
| 147 | mock_urlopen.side_effect = urllib.error.HTTPError( |
| 148 | "https://example.com", 500, "Server error", {}, SlowBody(b"error") |
| 149 | ) |
| 150 | started = time.monotonic() |
| 151 | try: |
| 152 | with self.assertRaises(http.DeadlineExceeded): |
| 153 | http.request( |
| 154 | "GET", "https://example.com", retries=1, |
| 155 | deadline_monotonic=started + 0.05, |
| 156 | ) |
| 157 | self.assertTrue(read_started.is_set()) |
| 158 | self.assertLess(time.monotonic() - started, 0.5) |
| 159 | self.assertEqual(mock_urlopen.call_count, 1) |
| 160 | finally: |
| 161 | release.set() |
| 162 | |
| 163 | @patch("lib.http.urllib.request.urlopen") |
| 164 | def test_error_body_within_deadline_keeps_status_and_body(self, mock_urlopen): |
| 165 | mock_urlopen.side_effect = urllib.error.HTTPError( |
| 166 | "https://example.com", 401, "Unauthorized", {}, io.BytesIO(b"bad token") |
| 167 | ) |
| 168 | with self.assertRaises(http.HTTPError) as caught: |
| 169 | http.request( |
| 170 | "GET", "https://example.com", retries=1, |
| 171 | deadline_monotonic=time.monotonic() + 1, |
| 172 | ) |
| 173 | self.assertEqual(caught.exception.status_code, 401) |
| 174 | self.assertEqual(caught.exception.body, "bad token") |
| 175 | self.assertEqual(caught.exception.outcome_state, http.health.AUTH_FAILED) |
| 176 | |
| 177 | @patch("lib.http.urllib.request.urlopen") |
| 178 | def test_worker_socket_timeout_is_not_wall_deadline_expiration( |
| 179 | self, |
| 180 | mock_urlopen, |
| 181 | ): |
| 182 | mock_urlopen.side_effect = TimeoutError("early socket timeout") |
| 183 | |
| 184 | with self.assertRaises(http.HTTPError) as caught: |
| 185 | http.request( |
| 186 | "GET", |
| 187 | "http://example.com", |
| 188 | retries=1, |
| 189 | deadline_monotonic=time.monotonic() + 600, |
| 190 | ) |
| 191 | |
| 192 | self.assertNotIsInstance(caught.exception, http.DeadlineExceeded) |
| 193 | self.assertEqual(http.health.TIMEOUT, caught.exception.outcome_state) |
| 194 | |
| 195 | |
| 196 | def _mock_response(body: str = '{"ok": true}', status: int = 200): |
| 197 | resp = MagicMock() |
| 198 | resp.__enter__ = MagicMock(return_value=resp) |
| 199 | resp.__exit__ = MagicMock(return_value=False) |
| 200 | resp.read.return_value = body.encode("utf-8") |
| 201 | resp.status = status |
| 202 | return resp |
| 203 | |
| 204 | |
| 205 | class TestParamsEncoding(unittest.TestCase): |
| 206 | """request() should urlencode the params dict into the URL.""" |
| 207 | |
| 208 | def _sent_url(self, mock_urlopen) -> str: |
| 209 | request_arg = mock_urlopen.call_args[0][0] |
| 210 | return request_arg.full_url |
| 211 | |
| 212 | @patch("lib.http.urllib.request.urlopen") |
| 213 | def test_params_appended_to_url(self, mock_urlopen): |
| 214 | mock_urlopen.return_value = _mock_response() |
| 215 | http.get("https://api.example.com/search", params={"q": "test", "limit": 10}) |
| 216 | sent_url = self._sent_url(mock_urlopen) |
| 217 | self.assertIn("q=test", sent_url) |
| 218 | self.assertIn("limit=10", sent_url) |
| 219 | |
| 220 | @patch("lib.http.urllib.request.urlopen") |
| 221 | def test_params_appended_with_existing_query_string(self, mock_urlopen): |
| 222 | mock_urlopen.return_value = _mock_response() |
| 223 | http.get("https://api.example.com/search?api_key=secret", params={"q": "test"}) |
| 224 | sent_url = self._sent_url(mock_urlopen) |
| 225 | self.assertTrue(sent_url.startswith("https://api.example.com/search?api_key=secret&")) |
| 226 | self.assertIn("q=test", sent_url) |
| 227 | |
| 228 | @patch("lib.http.urllib.request.urlopen") |
| 229 | def test_none_values_dropped(self, mock_urlopen): |
| 230 | mock_urlopen.return_value = _mock_response() |
| 231 | http.get("https://api.example.com/search", params={"q": "test", "filter": None}) |
| 232 | sent_url = self._sent_url(mock_urlopen) |
| 233 | self.assertIn("q=test", sent_url) |
| 234 | self.assertNotIn("filter", sent_url) |
| 235 | |
| 236 | @patch("lib.http.urllib.request.urlopen") |
| 237 | def test_empty_params_leaves_url_unchanged(self, mock_urlopen): |
| 238 | mock_urlopen.return_value = _mock_response() |
| 239 | http.get("https://api.example.com/search", params={}) |
| 240 | sent_url = self._sent_url(mock_urlopen) |
| 241 | self.assertEqual(sent_url, "https://api.example.com/search") |
| 242 | |
| 243 | @patch("lib.http.urllib.request.urlopen") |
| 244 | def test_no_params_kwarg_leaves_url_unchanged(self, mock_urlopen): |
| 245 | mock_urlopen.return_value = _mock_response() |
| 246 | http.get("https://api.example.com/search") |
| 247 | sent_url = self._sent_url(mock_urlopen) |
| 248 | self.assertEqual(sent_url, "https://api.example.com/search") |
| 249 | |
| 250 | @patch("lib.http.urllib.request.urlopen") |
| 251 | def test_int_and_bool_params_stringified(self, mock_urlopen): |
| 252 | mock_urlopen.return_value = _mock_response() |
| 253 | http.get("https://api.example.com/search", params={"count": 25, "raw": True}) |
| 254 | sent_url = self._sent_url(mock_urlopen) |
| 255 | self.assertIn("count=25", sent_url) |
| 256 | self.assertIn("raw=True", sent_url) |
| 257 | |
| 258 | @patch("lib.http.urllib.request.urlopen") |
| 259 | def test_arabic_query_param_is_percent_encoded(self, mock_urlopen): |
| 260 | mock_urlopen.return_value = _mock_response() |
| 261 | arabic_topic = "اسعار التمريض المنزلي" |
| 262 | http.get("https://api.scrapecreators.com/v1/tiktok/search/keyword", |
| 263 | params={"query": arabic_topic}) |
| 264 | sent_url = self._sent_url(mock_urlopen) |
| 265 | sent_url.encode("ascii") |
| 266 | self.assertIn("%D8%A7", sent_url) |
| 267 | self.assertEqual(parse_qs(urlsplit(sent_url).query)["query"], [arabic_topic]) |
| 268 | |
| 269 | @patch("lib.http.urllib.request.urlopen") |
| 270 | def test_cjk_query_param_is_percent_encoded(self, mock_urlopen): |
| 271 | mock_urlopen.return_value = _mock_response() |
| 272 | http.get("https://api.example.com/search", params={"q": "人工智能"}) |
| 273 | sent_url = self._sent_url(mock_urlopen) |
| 274 | sent_url.encode("ascii") |
| 275 | self.assertEqual(parse_qs(urlsplit(sent_url).query)["q"], ["人工智能"]) |
| 276 | |
| 277 | @patch("lib.http.urllib.request.urlopen") |
| 278 | def test_non_ascii_in_base_url_path_is_percent_encoded(self, mock_urlopen): |
| 279 | mock_urlopen.return_value = _mock_response() |
| 280 | http.get("https://api.example.com/search/العربية") |
| 281 | sent_url = self._sent_url(mock_urlopen) |
| 282 | sent_url.encode("ascii") |
| 283 | self.assertEqual(unquote(urlsplit(sent_url).path), "/search/العربية") |
| 284 | |
| 285 | @patch("lib.http.urllib.request.urlopen") |
| 286 | def test_non_ascii_in_raw_url_query_string_is_percent_encoded(self, mock_urlopen): |
| 287 | mock_urlopen.return_value = _mock_response() |
| 288 | http.get("https://api.example.com/search?q=العربية") |
| 289 | sent_url = self._sent_url(mock_urlopen) |
| 290 | sent_url.encode("ascii") |
| 291 | self.assertEqual(parse_qs(urlsplit(sent_url).query)["q"], ["العربية"]) |
| 292 | |
| 293 | |
| 294 | class TestDNSResolutionRetry(unittest.TestCase): |
| 295 | """DNS resolution failures (gaierror) must retry with exponential backoff. |
| 296 | |
| 297 | Caller-passed `retries` values smaller than MIN_DNS_RETRIES are expanded |
| 298 | on the first gaierror so a transient resolution failure doesn't wipe a |
| 299 | request just because the caller passed retries=2. |
| 300 | """ |
| 301 | |
| 302 | @patch("lib.http.urllib.request.urlopen") |
| 303 | @patch("lib.http.time.sleep") |
| 304 | def test_gaierror_retries_up_to_min_dns_retries_even_when_caller_passes_fewer( |
| 305 | self, mock_sleep, mock_urlopen |
| 306 | ): |
| 307 | """Caller passed retries=2; gaierror should still get MIN_DNS_RETRIES attempts.""" |
| 308 | import socket |
| 309 | err = urllib.error.URLError(socket.gaierror(-2, "Name or service not known")) |
| 310 | mock_urlopen.side_effect = err |
| 311 | |
| 312 | with self.assertRaises(http.HTTPError): |
| 313 | http.request("GET", "http://nonexistent.example", retries=2) |
| 314 | |
| 315 | # Caller passed retries=2, but the budget expanded to MIN_DNS_RETRIES=3. |
| 316 | self.assertEqual(mock_urlopen.call_count, http.MIN_DNS_RETRIES) |
| 317 | |
| 318 | @patch("lib.http.urllib.request.urlopen") |
| 319 | @patch("lib.http.time.sleep") |
| 320 | def test_dns_failure_widens_single_attempt_budget(self, mock_sleep, mock_urlopen): |
| 321 | """DNS failures widen the budget to MIN_DNS_RETRIES, even from retries=1.""" |
| 322 | import socket |
| 323 | mock_urlopen.side_effect = urllib.error.URLError(socket.gaierror(-2, "DNS failure")) |
| 324 | |
| 325 | with self.assertRaises(http.HTTPError): |
| 326 | http.request("GET", "https://example.com", retries=1) |
| 327 | |
| 328 | self.assertEqual(mock_urlopen.call_count, http.MIN_DNS_RETRIES) |
| 329 | |
| 330 | @patch("lib.http.urllib.request.urlopen") |
| 331 | @patch("lib.http.time.sleep") |
| 332 | def test_gaierror_succeeds_after_transient_failure(self, mock_sleep, mock_urlopen): |
| 333 | """gaierror on attempt 1, then success — should NOT raise.""" |
| 334 | import socket |
| 335 | success_response = MagicMock() |
| 336 | success_response.read.return_value = b'{"ok": true}' |
| 337 | success_response.status = 200 |
| 338 | success_response.__enter__ = lambda self: self |
| 339 | success_response.__exit__ = lambda *args: None |
| 340 | |
| 341 | err = urllib.error.URLError(socket.gaierror(-2, "Name or service not known")) |
| 342 | mock_urlopen.side_effect = [err, success_response] |
| 343 | |
| 344 | result = http.request("GET", "http://flaky.example", retries=2) |
| 345 | |
| 346 | self.assertEqual(result, {"ok": True}) |
| 347 | self.assertEqual(mock_urlopen.call_count, 2) |
| 348 | |
| 349 | @patch("lib.http.urllib.request.urlopen") |
| 350 | @patch("lib.http.time.sleep") |
| 351 | def test_gaierror_uses_exponential_backoff(self, mock_sleep, mock_urlopen): |
| 352 | """Backoff delays for gaierror should be 1s, 2s, 4s — not the linear default.""" |
| 353 | import socket |
| 354 | err = urllib.error.URLError(socket.gaierror(-2, "Name or service not known")) |
| 355 | mock_urlopen.side_effect = err |
| 356 | |
| 357 | with self.assertRaises(http.HTTPError): |
| 358 | http.request("GET", "http://nonexistent.example", retries=4) |
| 359 | |
| 360 | sleep_delays = [call.args[0] for call in mock_sleep.call_args_list] |
| 361 | self.assertEqual(sleep_delays, [1, 2, 4]) |
| 362 | self.assertEqual(mock_urlopen.call_count, 4) |
| 363 | |
| 364 | @patch("lib.http.urllib.request.urlopen") |
| 365 | @patch("lib.http.time.sleep") |
| 366 | def test_non_dns_urlerror_uses_linear_backoff_not_dns_branch( |
| 367 | self, mock_sleep, mock_urlopen |
| 368 | ): |
| 369 | """A URLError that's NOT a gaierror must NOT expand the retry budget.""" |
| 370 | # ConnectionRefusedError-style URLError reason (not gaierror) |
| 371 | err = urllib.error.URLError(ConnectionRefusedError(111, "Connection refused")) |
| 372 | mock_urlopen.side_effect = err |
| 373 | |
| 374 | with self.assertRaises(http.HTTPError): |
| 375 | http.request("GET", "http://refused.example", retries=2) |
| 376 | |
| 377 | # Caller passed retries=2, and non-DNS URLError doesn't expand it. |
| 378 | self.assertEqual(mock_urlopen.call_count, 2) |
| 379 | |
| 380 | @patch("lib.http.urllib.request.urlopen") |
| 381 | @patch("lib.http.time.sleep") |
| 382 | def test_dns_widening_does_not_leak_into_subsequent_non_dns_urlerror( |
| 383 | self, mock_sleep, mock_urlopen |
| 384 | ): |
| 385 | """Mixed sequence: DNS-then-non-DNS must respect caller's original retries. |
| 386 | |
| 387 | Without the fix, the first gaierror widens effective_retries from 2 to |
| 388 | MIN_DNS_RETRIES=3, and a subsequent ConnectionRefused on attempt 1 |
| 389 | slips into a third overall attempt — exceeding what the caller asked |
| 390 | for. Each non-DNS error path must gate on the original `retries`. |
| 391 | """ |
| 392 | import socket |
| 393 | dns_err = urllib.error.URLError(socket.gaierror(-2, "Name or service not known")) |
| 394 | conn_err = urllib.error.URLError(ConnectionRefusedError(111, "Connection refused")) |
| 395 | mock_urlopen.side_effect = [dns_err, conn_err, conn_err] # 3rd would only fire if budget leaked |
| 396 | |
| 397 | with self.assertRaises(http.HTTPError): |
| 398 | http.request("GET", "http://flaky.example", retries=2) |
| 399 | |
| 400 | # Caller asked for at most 2 attempts. DNS widening must not give us a 3rd. |
| 401 | self.assertEqual(mock_urlopen.call_count, 2) |
| 402 | |
| 403 | @patch("lib.http.urllib.request.urlopen") |
| 404 | @patch("lib.http.time.sleep") |
| 405 | def test_dns_widening_does_not_leak_into_subsequent_oserror( |
| 406 | self, mock_sleep, mock_urlopen |
| 407 | ): |
| 408 | """Mixed sequence: DNS-then-OSError must respect caller's original retries.""" |
| 409 | import socket |
| 410 | dns_err = urllib.error.URLError(socket.gaierror(-2, "Name or service not known")) |
| 411 | mock_urlopen.side_effect = [dns_err, TimeoutError("timed out"), TimeoutError("timed out")] |
| 412 | |
| 413 | with self.assertRaises(http.HTTPError): |
| 414 | http.request("GET", "http://flaky.example", retries=2) |
| 415 | |
| 416 | self.assertEqual(mock_urlopen.call_count, 2) |
| 417 | |
| 418 | |
| 419 | class TestDebugLogRedaction(unittest.TestCase): |
| 420 | """Debug log lines must not echo credentials the request carried.""" |
| 421 | |
| 422 | SECRET = "sk-live-abcdef1234567890" |
| 423 | |
| 424 | def _logged(self, mock_log) -> str: |
| 425 | return "\n".join(call.args[0] for call in mock_log.call_args_list) |
| 426 | |
| 427 | @patch("lib.http.log") |
| 428 | @patch("lib.http.urllib.request.urlopen") |
| 429 | def test_error_body_echoing_bearer_token_is_redacted(self, mock_urlopen, mock_log): |
| 430 | mock_urlopen.side_effect = urllib.error.HTTPError( |
| 431 | "https://example.com", 401, "Unauthorized", {}, |
| 432 | io.BytesIO(f"invalid key Bearer {self.SECRET}".encode("utf-8")), |
| 433 | ) |
| 434 | |
| 435 | with self.assertRaises(http.HTTPError): |
| 436 | http.request( |
| 437 | "POST", "https://example.com", retries=1, |
| 438 | headers={"Authorization": f"Bearer {self.SECRET}"}, |
| 439 | json_data={"q": "x"}, |
| 440 | ) |
| 441 | |
| 442 | logged = self._logged(mock_log) |
| 443 | self.assertIn("Error body:", logged) |
| 444 | self.assertIn("<redacted>", logged) |
| 445 | self.assertNotIn(self.SECRET, logged) |
| 446 | |
| 447 | @patch("lib.http.log") |
| 448 | @patch("lib.http.urllib.request.urlopen") |
| 449 | @patch("lib.http.time.sleep") |
| 450 | def test_url_error_echoing_api_key_is_redacted(self, _mock_sleep, mock_urlopen, mock_log): |
| 451 | mock_urlopen.side_effect = urllib.error.URLError(f"proxy refused key {self.SECRET}") |
| 452 | |
| 453 | with self.assertRaises(http.HTTPError): |
| 454 | http.request( |
| 455 | "GET", "https://example.com", retries=1, |
| 456 | headers={"X-Api-Key": self.SECRET}, |
| 457 | ) |
| 458 | |
| 459 | logged = self._logged(mock_log) |
| 460 | self.assertIn("URL Error:", logged) |
| 461 | self.assertNotIn(self.SECRET, logged) |
| 462 |