| 1 | """Proxy mode (LAST30DAYS_API_MODE=proxy): the http.request seam. |
| 2 | |
| 3 | Every test is offline: transport is mocked at ``http._open_request``, the same |
| 4 | seam tests/test_usage_accounting.py uses. Keys and hosts are dummy values. |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import io |
| 10 | import json |
| 11 | import urllib.error |
| 12 | from decimal import Decimal |
| 13 | from email.message import Message |
| 14 | from unittest import mock |
| 15 | |
| 16 | import pytest |
| 17 | |
| 18 | from lib import backends, doctor, env, grounding, http, parallel_mcp, providers, proxy, render, tiktok |
| 19 | |
| 20 | TEST_KEY = "sk_live_DUMMY_PROXY_KEY_00000" |
| 21 | TEST_BASE = "https://api.example.test/api/v1" |
| 22 | SC_KEYWORD = "https://api.scrapecreators.com/v1/tiktok/search/keyword" |
| 23 | |
| 24 | |
| 25 | @pytest.fixture(autouse=True) |
| 26 | def _fresh_session(monkeypatch): |
| 27 | for name in ("LAST30DAYS_API_MODE", "LAST30DAYS_API_KEY", "LAST30DAYS_API_BASE"): |
| 28 | monkeypatch.delenv(name, raising=False) |
| 29 | monkeypatch.setattr(http.time, "sleep", lambda _s: None) |
| 30 | proxy.reset() |
| 31 | yield |
| 32 | proxy.reset() |
| 33 | |
| 34 | |
| 35 | @pytest.fixture |
| 36 | def proxy_env(monkeypatch): |
| 37 | monkeypatch.setenv("LAST30DAYS_API_MODE", "proxy") |
| 38 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 39 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 40 | |
| 41 | |
| 42 | def _headers(values: dict[str, str] | None = None) -> Message: |
| 43 | message = Message() |
| 44 | for name, value in (values or {}).items(): |
| 45 | message[name] = value |
| 46 | return message |
| 47 | |
| 48 | |
| 49 | class Response(io.BytesIO): |
| 50 | def __init__(self, payload, status=200, headers=None): |
| 51 | super().__init__(json.dumps(payload).encode()) |
| 52 | self.status = status |
| 53 | self.headers = _headers(headers) |
| 54 | |
| 55 | |
| 56 | def _http_error(url, status, payload, headers=None): |
| 57 | body = json.dumps(payload).encode() if payload is not None else b"" |
| 58 | return urllib.error.HTTPError(url, status, "error", _headers(headers), io.BytesIO(body)) |
| 59 | |
| 60 | |
| 61 | class Transport: |
| 62 | """Records each request and answers from a queue (or one fixed answer).""" |
| 63 | |
| 64 | def __init__(self, *answers): |
| 65 | self.answers = list(answers) |
| 66 | self.requests = [] |
| 67 | |
| 68 | def __call__(self, req, timeout, **_kwargs): |
| 69 | self.requests.append(req) |
| 70 | answer = self.answers.pop(0) if len(self.answers) > 1 else self.answers[0] |
| 71 | if callable(answer): |
| 72 | answer = answer(req) |
| 73 | if isinstance(answer, BaseException): |
| 74 | raise answer |
| 75 | return answer |
| 76 | |
| 77 | |
| 78 | def _config(**keys): |
| 79 | config = dict(keys) |
| 80 | proxy.fill_config(config) |
| 81 | return config |
| 82 | |
| 83 | |
| 84 | # --------------------------------------------------------------------------- |
| 85 | # Config: which lanes the proxy serves |
| 86 | # --------------------------------------------------------------------------- |
| 87 | |
| 88 | |
| 89 | def test_fill_config_marks_only_absent_proxy_lanes(proxy_env): |
| 90 | config = _config(SCRAPECREATORS_API_KEY="user-sc-key") |
| 91 | assert config["SCRAPECREATORS_API_KEY"] == "user-sc-key" |
| 92 | for var in ("XAI_API_KEY", "SERPER_API_KEY", "PARALLEL_API_KEY"): |
| 93 | assert proxy.is_sentinel(config[var]) |
| 94 | assert proxy.via_api_key(config) == ["XAI_API_KEY", "SERPER_API_KEY", "PARALLEL_API_KEY"] |
| 95 | # Lanes outside the proxy are never filled. |
| 96 | assert "OPENAI_API_KEY" not in config and "BRAVE_API_KEY" not in config |
| 97 | |
| 98 | |
| 99 | @pytest.mark.parametrize( |
| 100 | "env_values", |
| 101 | [ |
| 102 | {}, |
| 103 | {"LAST30DAYS_API_KEY": TEST_KEY, "LAST30DAYS_API_BASE": TEST_BASE}, |
| 104 | {"LAST30DAYS_API_MODE": "proxy", "LAST30DAYS_API_BASE": TEST_BASE}, |
| 105 | {"LAST30DAYS_API_MODE": "proxy", "LAST30DAYS_API_KEY": TEST_KEY, |
| 106 | "LAST30DAYS_API_BASE": "http://remote.example.test/api/v1"}, |
| 107 | {"LAST30DAYS_API_MODE": "hosted", "LAST30DAYS_API_KEY": TEST_KEY, |
| 108 | "LAST30DAYS_API_BASE": TEST_BASE}, |
| 109 | ], |
| 110 | ) |
| 111 | def test_no_lane_is_filled_unless_proxy_mode_is_fully_configured(monkeypatch, env_values): |
| 112 | for name, value in env_values.items(): |
| 113 | monkeypatch.setenv(name, value) |
| 114 | assert _config() == {} |
| 115 | |
| 116 | |
| 117 | def test_get_config_fills_lanes_in_proxy_mode_and_leaves_hosted_mode_alone(monkeypatch): |
| 118 | with mock.patch.object(env, "_load_keychain", return_value={}), \ |
| 119 | mock.patch.object(env, "_load_pass", return_value={}): |
| 120 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 121 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 122 | hosted = env.get_config() |
| 123 | assert not any(proxy.is_sentinel(value) for value in hosted.values()) |
| 124 | assert env.hosted_backend_configured() is True |
| 125 | |
| 126 | monkeypatch.setenv("LAST30DAYS_API_MODE", "proxy") |
| 127 | proxied = env.get_config() |
| 128 | assert proxied["SCRAPECREATORS_API_KEY"] == proxy.SENTINEL |
| 129 | assert env.hosted_backend_configured() is False |
| 130 | assert env.is_tiktok_available(proxied) |
| 131 | |
| 132 | |
| 133 | # --------------------------------------------------------------------------- |
| 134 | # Routing |
| 135 | # --------------------------------------------------------------------------- |
| 136 | |
| 137 | |
| 138 | def test_own_scrapecreators_key_goes_direct_in_proxy_mode(proxy_env, monkeypatch): |
| 139 | """AE2: a key the user set wins; the proxy never sees the call.""" |
| 140 | transport = Transport(Response({"search_item_list": []})) |
| 141 | monkeypatch.setattr(http, "_open_request", transport) |
| 142 | config = _config(SCRAPECREATORS_API_KEY="user-sc-key") |
| 143 | |
| 144 | tiktok.search_tiktok("ai agents", "2026-10-19", "2026-11-18", depth="quick", token=config["SCRAPECREATORS_API_KEY"]) |
| 145 | |
| 146 | req = transport.requests[0] |
| 147 | assert req.full_url.startswith(SC_KEYWORD + "?") |
| 148 | assert req.get_header("X-api-key") == "user-sc-key" |
| 149 | assert req.get_header("Authorization") is None |
| 150 | assert req.get_header("Idempotency-key") is None |
| 151 | assert proxy.footer_line() is None |
| 152 | |
| 153 | |
| 154 | def test_sentinel_scrapecreators_call_goes_through_proxy(proxy_env, monkeypatch): |
| 155 | transport = Transport(Response({"search_item_list": []}, headers={"x-l30d-charge-credits": "1.750000"})) |
| 156 | monkeypatch.setattr(http, "_open_request", transport) |
| 157 | config = _config() |
| 158 | |
| 159 | tiktok.search_tiktok("ai agents", "2026-10-19", "2026-11-18", depth="quick", token=config["SCRAPECREATORS_API_KEY"]) |
| 160 | |
| 161 | req = transport.requests[0] |
| 162 | assert req.full_url.startswith(f"{TEST_BASE}/proxy/scrapecreators/v1/tiktok/search/keyword?") |
| 163 | assert "query=ai" in req.full_url |
| 164 | assert req.get_header("Authorization") == f"Bearer {TEST_KEY}" |
| 165 | assert req.get_header("X-api-key") is None |
| 166 | assert proxy.SENTINEL not in json.dumps(req.header_items()) |
| 167 | assert req.get_header("Idempotency-key") |
| 168 | session = req.get_header("X-l30d-session") |
| 169 | assert session and len(session) <= 128 |
| 170 | assert proxy.session_summary() == (1, Decimal("1.75")) |
| 171 | |
| 172 | |
| 173 | def test_free_source_is_never_rewritten(proxy_env, monkeypatch): |
| 174 | transport = Transport(Response({"hits": []})) |
| 175 | monkeypatch.setattr(http, "_open_request", transport) |
| 176 | _config() |
| 177 | |
| 178 | http.get("https://hn.algolia.com/api/v1/search_by_date", params={"query": "ai"}) |
| 179 | |
| 180 | req = transport.requests[0] |
| 181 | assert req.full_url.startswith("https://hn.algolia.com/api/v1/search_by_date?") |
| 182 | assert req.get_header("Authorization") is None |
| 183 | assert req.get_header("X-l30d-session") is None |
| 184 | assert proxy.footer_line() is None |
| 185 | |
| 186 | |
| 187 | def test_proxied_xai_call_carries_its_timeout_as_deadline(proxy_env, monkeypatch): |
| 188 | transport = Transport(Response({"output": []}, headers={"x-l30d-charge-credits": "0.5"})) |
| 189 | monkeypatch.setattr(http, "_open_request", transport) |
| 190 | client = providers.XAIClient(_config()["XAI_API_KEY"]) |
| 191 | |
| 192 | client.generate_text("grok-4-1-fast-non-reasoning", "plan this") |
| 193 | |
| 194 | req = transport.requests[0] |
| 195 | assert req.full_url == f"{TEST_BASE}/proxy/xai/v1/responses" |
| 196 | assert req.get_method() == "POST" |
| 197 | assert req.get_header("X-l30d-deadline") == "90" |
| 198 | assert req.get_header("Authorization") == f"Bearer {TEST_KEY}" |
| 199 | assert json.loads(req.data)["input"] == [{"role": "user", "content": "plan this"}] |
| 200 | |
| 201 | |
| 202 | def test_retry_reuses_idempotency_key_and_calls_get_new_ones(proxy_env, monkeypatch): |
| 203 | transport = Transport( |
| 204 | _http_error(SC_KEYWORD, 503, {"message": "upstream busy"}), |
| 205 | Response({"ok": True}, headers={"x-l30d-charge-credits": "1"}), |
| 206 | ) |
| 207 | monkeypatch.setattr(http, "_open_request", transport) |
| 208 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 209 | |
| 210 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "a"}, retries=2) |
| 211 | first, retried = transport.requests |
| 212 | assert first.get_header("Idempotency-key") == retried.get_header("Idempotency-key") |
| 213 | |
| 214 | transport.answers = [Response({"ok": True}, headers={"x-l30d-charge-credits": "1"})] |
| 215 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "b"}) |
| 216 | assert transport.requests[2].get_header("Idempotency-key") != first.get_header("Idempotency-key") |
| 217 | # One session for the whole run. |
| 218 | assert len({req.get_header("X-l30d-session") for req in transport.requests}) == 1 |
| 219 | |
| 220 | |
| 221 | def test_already_settled_is_not_retried_and_its_charge_counts(proxy_env, monkeypatch): |
| 222 | transport = Transport(_http_error( |
| 223 | SC_KEYWORD, 409, {"error": "already charged", "code": "already_settled"}, |
| 224 | headers={"x-l30d-charge-credits": "2.000000"}, |
| 225 | )) |
| 226 | monkeypatch.setattr(http, "_open_request", transport) |
| 227 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 228 | |
| 229 | with pytest.raises(http.HTTPError) as exc: |
| 230 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "a"}, retries=3) |
| 231 | |
| 232 | assert exc.value.status_code == 409 |
| 233 | assert len(transport.requests) == 1 |
| 234 | assert proxy.session_summary() == (1, Decimal("2")) |
| 235 | |
| 236 | |
| 237 | def test_first_402_disables_paid_lanes_for_the_run(proxy_env, monkeypatch, capsys): |
| 238 | """AE3: one 402 insufficient_credits, a single hint, then no more proxy calls.""" |
| 239 | transport = Transport(_http_error( |
| 240 | SC_KEYWORD, 402, {"error": "Not enough credits", "code": "insufficient_credits"}, |
| 241 | )) |
| 242 | monkeypatch.setattr(http, "_open_request", transport) |
| 243 | config = _config() |
| 244 | |
| 245 | with pytest.raises(http.HTTPError): |
| 246 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(config["SCRAPECREATORS_API_KEY"]), params={"query": "a"}) |
| 247 | with pytest.raises(http.HTTPError) as later: |
| 248 | providers.XAIClient(config["XAI_API_KEY"]).generate_text("grok-4-1-fast-non-reasoning", "x") |
| 249 | |
| 250 | assert len(transport.requests) == 1 |
| 251 | assert later.value.status_code == 402 |
| 252 | assert proxy.exhausted() |
| 253 | err = capsys.readouterr().err |
| 254 | assert err.count("out of credits") == 1 |
| 255 | assert "https://api.example.test/dashboard/billing" in err |
| 256 | assert TEST_KEY not in err |
| 257 | |
| 258 | # Free sources keep working after the paid lanes stop. |
| 259 | transport.answers = [Response({"hits": []})] |
| 260 | assert http.get("https://hn.algolia.com/api/v1/search", params={"query": "ai"}) == {"hits": []} |
| 261 | |
| 262 | |
| 263 | def test_spend_ceiling_stops_paid_lanes_without_waiting_out_retry_after(proxy_env, monkeypatch): |
| 264 | slept = [] |
| 265 | monkeypatch.setattr(http.time, "sleep", slept.append) |
| 266 | transport = Transport(_http_error( |
| 267 | SC_KEYWORD, 429, {"error": "ceiling", "code": "spend_ceiling"}, headers={"Retry-After": "3600"}, |
| 268 | )) |
| 269 | monkeypatch.setattr(http, "_open_request", transport) |
| 270 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 271 | |
| 272 | with pytest.raises(http.HTTPError): |
| 273 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "a"}) |
| 274 | |
| 275 | assert len(transport.requests) == 1 |
| 276 | assert slept == [] |
| 277 | assert proxy.exhausted() |
| 278 | |
| 279 | |
| 280 | def test_upstream_provider_402_without_code_does_not_exhaust_the_key(proxy_env, monkeypatch): |
| 281 | transport = Transport(_http_error( |
| 282 | SC_KEYWORD, 402, {"message": "provider out of credits"}, |
| 283 | headers={"x-l30d-charge-credits": "0.000000"}, |
| 284 | )) |
| 285 | monkeypatch.setattr(http, "_open_request", transport) |
| 286 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 287 | |
| 288 | with pytest.raises(http.HTTPError): |
| 289 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "a"}) |
| 290 | |
| 291 | assert not proxy.exhausted() |
| 292 | assert proxy.session_summary() == (0, Decimal(0)) |
| 293 | |
| 294 | |
| 295 | def test_unlisted_endpoint_never_leaves_the_machine(proxy_env, monkeypatch): |
| 296 | transport = Transport(Response({})) |
| 297 | monkeypatch.setattr(http, "_open_request", transport) |
| 298 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 299 | |
| 300 | with pytest.raises(http.HTTPError) as exc: |
| 301 | http.get("https://api.scrapecreators.com/v1/twitter/profile", headers=http.scrapecreators_headers(token)) |
| 302 | with pytest.raises(http.HTTPError): |
| 303 | http.post("https://xai.example.test/v1/responses", {"model": "m"}, headers={"Authorization": f"Bearer {proxy.SENTINEL}"}) |
| 304 | |
| 305 | assert exc.value.status_code == 404 |
| 306 | assert transport.requests == [] |
| 307 | |
| 308 | |
| 309 | def test_parallel_mcp_and_transcription_never_receive_the_sentinel(proxy_env, monkeypatch): |
| 310 | config = _config() |
| 311 | seen = [] |
| 312 | monkeypatch.setattr(parallel_mcp, "search", lambda query, date_range, key: seen.append(key) or ([], {})) |
| 313 | |
| 314 | grounding.web_search("ai", ("2026-10-19", "2026-11-18"), config, backend="parallel-mcp") |
| 315 | |
| 316 | assert seen == [None] |
| 317 | assert env.transcription_providers(config) == [] |
| 318 | |
| 319 | |
| 320 | def test_user_keys_win_lane_selection_over_proxied_ones(proxy_env): |
| 321 | config = _config(PARALLEL_API_KEY="user-parallel", OPENROUTER_API_KEY="user-openrouter") |
| 322 | assert grounding.configured_backend(config) == "parallel" |
| 323 | runtime, client = providers.resolve_runtime(config, "default") |
| 324 | assert runtime.reasoning_provider == "openrouter" |
| 325 | |
| 326 | proxied_only = _config() |
| 327 | assert grounding.configured_backend(proxied_only) == "serper" |
| 328 | runtime, client = providers.resolve_runtime(proxied_only, "default") |
| 329 | assert runtime.reasoning_provider == "xai" |
| 330 | |
| 331 | |
| 332 | def test_proxied_xai_ranks_after_the_users_own_x_backends(proxy_env, monkeypatch): |
| 333 | config = _config(XQUIK_API_KEY="user-xquik") |
| 334 | monkeypatch.setattr(env, "is_xquik_available", lambda cfg: True) |
| 335 | chain = env.x_backend_chain(config, local_only=True) |
| 336 | assert chain[-1] == "xai" |
| 337 | assert chain.index("xquik") < chain.index("xai") |
| 338 | |
| 339 | |
| 340 | # --------------------------------------------------------------------------- |
| 341 | # Footer, fixtures, and mode boundaries |
| 342 | # --------------------------------------------------------------------------- |
| 343 | |
| 344 | |
| 345 | def test_footer_total_equals_sum_of_charge_headers(proxy_env, monkeypatch): |
| 346 | charges = ["0.125000", "1.000000", "0.000000", "2.333333"] |
| 347 | transport = Transport(*[Response({"ok": True}, headers={"x-l30d-charge-credits": c}) for c in charges]) |
| 348 | monkeypatch.setattr(http, "_open_request", transport) |
| 349 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 350 | |
| 351 | for query in "abcd": |
| 352 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": query}) |
| 353 | |
| 354 | total = sum(Decimal(c) for c in charges) |
| 355 | assert proxy.session_summary() == (4, total) |
| 356 | line = proxy.footer_line() |
| 357 | assert line == "💳 API key: 3.458333 credits across 4 paid calls" |
| 358 | |
| 359 | report = mock.Mock() |
| 360 | with mock.patch.object(render, "_build_source_footer_lines", return_value=["🔴 Reddit: 1 thread"]), \ |
| 361 | mock.patch.object(render, "_top_voices_footer_line", return_value=None), \ |
| 362 | mock.patch.object(render, "_assess_data_freshness", return_value=None): |
| 363 | footer = render._render_emoji_footer(report, "/tmp/raw.md") |
| 364 | assert f"├─ {line}" in footer |
| 365 | |
| 366 | |
| 367 | def test_footer_has_no_proxy_line_outside_proxy_mode(): |
| 368 | report = mock.Mock() |
| 369 | with mock.patch.object(render, "_build_source_footer_lines", return_value=["🔴 Reddit: 1 thread"]), \ |
| 370 | mock.patch.object(render, "_top_voices_footer_line", return_value=None), \ |
| 371 | mock.patch.object(render, "_assess_data_freshness", return_value=None): |
| 372 | footer = render._render_emoji_footer(report, None) |
| 373 | assert footer == ["---", "✅ All agents reported back!", "└─ 🔴 Reddit: 1 thread", "---"] |
| 374 | |
| 375 | |
| 376 | def test_recorded_fixtures_never_contain_the_bearer_key(proxy_env, monkeypatch, tmp_path): |
| 377 | transport = Transport(Response({"echo": f"Bearer {TEST_KEY}"}, headers={"x-l30d-charge-credits": "1"})) |
| 378 | monkeypatch.setattr(http, "_open_request", transport) |
| 379 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 380 | |
| 381 | with http.recording_requests(tmp_path / "fixture"): |
| 382 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "a"}) |
| 383 | |
| 384 | fixture_text = (tmp_path / "fixture" / "http.json").read_text(encoding="utf-8") |
| 385 | assert TEST_KEY not in fixture_text |
| 386 | assert "/proxy/scrapecreators/v1/tiktok/search/keyword" in fixture_text |
| 387 | |
| 388 | |
| 389 | def test_hosted_mode_without_api_mode_routes_nothing(monkeypatch): |
| 390 | """Without LAST30DAYS_API_MODE, a user key call is untouched by the seam.""" |
| 391 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 392 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 393 | transport = Transport(Response({"ok": True})) |
| 394 | monkeypatch.setattr(http, "_open_request", transport) |
| 395 | |
| 396 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers("user-sc-key"), params={"query": "a"}) |
| 397 | |
| 398 | req = transport.requests[0] |
| 399 | assert req.full_url == f"{SC_KEYWORD}?query=a" |
| 400 | assert sorted(name.lower() for name, _ in req.header_items()) == ["content-type", "user-agent", "x-api-key"] |
| 401 | assert proxy.footer_line() is None |
| 402 | |
| 403 | |
| 404 | def test_sentinel_without_proxy_mode_is_refused_locally(monkeypatch): |
| 405 | transport = Transport(Response({})) |
| 406 | monkeypatch.setattr(http, "_open_request", transport) |
| 407 | with pytest.raises(http.HTTPError): |
| 408 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(proxy.SENTINEL)) |
| 409 | assert transport.requests == [] |
| 410 | |
| 411 | |
| 412 | def test_doctor_reports_proxied_lanes_via_api_key(proxy_env): |
| 413 | config = _config(SCRAPECREATORS_API_KEY="") |
| 414 | record = doctor._sc_gated_record(config, "TikTok") |
| 415 | assert record["detail"] == "ScrapeCreators via API key (TikTok)" |
| 416 | setup = doctor._setup_block(config) |
| 417 | assert setup["keys_present"]["SCRAPECREATORS_API_KEY"] is False |
| 418 | assert setup["via_api_key"] == ["SCRAPECREATORS_API_KEY", "XAI_API_KEY", "SERPER_API_KEY", "PARALLEL_API_KEY"] |
| 419 | assert doctor._x_auth_path(config)["note"].startswith("xAI via API key") |
| 420 | |
| 421 | |
| 422 | def test_doctor_setup_block_lists_no_proxied_lane_outside_proxy_mode(): |
| 423 | config = {"SCRAPECREATORS_API_KEY": "user-sc-key"} |
| 424 | setup = doctor._setup_block(config) |
| 425 | assert setup["via_api_key"] == [] |
| 426 | assert setup["keys_present"]["SCRAPECREATORS_API_KEY"] is True |
| 427 | |
| 428 | |
| 429 | def test_run_end_prints_the_session_total_on_stderr(proxy_env, monkeypatch, capsys): |
| 430 | import last30days as cli |
| 431 | |
| 432 | cli._report_proxy_session() |
| 433 | assert capsys.readouterr().err == "" |
| 434 | |
| 435 | transport = Transport(Response({"ok": True}, headers={"x-l30d-charge-credits": "1.5"})) |
| 436 | monkeypatch.setattr(http, "_open_request", transport) |
| 437 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(_config()["SCRAPECREATORS_API_KEY"]), params={"query": "a"}) |
| 438 | cli._report_proxy_session() |
| 439 | |
| 440 | err = capsys.readouterr().err |
| 441 | assert err == f"[last30days] API key session {proxy.session_id()}: 1.5 credits across 1 paid call\n" |
| 442 | assert TEST_KEY not in err |
| 443 | |
| 444 | |
| 445 | # --------------------------------------------------------------------------- |
| 446 | # Review regressions |
| 447 | # --------------------------------------------------------------------------- |
| 448 | |
| 449 | |
| 450 | class _BrokenBody(Response): |
| 451 | """A charged response whose body read fails after the headers arrived.""" |
| 452 | |
| 453 | def read(self, *args): |
| 454 | raise ConnectionResetError("connection reset mid-body") |
| 455 | |
| 456 | |
| 457 | def test_charge_counts_once_when_a_body_read_fails_and_the_retry_is_already_settled(proxy_env, monkeypatch): |
| 458 | transport = Transport( |
| 459 | _BrokenBody({"ok": True}, headers={"x-l30d-charge-credits": "2.000000"}), |
| 460 | _http_error( |
| 461 | SC_KEYWORD, 409, {"error": "already charged", "code": "already_settled"}, |
| 462 | headers={"x-l30d-charge-credits": "2.000000"}, |
| 463 | ), |
| 464 | ) |
| 465 | monkeypatch.setattr(http, "_open_request", transport) |
| 466 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 467 | |
| 468 | with pytest.raises(http.HTTPError) as exc: |
| 469 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "a"}, retries=3) |
| 470 | |
| 471 | assert exc.value.status_code == 409 |
| 472 | first, retried = transport.requests |
| 473 | assert first.get_header("Idempotency-key") == retried.get_header("Idempotency-key") |
| 474 | assert proxy.session_summary() == (1, Decimal("2")) |
| 475 | |
| 476 | |
| 477 | def test_pending_retry_stops_once_another_call_exhausts_the_key(proxy_env, monkeypatch): |
| 478 | transport = Transport(_http_error(SC_KEYWORD, 503, {"message": "upstream busy"})) |
| 479 | monkeypatch.setattr(http, "_open_request", transport) |
| 480 | |
| 481 | def another_call_hits_402(_delay): |
| 482 | proxy.observe_error( |
| 483 | "xai", 402, json.dumps({"error": "Not enough credits", "code": "insufficient_credits"}), None, |
| 484 | ) |
| 485 | |
| 486 | monkeypatch.setattr(http.time, "sleep", another_call_hits_402) |
| 487 | token = _config()["SCRAPECREATORS_API_KEY"] |
| 488 | |
| 489 | with pytest.raises(http.HTTPError) as exc: |
| 490 | http.get(SC_KEYWORD, headers=http.scrapecreators_headers(token), params={"query": "a"}, retries=3) |
| 491 | |
| 492 | assert len(transport.requests) == 1 |
| 493 | assert exc.value.status_code == 402 |
| 494 | |
| 495 | |
| 496 | def test_doctor_predicts_the_same_web_backend_as_the_runtime(proxy_env): |
| 497 | own_parallel = _config(PARALLEL_API_KEY="user-parallel") |
| 498 | resolution = backends.resolve("web", own_parallel) |
| 499 | assert resolution.active_backend == grounding.configured_backend(own_parallel) == "parallel" |
| 500 | assert resolution.chain == ["brave", "exa", "parallel", "serper", "keyless", "parallel-mcp"] |
| 501 | |
| 502 | proxied_only = _config() |
| 503 | resolution = backends.resolve("web", proxied_only) |
| 504 | assert resolution.active_backend == grounding.configured_backend(proxied_only) == "serper" |
| 505 | |
| 506 | # An explicit pin still wins over the preference. |
| 507 | assert backends.resolve("web", own_parallel, pin="serper").active_backend == "serper" |
| 508 | |
| 509 | |
| 510 | def test_doctor_x_chain_ranks_proxied_xai_last_like_the_runtime(proxy_env): |
| 511 | config = _config(XQUIK_API_KEY="user-xquik") |
| 512 | resolution = backends.resolve("x", config) |
| 513 | assert resolution.chain[-1] == "xai" |
| 514 | assert resolution.chain.index("xquik") < resolution.chain.index("xai") |
| 515 | |
| 516 | |
| 517 | def test_doctor_chain_order_unchanged_outside_proxy_mode(): |
| 518 | config = {"PARALLEL_API_KEY": "user-parallel", "SERPER_API_KEY": "user-serper"} |
| 519 | resolution = backends.resolve("web", config) |
| 520 | assert resolution.chain == list(backends.WEB_BACKEND_ORDER) |
| 521 | assert resolution.active_backend == "serper" |
| 522 | |
| 523 | |
| 524 | def test_web_falls_back_to_parallel_when_the_service_cannot_serve_serper(proxy_env, monkeypatch): |
| 525 | """The hosted service may hold no Serper key; web search moves on to Parallel.""" |
| 526 | def answer(req): |
| 527 | if "/proxy/serper/" in req.full_url: |
| 528 | return _http_error(req.full_url, 503, {"error": "not available", "code": "provider_unavailable"}) |
| 529 | return Response( |
| 530 | {"results": [{"url": "https://example.com/a", "title": "A", "excerpts": ["x"], "publish_date": "2026-11-10"}]}, |
| 531 | headers={"x-l30d-charge-credits": "0.500000"}, |
| 532 | ) |
| 533 | |
| 534 | transport = Transport(answer) |
| 535 | monkeypatch.setattr(http, "_open_request", transport) |
| 536 | config = _config() |
| 537 | config["EXCLUDE_SOURCES"] = "reddit" |
| 538 | |
| 539 | items, artifact = grounding.web_search("claude", ("2026-10-20", "2026-11-19"), config) |
| 540 | |
| 541 | urls = [req.full_url for req in transport.requests] |
| 542 | assert any("/proxy/serper/" in url for url in urls) |
| 543 | assert any("/proxy/parallel/" in url for url in urls) |
| 544 | assert artifact.get("label") == "parallel" |
| 545 | assert proxy.provider_unavailable("serper") |
| 546 | assert grounding.configured_backend(config) == "parallel" |
| 547 | |
| 548 | |
| 549 | def test_web_failure_on_an_available_backend_still_raises(proxy_env, monkeypatch): |
| 550 | transport = Transport(_http_error("https://x", 500, {"error": "boom"})) |
| 551 | monkeypatch.setattr(http, "_open_request", transport) |
| 552 | config = _config() |
| 553 | with pytest.raises(Exception): |
| 554 | grounding.web_search("claude", ("2026-10-20", "2026-11-19"), config) |
| 555 | assert not any("/proxy/parallel/" in req.full_url for req in transport.requests) |
| 556 |