diff --git a/CHANGELOG.md b/CHANGELOG.md index 3994d10..f8881b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## [0.82.0] - 2026-11-23 + +### Added +- `google.search.search()` and `google.search.light()`: an `organic_results` item whose `link` is still a Google redirect (`https://www.google.com/goto?url=...`) now also has `link_token` (string) and `retry_after_seconds` (int, 0 = can be resolved right away). Both are `None` when `link` is already the real URL. The responses are plain dicts, so no call changes. +- `google.search.resolve(results)` makes one `POST /v1/google/resolve` request and returns `{"results": [...], "retry_after_seconds": int | None}`. It takes 1 to 25 rows, each with a `link_token`; other fields are returned unchanged, so `organic_results` items can be sent as they are. Each returned row is resolved (`link` is the result's own URL, no `link_token`), not ready (`link_token` and `retry_after_seconds`; the token can differ from the one sent, always keep the latest) or failed (`link_token` and `error`; do not send it again). Costs no credits. +- `google.search.resolve_all(results, *, max_wait=240.0)` calls `resolve` in requests of at most 25 rows, sleeps the `retry_after_seconds` the API returns (at least 1 second) and repeats until no row is waiting or `max_wait` seconds have passed. It returns a new list in the input order and does not change the input. Rows without a `link_token` are returned as they are and never sent. Rows that are still not ready at `max_wait` are returned with their latest `link_token` and `retry_after_seconds`; no exception is raised for them. +- Google limits how fast the links of one result page can be followed. Polling this way, all ten links of a page are usually known 45 to 70 seconds after the search. + ## [0.81.0] - 2026-11-18 ### Added diff --git a/README.md b/README.md index 49782b7..0ce95f2 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ The official Python SDK for [ScrapeBadger](https://scrapebadger.com) - async web - **Resilient retries** - Exponential backoff on transient errors - **Async requests and webhooks** - Submit any slow call, poll or `wait` for it, or take a signed webhook; idempotency keys make re-submits safe - **37+ Twitter endpoints** - Tweets, users, lists, communities, trends, geo, real-time streams -- **20 Google product APIs** - Search (with optional deferred AI Overview follow-up), Maps, News, Hotels, Trends (incl. topic autocomplete), Jobs, Shopping (+ merchant URL enrichment), Patents, Scholar (search + profiles + author + author citation + cite formats), Images, Videos, Finance, AI Mode, Lens, **Local Pack**, **Shorts**, **Flights**, Products, **Ads Transparency Center** +- **20 Google product APIs** - Search (with optional deferred AI Overview follow-up and free result link resolution), Maps, News, Hotels, Trends (incl. topic autocomplete), Jobs, Shopping (+ merchant URL enrichment), Patents, Scholar (search + profiles + author + author citation + cite formats), Images, Videos, Finance, AI Mode, Lens, **Local Pack**, **Shorts**, **Flights**, Products, **Ads Transparency Center** - **Vinted scraping** - Search items, item details, user profiles, brands, colors, markets - **Reddit scraping** - Search posts/subreddits/users/domains, subreddit posts, post comments, user profiles, trophies, wiki pages, moderators - **Web scraping** - Anti-bot bypass, JS rendering, screenshots, and selector/AI data extraction diff --git a/docs/google.md b/docs/google.md index 7f52d68..3be2f5e 100644 --- a/docs/google.md +++ b/docs/google.md @@ -31,7 +31,9 @@ async with ScrapeBadger(api_key="your-key") as client: ) # Structured sections: # serp["organic_results"] — position, title, link, snippet, displayed_link, - # date, sitelinks, rich_snippet, read_more_link + # date, sitelinks, rich_snippet, read_more_link, + # link_token, retry_after_seconds (see + # "Resolving result links" below) # serp["knowledge_graph"] — title, type, description, attributes # serp["ai_overview"] — text_blocks (paragraph/heading/list, with # reference_indexes), references, videos @@ -73,6 +75,89 @@ answered) at today's price); a question that does not come back is not billed. It adds about a second per question and upgrades `mode="fast"` to full. Light Search does not accept it. +#### Resolving result links + +Google can return a result's URL as a redirect link +(`https://www.google.com/goto?url=...`) instead of the page's own URL. In +`search()` and `light()` responses, each `organic_results` item whose `link` is +still a redirect has two more fields: + +| Field | Type | Meaning | +|---|---|---| +| `link_token` | `str` or `None` | Send it to `resolve()` to get the real URL. | +| `retry_after_seconds` | `int` or `None` | Seconds to wait before resolving. `0` means it can be resolved right away. | + +Both are `None` when `link` is already the real URL. + +Google limits how fast the links of one result page can be followed, so not +every link is ready at once. `resolve_all()` sends the results, waits as long +as the API asks, and repeats until every link is known. Resolving costs no +credits. + +```python +import asyncio + +from scrapebadger import ScrapeBadger + + +async def main() -> None: + async with ScrapeBadger(api_key="your-key") as client: + serp = await client.google.search.search("python 3.13") + results = await client.google.search.resolve_all(serp["organic_results"]) + for result in results: + if result.get("error"): + print(result["position"], "failed:", result["error"]) + elif result.get("link_token"): + print(result["position"], "not ready, wait", result["retry_after_seconds"], "s") + else: + print(result["position"], result["link"]) + + +asyncio.run(main()) +``` + +`resolve_all(results, *, max_wait=240.0)` returns a new list with one row per +input row, in the same order. It does not change the list you pass in. Rows +without a `link_token` are returned as they are and never sent. Each row that +had a `link_token` comes back in one of three states: + +| State | How to tell | What to do | +|---|---|---| +| Resolved | No `link_token`, no `retry_after_seconds`, no `error` | `link` is the result's own URL. | +| Not ready | `link_token` and `retry_after_seconds` (1 or more) | Wait that many seconds, then send the row again. The token can differ from the one you sent: always keep the latest. `link` is as you sent it. | +| Failed | `link_token` and `error` (a string) | Do not send it again. | + +`resolve_all()` stops when no row is waiting or after `max_wait` seconds. It +does not raise for rows that are still not ready at that point: they are +returned with their latest `link_token` and `retry_after_seconds`, so you can +pass them to `resolve_all()` or `resolve()` later. + +Typical timing with `resolve_all()`: all ten links of a result page are known +45 to 70 seconds after the search. Once the result page is about 160 seconds old, every +remaining link resolves in a single request. + +`resolve(results)` makes one `POST /v1/google/resolve` request, for your own +loop. It takes 1 to 25 rows, each with a `link_token`. Other fields on a row +are returned unchanged, so `organic_results` items can be sent as they are. + +```python +async with ScrapeBadger(api_key="your-key") as client: + serp = await client.google.search.search("python 3.13") + pending = [r for r in serp["organic_results"] if r.get("link_token")] + if pending: + answer = await client.google.search.resolve(pending) + for row in answer["results"]: # same order as sent + print(row["position"], row["link"], row.get("retry_after_seconds")) + # Smallest wait among the rows that are not ready, or None when none is waiting + print(answer["retry_after_seconds"]) +``` + +Sending a token before its wait is over is not an error: the row comes back +not ready with the wait that is left. An invalid request (no rows, more than +25, or a row without `link_token`) raises `ValidationError` (422). When link +resolution is temporarily unavailable the API answers 503 with `Retry-After`; +the SDK retries it and raises `ServerError` if it still fails. + ### Maps (Search, Place, Reviews, Photos, Posts) ```python @@ -353,6 +438,8 @@ look-alikes and lists the `variants` it searched. | Sub-client | Method | Description | |---|---|---| | `search` | `search(q, *, gl, hl, num, start, domain, device, ...)` | Web search with 21 parameters | +| `search` | `resolve(results)` | Real URLs for up to 25 results with a `link_token`, one request (free) | +| `search` | `resolve_all(results, *, max_wait)` | Resolve every result link, waiting and retrying as needed (free); returns a list | | `maps` | `search(q, *, ll, gl, hl, start)` | Place search by query | | `maps` | `place(*, place_id, data_id, hl, gl)` | Place detail | | `maps` | `reviews(data_id, *, sort_by, hl, next_page_token, results)` | Paginated reviews | @@ -387,7 +474,7 @@ look-alikes and lists the `variants` it searched. | `ads` | `advertiser(advertiser_id, *, region, start_date, end_date)` | Disclosed spend and ad mix | | `ads` | `creative(advertiser_id, creative_id, *, region, political)` | One creative with variations | -All methods are async and return `dict[str, Any]` responses matching the documented JSON shapes. +All methods are async and return `dict[str, Any]` responses matching the documented JSON shapes, except `search.resolve_all`, which returns a list of result rows. ## Credit Costs @@ -400,6 +487,7 @@ All methods are async and return `dict[str, Any]` responses matching the documen | `ads/search` | **25** | | `ads/advertisers` with `fuzzy=true` (billed as 3 lookups) | **45** | | `shopping/product`, `shopping/product/click` | **1** | +| `resolve` (`/v1/google/resolve`) | **0** | | Failed requests | **0** | Prices change; `GET /api/public/pricing` (or the [pricing page](https://scrapebadger.com/pricing)) always has the live per-endpoint cost. diff --git a/pyproject.toml b/pyproject.toml index bc05018..cda700b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "scrapebadger" -version = "0.81.0" +version = "0.82.0" description = "Official Python SDK for ScrapeBadger - Async web scraping APIs for Twitter and more" readme = "README.md" license = { text = "MIT" } diff --git a/src/scrapebadger/__init__.py b/src/scrapebadger/__init__.py index d649102..209327a 100644 --- a/src/scrapebadger/__init__.py +++ b/src/scrapebadger/__init__.py @@ -1356,7 +1356,7 @@ async def main(): ZestimateHistoryPoint as ZillowZestimateHistoryPoint, ) -__version__ = "0.81.0" +__version__ = "0.82.0" __all__ = [ # TikTok core models diff --git a/src/scrapebadger/_internal/client.py b/src/scrapebadger/_internal/client.py index 8484e08..40e4fe8 100644 --- a/src/scrapebadger/_internal/client.py +++ b/src/scrapebadger/_internal/client.py @@ -56,7 +56,7 @@ T = TypeVar("T") # User agent for SDK requests -SDK_VERSION = "0.81.0" +SDK_VERSION = "0.82.0" USER_AGENT = f"scrapebadger-python/{SDK_VERSION}" diff --git a/src/scrapebadger/google/search.py b/src/scrapebadger/google/search.py index c65b65d..11eac96 100644 --- a/src/scrapebadger/google/search.py +++ b/src/scrapebadger/google/search.py @@ -2,11 +2,23 @@ from __future__ import annotations +import asyncio +from time import monotonic from typing import TYPE_CHECKING, Any, Literal, overload if TYPE_CHECKING: from scrapebadger._internal.client import BaseClient +# POST /v1/google/resolve takes 1 to 25 rows per request. +_RESOLVE_MAX_ROWS = 25 +# resolve_all() waits at least this long between two rounds of requests. +_RESOLVE_MIN_WAIT_S = 1.0 + + +def _is_waiting(row: dict[str, Any]) -> bool: + """True when a row has a ``link_token`` to send and has not failed.""" + return bool(row.get("link_token")) and row.get("error") is None + class SearchClient: """Client for Google Web Search. @@ -16,6 +28,9 @@ class SearchClient: serp = await client.google.search.search("python 3.13") for result in serp["organic_results"]: print(result["title"], result["link"]) + + # Some links are still Google redirects: get the real URLs (free). + results = await client.google.search.resolve_all(serp["organic_results"]) ``` """ @@ -332,7 +347,11 @@ async def search( organic_results_state - `organic_results`: position/title/link/snippet/displayed_link, plus `date`, `sitelinks`, `rich_snippet` and `read_more_link` - when Google shows them + when Google shows them. A result whose `link` is still a + Google redirect also has `link_token` and + `retry_after_seconds` (0 = can be resolved right away); both + are ``None`` when `link` is already the real URL. Pass the + results to :meth:`resolve_all` to get the real URLs. - `ads`, `knowledge_graph`, `related_searches`, `people_also_search_for` - `related_questions`: question, rank, `type` (``"ai_overview"`` @@ -679,7 +698,9 @@ async def light( pagination}`` — no ``ai_overview`` / ``knowledge_graph`` / ``ads`` / ``local_results`` / ``news_results`` blocks. ``search_information.organic_results_state`` is filled, as on - full Search. + full Search. ``organic_results`` items carry ``link_token`` and + ``retry_after_seconds`` as on full Search; pass them to + :meth:`resolve_all` to get the real URLs. """ params: dict[str, Any] = { "google_domain": google_domain, @@ -732,3 +753,121 @@ async def light( body, _, _ = await self._client.get_raw("/v1/google/light/search", params=params) return body.decode("utf-8") return await self._client.get("/v1/google/light/search", params=params) + + async def resolve(self, results: list[dict[str, Any]]) -> dict[str, Any]: + """Get the real URLs of results whose ``link`` is a Google redirect. + + Calls ``POST /v1/google/resolve`` once. Costs no credits. + + A result from :meth:`search` or :meth:`light` whose ``link`` is still + a Google redirect (``https://www.google.com/goto?url=...``) has a + ``link_token``. Google limits how fast the links of one result page + can be followed, so a row can come back not ready, with the number of + seconds to wait. :meth:`resolve_all` does the waiting and retrying + for you. + + Args: + results: 1 to 25 rows. Each row needs a non-empty string + ``link_token``. Any other fields are returned unchanged on + the row, so ``organic_results`` items can be sent as they + are. + + Returns: + ``{"results": [...], "retry_after_seconds": int | None}``. The + rows come back in the order sent. Each row is one of: + + - resolved: ``link`` is the result's own URL. The row has no + ``link_token``, ``retry_after_seconds`` or ``error``. + - not ready: the row has ``link_token`` and + ``retry_after_seconds`` (1 or more). Wait that many seconds, + then send the row again. The token can differ from the one + sent: always keep the latest. ``link`` is as sent. + - failed: the row has ``link_token`` as sent and ``error`` (a + string). Do not send it again. + + The top-level ``retry_after_seconds`` is the smallest wait among + the not-ready rows, or ``None`` when no row is waiting. Sending + a token before its wait is over is not an error: the row comes + back not ready with the wait that is left. + + Raises: + ValidationError: 422 for an empty list, more than 25 rows, or a + row without ``link_token``. + ServerError: 503 when link resolution is temporarily + unavailable. The SDK retries it first, like other 5xx. + """ + return await self._client.post("/v1/google/resolve", json={"results": results}) + + async def resolve_all( + self, results: list[dict[str, Any]], *, max_wait: float = 240.0 + ) -> list[dict[str, Any]]: + """Resolve every result link, waiting between requests as the API asks. + + Calls :meth:`resolve` with the rows that have a ``link_token``, at + most 25 per request, then sleeps the smallest ``retry_after_seconds`` + returned (at least 1 second) and sends the rows that are still not + ready again. It stops when no row is waiting or when ``max_wait`` + seconds have passed. Costs no credits. + + Polling this way, all ten links of a result page are usually known + 45 to 70 seconds after the search. Once the result page is about 160 + seconds old, every remaining link resolves in a single request. + + Args: + results: Result rows, normally a search response's + ``organic_results``. Rows without a ``link_token`` are + returned as they are and never sent. The list and its rows + are not modified. + max_wait: Stop after this many seconds (default 240). The last + sleep is cut so that it does not pass this limit. With 0, + each row is sent once. + + Returns: + A new list with one row per input row, in the same order. Each + row that had a ``link_token`` is in one of the states described + in :meth:`resolve`: + + - resolved: ``link`` is the result's own URL. + - failed: the row has ``error``. It is not sent again. + - not ready: ``max_wait`` passed first. The row has its latest + ``link_token`` and ``retry_after_seconds``, so you can pass it + to :meth:`resolve` or :meth:`resolve_all` later. No exception + is raised for these rows. + + Raises: + ScrapeBadgerError: A request failed (see :meth:`resolve`). + + Example: + ```python + serp = await client.google.search.search("python 3.13") + results = await client.google.search.resolve_all(serp["organic_results"]) + for result in results: + if result.get("error"): + print("failed:", result["error"]) + elif result.get("link_token"): + print("not ready, wait", result["retry_after_seconds"], "s") + else: + print(result["link"]) + ``` + """ + rows = [dict(row) for row in results] + deadline = monotonic() + max_wait + waiting = [i for i, row in enumerate(rows) if _is_waiting(row)] + while waiting: + waits: list[float] = [] + for start in range(0, len(waiting), _RESOLVE_MAX_ROWS): + chunk = waiting[start : start + _RESOLVE_MAX_ROWS] + response = await self.resolve([rows[i] for i in chunk]) + for i, row in zip(chunk, response.get("results") or [], strict=False): + if isinstance(row, dict): + rows[i] = row + wait = response.get("retry_after_seconds") + if isinstance(wait, int | float): + waits.append(wait) + waiting = [i for i in waiting if _is_waiting(rows[i])] + remaining = deadline - monotonic() + if not waiting or remaining <= 0: + break + delay = max(min(waits, default=_RESOLVE_MIN_WAIT_S), _RESOLVE_MIN_WAIT_S) + await asyncio.sleep(min(delay, remaining)) + return rows diff --git a/tests/test_google.py b/tests/test_google.py index e67be5c..26cadb6 100644 --- a/tests/test_google.py +++ b/tests/test_google.py @@ -6,7 +6,10 @@ from __future__ import annotations -from unittest.mock import AsyncMock, MagicMock +import copy +from collections.abc import Iterator +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -43,6 +46,61 @@ def google(mock_base_client: MagicMock) -> GoogleClient: return GoogleClient(mock_base_client) +GOTO = "https://www.google.com/goto?url=abc" + + +def redirect_row(position: int, token: str | None = None, wait: int = 0) -> dict[str, Any]: + """An organic result whose link is still a Google redirect.""" + return { + "position": position, + "title": f"Result {position}", + "link": GOTO, + "link_token": token or f"tok-{position}", + "retry_after_seconds": wait, + } + + +def resolved_row(position: int) -> dict[str, Any]: + """The same result once resolved: the real link and no token.""" + return { + "position": position, + "title": f"Result {position}", + "link": f"https://example.com/{position}", + } + + +def sent_rows(mock_base_client: MagicMock) -> list[list[dict[str, Any]]]: + """The rows of every POST /v1/google/resolve made so far.""" + for call in mock_base_client.post.await_args_list: + assert call.args == ("/v1/google/resolve",) + return [call.kwargs["json"]["results"] for call in mock_base_client.post.await_args_list] + + +class FakeClock: + """Time moves only when the code under test sleeps.""" + + def __init__(self) -> None: + self.now = 1000.0 + self.sleeps: list[float] = [] + + def monotonic(self) -> float: + return self.now + + async def sleep(self, seconds: float) -> None: + self.sleeps.append(seconds) + self.now += seconds + + +@pytest.fixture +def clock() -> Iterator[FakeClock]: + fake = FakeClock() + with ( + patch("scrapebadger.google.search.monotonic", fake.monotonic), + patch("scrapebadger.google.search.asyncio.sleep", fake.sleep), + ): + yield fake + + class TestGoogleClientWiring: def test_sub_clients_lazy_and_typed(self, google: GoogleClient) -> None: assert isinstance(google.search, SearchClient) @@ -149,6 +207,257 @@ async def test_light_uses_dedicated_endpoint( for key in ("mode", "ai_overview", "expand_related_questions"): assert key not in params + @pytest.mark.asyncio + async def test_resolve_posts_results( + self, google: GoogleClient, mock_base_client: MagicMock + ) -> None: + rows = [redirect_row(1), redirect_row(2, wait=6)] + answer = { + "results": [resolved_row(1), redirect_row(2, "tok-2b", wait=6)], + "retry_after_seconds": 6, + } + mock_base_client.post.return_value = answer + + out = await google.search.resolve(rows) + + mock_base_client.post.assert_awaited_once_with("/v1/google/resolve", json={"results": rows}) + assert out is answer + + @pytest.mark.asyncio + async def test_resolve_all_resolved_on_first_call( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + mock_base_client.post.return_value = { + "results": [resolved_row(1), resolved_row(2)], + "retry_after_seconds": None, + } + + out = await google.search.resolve_all([redirect_row(1), redirect_row(2)]) + + assert out == [resolved_row(1), resolved_row(2)] + assert sent_rows(mock_base_client) == [[redirect_row(1), redirect_row(2)]] + assert clock.sleeps == [] + + @pytest.mark.asyncio + async def test_resolve_all_retries_not_ready_row_with_new_token( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + mock_base_client.post.side_effect = [ + { + "results": [resolved_row(1), redirect_row(2, "tok-2-new", wait=7)], + "retry_after_seconds": 7, + }, + {"results": [resolved_row(2)], "retry_after_seconds": None}, + ] + + out = await google.search.resolve_all([redirect_row(1), redirect_row(2)]) + + assert out == [resolved_row(1), resolved_row(2)] + first, second = sent_rows(mock_base_client) + assert [row["link_token"] for row in first] == ["tok-1", "tok-2"] + # Only the row that was not ready goes out again, with the token from the answer. + assert second == [redirect_row(2, "tok-2-new", wait=7)] + assert clock.sleeps == [7] + + @pytest.mark.asyncio + async def test_resolve_all_sleeps_at_least_one_second( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + mock_base_client.post.side_effect = [ + {"results": [redirect_row(1, wait=0)], "retry_after_seconds": 0}, + {"results": [redirect_row(1)], "retry_after_seconds": None}, + {"results": [resolved_row(1)], "retry_after_seconds": None}, + ] + + out = await google.search.resolve_all([redirect_row(1)]) + + assert out == [resolved_row(1)] + # A wait of 0 and a missing wait both become 1 second. + assert clock.sleeps == [1, 1] + + @pytest.mark.asyncio + async def test_resolve_all_does_not_resend_failed_row( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + failed = {**redirect_row(2), "error": "link could not be resolved"} + del failed["retry_after_seconds"] + mock_base_client.post.side_effect = [ + {"results": [redirect_row(1, wait=3), failed], "retry_after_seconds": 3}, + {"results": [resolved_row(1)], "retry_after_seconds": None}, + ] + + out = await google.search.resolve_all([redirect_row(1), redirect_row(2)]) + + assert out == [resolved_row(1), failed] + assert out[1]["link_token"] == "tok-2" + first, second = sent_rows(mock_base_client) + assert [row["position"] for row in first] == [1, 2] + assert [row["position"] for row in second] == [1] + assert clock.sleeps == [3] + + @pytest.mark.asyncio + async def test_resolve_all_never_sends_row_that_already_has_error( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + failed = {**redirect_row(1), "error": "link could not be resolved"} + + out = await google.search.resolve_all([failed]) + + assert out == [failed] + mock_base_client.post.assert_not_awaited() + + @pytest.mark.asyncio + async def test_resolve_all_sends_chunks_of_25( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + async def answer(_path: str, *, json: dict[str, Any]) -> dict[str, Any]: + return { + "results": [resolved_row(row["position"]) for row in json["results"]], + "retry_after_seconds": None, + } + + mock_base_client.post.side_effect = answer + + out = await google.search.resolve_all([redirect_row(n) for n in range(1, 61)]) + + chunks = sent_rows(mock_base_client) + assert [len(chunk) for chunk in chunks] == [25, 25, 10] + assert [row["position"] for chunk in chunks for row in chunk] == list(range(1, 61)) + assert out == [resolved_row(n) for n in range(1, 61)] + assert clock.sleeps == [] + + @pytest.mark.asyncio + async def test_resolve_all_sleeps_smallest_wait_of_all_chunks( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + waits = iter([9, 4]) + calls = 0 + + async def answer(_path: str, *, json: dict[str, Any]) -> dict[str, Any]: + nonlocal calls + calls += 1 + if calls > 2: # second round: everything resolves + return { + "results": [resolved_row(row["position"]) for row in json["results"]], + "retry_after_seconds": None, + } + wait = next(waits) + return { + "results": [redirect_row(row["position"], wait=wait) for row in json["results"]], + "retry_after_seconds": wait, + } + + mock_base_client.post.side_effect = answer + + out = await google.search.resolve_all([redirect_row(n) for n in range(1, 31)]) + + assert [len(chunk) for chunk in sent_rows(mock_base_client)] == [25, 5, 25, 5] + assert out == [resolved_row(n) for n in range(1, 31)] + assert clock.sleeps == [4] + + @pytest.mark.asyncio + async def test_resolve_all_returns_waiting_rows_at_deadline( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + calls = 0 + + async def answer(_path: str, *, json: dict[str, Any]) -> dict[str, Any]: + nonlocal calls + calls += 1 + return { + "results": [ + redirect_row(row["position"], f"tok-{row['position']}-v{calls}", wait=7) + for row in json["results"] + ], + "retry_after_seconds": 7, + } + + mock_base_client.post.side_effect = answer + + out = await google.search.resolve_all([redirect_row(1), redirect_row(2)], max_wait=10) + + # No exception: the rows come back with their latest token and wait. + assert out == [redirect_row(1, "tok-1-v3", wait=7), redirect_row(2, "tok-2-v3", wait=7)] + # The second sleep is cut to what is left of max_wait, then one last request. + assert clock.sleeps == [7, 3] + assert calls == 3 + + @pytest.mark.asyncio + async def test_resolve_all_max_wait_zero_sends_once( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + mock_base_client.post.return_value = { + "results": [redirect_row(1, "tok-1-new", wait=5)], + "retry_after_seconds": 5, + } + + out = await google.search.resolve_all([redirect_row(1)], max_wait=0) + + assert out == [redirect_row(1, "tok-1-new", wait=5)] + mock_base_client.post.assert_awaited_once() + assert clock.sleeps == [] + + @pytest.mark.asyncio + async def test_resolve_all_skips_rows_without_token( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + real_null = { + "position": 1, + "link": "https://example.com/real-1", + "link_token": None, + "retry_after_seconds": None, + } + real_bare = {"position": 3, "link": "https://example.com/real-3"} + mock_base_client.post.return_value = { + "results": [resolved_row(2), resolved_row(4)], + "retry_after_seconds": None, + } + + out = await google.search.resolve_all( + [real_null, redirect_row(2), real_bare, redirect_row(4)] + ) + + assert sent_rows(mock_base_client) == [[redirect_row(2), redirect_row(4)]] + assert out == [real_null, resolved_row(2), real_bare, resolved_row(4)] + + @pytest.mark.asyncio + async def test_resolve_all_nothing_to_resolve_makes_no_request( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + rows = [{"position": 1, "link": "https://example.com/1", "link_token": None}] + + assert await google.search.resolve_all(rows) == rows + assert await google.search.resolve_all([]) == [] + mock_base_client.post.assert_not_awaited() + assert clock.sleeps == [] + + @pytest.mark.asyncio + async def test_resolve_all_does_not_mutate_input( + self, google: GoogleClient, mock_base_client: MagicMock, clock: FakeClock + ) -> None: + rows = [ + {"position": 1, "link": "https://example.com/1", "link_token": None}, + {**redirect_row(2), "sitelinks": [{"title": "Docs"}]}, + redirect_row(3), + ] + before = copy.deepcopy(rows) + row_ids = [id(row) for row in rows] + mock_base_client.post.side_effect = [ + { + "results": [resolved_row(2), redirect_row(3, "tok-3-new", wait=2)], + "retry_after_seconds": 2, + }, + {"results": [resolved_row(3)], "retry_after_seconds": None}, + ] + + out = await google.search.resolve_all(rows) + + assert rows == before + assert [id(row) for row in rows] == row_ids + assert out is not rows + assert all(new is not old for new, old in zip(out, rows, strict=True)) + assert out == [before[0], resolved_row(2), resolved_row(3)] + class TestMapsClient: @pytest.mark.asyncio diff --git a/uv.lock b/uv.lock index 08189a2..c5e2f8d 100644 --- a/uv.lock +++ b/uv.lock @@ -930,7 +930,7 @@ wheels = [ [[package]] name = "scrapebadger" -version = "0.81.0" +version = "0.82.0" source = { editable = "." } dependencies = [ { name = "httpx" },