Skip to content

Automate browser based workflows with AI

feat(SKY-11846): shared test-fixture library slice + first consolidation exemplars (#7114)

Suchintanec773e02d680
diff --git a/tests/unit/_mcp_browser_fakes.py b/tests/unit/_mcp_browser_fakes.py
new file mode 100644
index 000000000..c57a0673a
--- /dev/null
+++ b/tests/unit/_mcp_browser_fakes.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from skyvern.cli.core.result import BrowserContext
+from skyvern.cli.core.session_manager import SessionState
+
+
+def make_session_state(**overrides: Any) -> SessionState:
+ state = SessionState()
+ for key, value in overrides.items():
+ setattr(state, key, value)
+ return state
+
+
+def make_page(raw: MagicMock | None = None) -> SimpleNamespace:
+ if raw is None:
+ raw = MagicMock()
+ raw.on = MagicMock()
+ return SimpleNamespace(page=raw)
+
+
+def make_mock_page(
+ url: str = "https://example.com",
+ *,
+ with_context: bool = True,
+ with_evaluate: bool = True,
+ with_locator: bool = True,
+ with_self_page: bool = True,
+) -> MagicMock:
+ page = MagicMock()
+ page.url = url
+ if with_self_page:
+ page.page = page
+ if with_evaluate:
+ page.evaluate = AsyncMock(return_value={})
+ if with_context:
+ page.context = MagicMock()
+ page.context.grant_permissions = AsyncMock()
+ if with_locator:
+ locator = MagicMock()
+ locator.evaluate = AsyncMock(return_value="<span>hello</span>")
+ locator.input_value = AsyncMock(return_value="test-value")
+ page.locator = MagicMock(return_value=locator)
+ return page
+
+
+def make_skyvern_page(page: MagicMock) -> MagicMock:
+ wrapper = MagicMock()
+ wrapper.page = page
+ wrapper.url = page.url
+ if "evaluate" in page.__dict__:
+ wrapper.evaluate = page.evaluate
+ if "locator" in page.__dict__:
+ wrapper.locator = page.locator
+ if "context" in page.__dict__:
+ wrapper.context = page.context
+ return wrapper
+
+
+def patch_get_page(monkeypatch: pytest.MonkeyPatch, module: Any, page: MagicMock, ctx: BrowserContext) -> AsyncMock:
+ mock = AsyncMock(return_value=(make_skyvern_page(page), ctx))
+ monkeypatch.setattr(module, "get_page", mock)
+ return mock
diff --git a/tests/unit/google/conftest.py b/tests/unit/google/conftest.py
new file mode 100644
index 000000000..e6da95a8c
--- /dev/null
+++ b/tests/unit/google/conftest.py
@@ -0,0 +1,24 @@
+from collections.abc import Callable
+from typing import Any
+
+import httpx
+import pytest
+
+from skyvern.forge.sdk.services import google_sheets_service
+
+
+def mock_sheets_transport(
+ monkeypatch: pytest.MonkeyPatch,
+) -> Callable[[Callable[[httpx.Request], httpx.Response]], None]:
+ def install(handler: Callable[[httpx.Request], httpx.Response]) -> None:
+ transport = httpx.MockTransport(handler)
+ real_client = httpx.AsyncClient
+
+ def fake_async_client(*args: Any, **kwargs: Any) -> httpx.AsyncClient:
+ kwargs["transport"] = transport
+ return real_client(*args, **kwargs)
+
+ monkeypatch.setattr(google_sheets_service.httpx, "AsyncClient", fake_async_client)
+
+ return install
diff --git a/tests/unit/google/test_google_sheets_service.py b/tests/unit/google/test_google_sheets_service.py
new file mode 100644
index 000000000..3eb00cccd
--- /dev/null
+++ b/tests/unit/google/test_google_sheets_service.py
@@ -0,0 +1,694 @@
+"""Tests for skyvern.forge.sdk.services.google_sheets_service."""
+
+from collections.abc import Callable
+from datetime import datetime, timezone
+from typing import Any
+
+import httpx
+import pytest
+
+from skyvern.forge.sdk.services import google_sheets_service
+
+TransportInstaller = Callable[[Callable[[httpx.Request], httpx.Response]], None]
+
+
+class TestSpreadsheetId:
+ def test_extract_spreadsheet_id_from_url(self) -> None:
+ url = "https://docs.google.com/spreadsheets/d/1AbC-XyZ_123/edit#gid=0"
+ assert google_sheets_service.extract_spreadsheet_id(url) == "1AbC-XyZ_123"
+
+ def test_extract_spreadsheet_id_bare(self) -> None:
+ bare = "1AbCdEfGhIjKlMnOpQrSt_12345"
+ assert google_sheets_service.extract_spreadsheet_id(bare) == bare
+
+ def test_extract_spreadsheet_id_invalid(self) -> None:
+ with pytest.raises(ValueError):
+ google_sheets_service.extract_spreadsheet_id("")
+ with pytest.raises(ValueError):
+ google_sheets_service.extract_spreadsheet_id("not-a-sheet")
+
+
+class TestDrivePicker:
+ def test_build_drive_q_escapes_user_input(self) -> None:
+ q = google_sheets_service._build_drive_q("Jen's sheet")
+ assert "Jen\\'s sheet" in q
+ assert "mimeType = 'application/vnd.google-apps.spreadsheet'" in q
+ assert "trashed = false" in q
+
+ @pytest.mark.asyncio
+ async def test_list_spreadsheets_sends_expected_params(self, mock_sheets_transport: TransportInstaller) -> None:
+ captured: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["url"] = str(request.url)
+ captured["auth"] = request.headers.get("Authorization")
+ return httpx.Response(
+ 200,
+ json={
+ "nextPageToken": "tok-2",
+ "files": [
+ {
+ "id": "1xyz",
+ "name": "Leads",
+ "modifiedTime": "2026-04-10T00:00:00Z",
+ "webViewLink": "https://docs.google.com/spreadsheets/d/1xyz",
+ },
+ {"id": "", "name": "skip-empty-id"},
+ ],
+ },
+ )
+
+ mock_sheets_transport(handler)
+
+ paged = await google_sheets_service.list_spreadsheets(
+ access_token="at-1",
+ query="leads",
+ page_token="tok-1",
+ page_size=50,
+ )
+
+ assert paged.next_page_token == "tok-2"
+ assert len(paged.spreadsheets) == 1
+ assert paged.spreadsheets[0].id == "1xyz"
+ assert paged.spreadsheets[0].name == "Leads"
+ assert captured["auth"] == "Bearer at-1"
+ assert "pageSize=50" in captured["url"]
+ assert "pageToken=tok-1" in captured["url"]
+ assert "supportsAllDrives=true" in captured["url"]
+ assert "includeItemsFromAllDrives=true" in captured["url"]
+
+
+class TestReconnectRequired:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("operation", ["list_spreadsheets", "get_sheet_headers"])
+ async def test_403_insufficient_scope_maps_to_reconnect_required(
+ self,
+ mock_sheets_transport: TransportInstaller,
+ operation: str,
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 403,
+ json={
+ "error": {
+ "message": "Request had insufficient authentication scopes.",
+ "errors": [{"reason": "insufficientPermissions"}],
+ }
+ },
+ )
+
+ mock_sheets_transport(handler)
+
+ with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc_info:
+ if operation == "list_spreadsheets":
+ await google_sheets_service.list_spreadsheets(access_token="at")
+ else:
+ await google_sheets_service.get_sheet_headers(
+ access_token="tok",
+ spreadsheet_id="1abcdefghijklmnopqrst_12345",
+ sheet_title="S",
+ )
+
+ assert exc_info.value.status == 403
+ assert exc_info.value.code == "reconnect_required"
+
+
+class TestSpreadsheetMetadata:
+ @pytest.mark.asyncio
+ async def test_get_spreadsheet_tabs_parses_sheet_metadata(self, mock_sheets_transport: TransportInstaller) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert "/v4/spreadsheets/1xyz" in str(request.url)
+ return httpx.Response(
+ 200,
+ json={
+ "sheets": [
+ {"properties": {"sheetId": 0, "title": "Sheet1", "index": 0}},
+ {"properties": {"sheetId": 123, "title": "Q2", "index": 1}},
+ {"properties": {"title": "no-id-skip"}},
+ ]
+ },
+ )
+
+ mock_sheets_transport(handler)
+
+ tabs = await google_sheets_service.get_spreadsheet_tabs(
+ access_token="at",
+ spreadsheet_id="https://docs.google.com/spreadsheets/d/1xyz/edit",
+ )
+
+ assert [t.title for t in tabs] == ["Sheet1", "Q2"]
+ assert [t.sheet_id for t in tabs] == [0, 123]
+
+ @pytest.mark.asyncio
+ async def test_create_spreadsheet_posts_title(self, mock_sheets_transport: TransportInstaller) -> None:
+ captured: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = request.content.decode()
+ return httpx.Response(
+ 200,
+ json={
+ "spreadsheetId": "1newid",
+ "properties": {"title": "My Sheet"},
+ "spreadsheetUrl": "https://docs.google.com/spreadsheets/d/1newid",
+ "sheets": [{"properties": {"sheetId": 0, "title": "Sheet1", "index": 0}}],
+ },
+ )
+
+ mock_sheets_transport(handler)
+
+ created = await google_sheets_service.create_spreadsheet(access_token="at", title="My Sheet")
+
+ assert created.id == "1newid"
+ assert created.title == "My Sheet"
+ assert created.web_view_link and "1newid" in created.web_view_link
+ assert created.first_sheet_name == "Sheet1"
+ assert '"My Sheet"' in captured["body"]
+
+ @pytest.mark.asyncio
+ async def test_create_sheet_tab_returns_new_tab(self, mock_sheets_transport: TransportInstaller) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert ":batchUpdate" in str(request.url)
+ return httpx.Response(
+ 200,
+ json={"replies": [{"addSheet": {"properties": {"sheetId": 55, "title": "New Tab", "index": 3}}}]},
+ )
+
+ mock_sheets_transport(handler)
+
+ tab = await google_sheets_service.create_sheet_tab(
+ access_token="at",
+ spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
+ title="New Tab",
+ )
+
+ assert tab.sheet_id == 55
+ assert tab.title == "New Tab"
+ assert tab.index == 3
+
+ @pytest.mark.asyncio
+ async def test_api_error_maps_status_and_message(self, mock_sheets_transport: TransportInstaller) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 404,
+ json={"error": {"message": "Requested entity was not found.", "errors": [{"reason": "notFound"}]}},
+ )
+
+ mock_sheets_transport(handler)
+
+ with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc_info:
+ await google_sheets_service.get_spreadsheet_tabs(
+ access_token="at", spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345"
+ )
+
+ assert exc_info.value.status == 404
+ assert "not found" in exc_info.value.message.lower()
+
+
+class TestHeaders:
+ @pytest.mark.asyncio
+ async def test_get_sheet_headers_returns_row_one_keyed_by_letter(
+ self,
+ mock_sheets_transport: TransportInstaller,
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert "/v4/spreadsheets/1abcdefghijklmnopqrst_12345/values/%27Sheet1%27%21A1%3AZZZ1" in str(request.url)
+ return httpx.Response(
+ 200,
+ json={"range": "Sheet1!A1:ZZZ1", "values": [["Name", "Email", "Date"]]},
+ )
+
+ mock_sheets_transport(handler)
+
+ headers = await google_sheets_service.get_sheet_headers(
+ access_token="tok",
+ spreadsheet_id="1abcdefghijklmnopqrst_12345",
+ sheet_title="Sheet1",
+ )
+
+ assert headers == [
+ google_sheets_service.SheetHeader(letter="A", name="Name"),
+ google_sheets_service.SheetHeader(letter="B", name="Email"),
+ google_sheets_service.SheetHeader(letter="C", name="Date"),
+ ]
+
+ @pytest.mark.asyncio
+ async def test_get_sheet_headers_returns_empty_when_no_values(
+ self,
+ mock_sheets_transport: TransportInstaller,
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"range": "Tab!A1:ZZZ1"})
+
+ mock_sheets_transport(handler)
+
+ headers = await google_sheets_service.get_sheet_headers(
+ access_token="tok",
+ spreadsheet_id="1abcdefghijklmnopqrst_12345",
+ sheet_title="Tab",
+ )
+
+ assert headers == []
+
+ @pytest.mark.asyncio
+ async def test_get_sheet_headers_skips_blank_header_cells(
+ self,
+ mock_sheets_transport: TransportInstaller,
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"values": [["Name", "", "Date"]]})
+
+ mock_sheets_transport(handler)
+
+ headers = await google_sheets_service.get_sheet_headers(
+ access_token="tok",
+ spreadsheet_id="1abcdefghijklmnopqrst_12345",
+ sheet_title="S",
+ )
+
+ assert headers == [
+ google_sheets_service.SheetHeader(letter="A", name="Name"),
+ google_sheets_service.SheetHeader(letter="C", name="Date"),
+ ]
+
+ @pytest.mark.asyncio
+ async def test_get_sheet_headers_quotes_titles_with_spaces(
+ self,
+ mock_sheets_transport: TransportInstaller,
+ ) -> None:
+ captured: dict[str, str] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["url"] = str(request.url)
+ return httpx.Response(200, json={"values": [["Name"]]})
+
+ mock_sheets_transport(handler)
+
+ await google_sheets_service.get_sheet_headers(
+ access_token="tok",
+ spreadsheet_id="1abcdefghijklmnopqrst_12345",
+ sheet_title="Q1 Leads",
+ )
+
+ assert "%27Q1" in captured["url"] and "Leads%27%21A1%3AZZZ1" in captured["url"]
+
+ @pytest.mark.asyncio
+ async def test_get_sheet_headers_generates_letters_beyond_Z(
+ self,
+ mock_sheets_transport: TransportInstaller,
+ ) -> None:
+ row = ["h" + str(i) for i in range(28)]
+ expected_letters = [chr(ord("A") + i) for i in range(26)] + ["AA", "AB"]
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"values": [row]})
+
+ mock_sheets_transport(handler)
+
+ headers = await google_sheets_service.get_sheet_headers(
+ access_token="tok",
+ spreadsheet_id="1abcdefghijklmnopqrst_12345",
+ sheet_title="S",
+ )
+
+ assert [h.letter for h in headers] == expected_letters
+
+
+class TestGridProperties:
+ @pytest.mark.asyncio
+ async def test_get_sheet_grid_properties_returns_dimensions(
+ self, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "sheets": [
+ {
+ "properties": {
+ "sheetId": 0,
+ "title": "Other",
+ "gridProperties": {"columnCount": 50, "rowCount": 1000},
+ }
+ },
+ {
+ "properties": {
+ "sheetId": 42,
+ "title": "Target",
+ "gridProperties": {"columnCount": 26, "rowCount": 1000},
+ }
+ },
+ ]
+ },
+ )
+
+ mock_sheets_transport(handler)
+
+ grid = await google_sheets_service.get_sheet_grid_properties(
+ access_token="at",
+ spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
+ sheet_title="Target",
+ )
+
+ assert grid is not None
+ assert grid.sheet_id == 42
+ assert grid.title == "Target"
+ assert grid.column_count == 26
+ assert grid.row_count == 1000
+
+ @pytest.mark.asyncio
+ async def test_get_sheet_grid_properties_by_id_matches_numeric_id(
+ self, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "sheets": [
+ {
+ "properties": {
+ "sheetId": 7,
+ "title": "Target",
+ "gridProperties": {"columnCount": 26, "rowCount": 1000},
+ }
+ }
+ ]
+ },
+ )
+
+ mock_sheets_transport(handler)
+
+ grid = await google_sheets_service.get_sheet_grid_properties_by_id(
+ access_token="at",
+ spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
+ sheet_id=7,
+ )
+
+ assert grid is not None
+ assert grid.sheet_id == 7
+ assert grid.title == "Target"
+ assert grid.column_count == 26
+
+ @pytest.mark.asyncio
+ async def test_get_sheet_grid_properties_returns_none_when_missing(
+ self, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"sheets": []})
+
+ mock_sheets_transport(handler)
+
+ grid = await google_sheets_service.get_sheet_grid_properties(
+ access_token="at",
+ spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
+ sheet_title="Missing",
+ )
+
+ assert grid is None
+
+
+class TestRetry:
+ @pytest.mark.asyncio
+ async def test_values_append_does_not_retry_on_429(
+ self, monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ calls = {"n": 0}
+ sleeps: list[float] = []
+
+ async def fake_sleep(delay: float) -> None:
+ sleeps.append(delay)
+
+ monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls["n"] += 1
+ return httpx.Response(429, headers={"Retry-After": "2"}, json={"error": {"message": "rate limit"}})
+
+ mock_sheets_transport(handler)
+
+ with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc:
+ await google_sheets_service.values_append(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ range_="Sheet1!A1",
+ values=[["a"]],
+ )
+ assert exc.value.status == 429
+ assert calls["n"] == 1
+ assert sleeps == []
+
+ @pytest.mark.asyncio
+ async def test_values_get_retries_on_429(
+ self, monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ calls = {"n": 0}
+ sleeps: list[float] = []
+
+ async def fake_sleep(delay: float) -> None:
+ sleeps.append(delay)
+
+ monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return httpx.Response(429, headers={"Retry-After": "2"}, json={"error": {"message": "rate limit"}})
+ return httpx.Response(200, json={"values": [["a"]]})
+
+ mock_sheets_transport(handler)
+
+ payload = await google_sheets_service.values_get(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ ranges="Sheet1!A1",
+ )
+ assert payload == {"values": [["a"]]}
+ assert calls["n"] == 2
+ assert sleeps == [2.0]
+
+ @pytest.mark.asyncio
+ async def test_values_get_honors_http_date_retry_after(
+ self, monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ calls = {"n": 0}
+ sleeps: list[float] = []
+
+ async def fake_sleep(delay: float) -> None:
+ sleeps.append(delay)
+
+ monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
+
+ frozen_now = datetime(2026, 4, 21, 12, 0, 0, tzinfo=timezone.utc)
+
+ class FrozenDatetime(datetime):
+ @classmethod
+ def now(cls, tz: Any = None) -> datetime:
+ return frozen_now if tz is None else frozen_now.astimezone(tz)
+
+ monkeypatch.setattr(google_sheets_service, "datetime", FrozenDatetime)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return httpx.Response(
+ 429,
+ headers={"Retry-After": "Tue, 21 Apr 2026 12:00:05 GMT"},
+ json={"error": {"message": "rate limit"}},
+ )
+ return httpx.Response(200, json={"values": [["a"]]})
+
+ mock_sheets_transport(handler)
+
+ payload = await google_sheets_service.values_get(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ ranges="Sheet1!A1",
+ )
+ assert payload == {"values": [["a"]]}
+ assert calls["n"] == 2
+ assert sleeps == [5.0]
+
+ @pytest.mark.asyncio
+ async def test_values_get_retries_on_transport_error(
+ self, monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ calls = {"n": 0}
+ sleeps: list[float] = []
+
+ async def fake_sleep(delay: float) -> None:
+ sleeps.append(delay)
+
+ monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise httpx.ConnectError("connection refused", request=request)
+ return httpx.Response(200, json={"sheets": []})
+
+ mock_sheets_transport(handler)
+
+ payload = await google_sheets_service.values_get(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ ranges="Sheet1!A1",
+ )
+ assert payload == {"sheets": []}
+ assert calls["n"] == 2
+ assert sleeps == [1.0]
+
+ @pytest.mark.asyncio
+ async def test_values_append_does_not_replay_post_on_transport_error(
+ self, monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ calls = {"n": 0}
+
+ async def fake_sleep(delay: float) -> None:
+ return None
+
+ monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls["n"] += 1
+ raise httpx.ReadTimeout("response lost", request=request)
+
+ mock_sheets_transport(handler)
+
+ with pytest.raises(google_sheets_service.GoogleSheetsAPIError):
+ await google_sheets_service.values_append(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ range_="Sheet1!A1",
+ values=[["a"]],
+ )
+ assert calls["n"] == 1
+
+ @pytest.mark.asyncio
+ async def test_values_append_terminal_transport_error_becomes_api_error(
+ self, monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ async def fake_sleep(delay: float) -> None:
+ return None
+
+ monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("connection refused", request=request)
+
+ mock_sheets_transport(handler)
+
+ with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc:
+ await google_sheets_service.values_append(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ range_="Sheet1!A1",
+ values=[["a"]],
+ )
+ assert exc.value.status == 503
+ assert exc.value.code == "upstream_unavailable"
+
+ @pytest.mark.asyncio
+ async def test_values_append_gives_up_after_max_attempts(
+ self, monkeypatch: pytest.MonkeyPatch, mock_sheets_transport: TransportInstaller
+ ) -> None:
+ async def fake_sleep(delay: float) -> None:
+ return None
+
+ monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(503, json={"error": {"message": "upstream down"}})
+
+ mock_sheets_transport(handler)
+
+ with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc:
+ await google_sheets_service.values_append(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ range_="Sheet1!A1",
+ values=[["a"]],
+ )
+ assert exc.value.status == 503
+
+
+class TestRuntime:
+ @pytest.mark.asyncio
+ async def test_values_get_returns_payload(self, mock_sheets_transport: TransportInstaller) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert "1abc_xyz_1234567890ABCDEF" in request.url.path
+ return httpx.Response(200, json={"sheets": [{"properties": {"title": "t"}, "data": [{"rowData": []}]}]})
+
+ mock_sheets_transport(handler)
+ payload = await google_sheets_service.values_get(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ ranges="A1:B2",
+ fields="sheets(properties(title))",
+ )
+ assert payload["sheets"][0]["properties"]["title"] == "t"
+
+ @pytest.mark.asyncio
+ async def test_values_append_posts_to_append_endpoint(self, mock_sheets_transport: TransportInstaller) -> None:
+ captured: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["path"] = request.url.path
+ captured["params"] = dict(request.url.params)
+ return httpx.Response(200, json={"updates": {"updatedRows": 1}})
+
+ mock_sheets_transport(handler)
+ payload = await google_sheets_service.values_append(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ range_="Sheet1!A1",
+ values=[["a", "b"]],
+ )
+ assert payload["updates"]["updatedRows"] == 1
+ assert captured["path"].endswith(":append")
+ assert captured["params"]["valueInputOption"] == "USER_ENTERED"
+
+ @pytest.mark.asyncio
+ async def test_batch_update_sends_requests(self, mock_sheets_transport: TransportInstaller) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path.endswith(":batchUpdate")
+ return httpx.Response(200, json={"replies": [{"addSheet": {"properties": {"sheetId": 7, "title": "new"}}}]})
+
+ mock_sheets_transport(handler)
+ payload = await google_sheets_service.batch_update(
+ access_token="tok",
+ spreadsheet_id="1abc_xyz_1234567890ABCDEF",
+ requests=[{"addSheet": {"properties": {"title": "new"}}}],
+ )
+ assert payload["replies"][0]["addSheet"]["properties"]["sheetId"] == 7
+
+ @pytest.mark.asyncio
+ async def test_get_sheet_id_by_title_matches(self, mock_sheets_transport: TransportInstaller) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "sheets": [
+ {"properties": {"sheetId": 1, "title": "A"}},
+ {"properties": {"sheetId": 42, "title": "Leads"}},
+ ]
+ },
+ )
+
+ mock_sheets_transport(handler)
+ sheet_id = await google_sheets_service.get_sheet_id_by_title(
+ access_token="tok", spreadsheet_id="1abc_xyz_1234567890ABCDEF", sheet_title="Leads"
+ )
+ assert sheet_id == 42
+
+
+class TestSchemaHelpers:
+ def test_build_append_dimension_request_validates_inputs(self) -> None:
+ from skyvern.schemas.google_sheets import build_append_dimension_request
+
+ req = build_append_dimension_request(sheet_id=42, dimension="COLUMNS", length=5)
+ assert req == {"appendDimension": {"sheetId": 42, "dimension": "COLUMNS", "length": 5}}
+
+ with pytest.raises(ValueError):
+ build_append_dimension_request(sheet_id=42, dimension="DIAGONAL", length=1)
+ with pytest.raises(ValueError):
+ build_append_dimension_request(sheet_id=42, dimension="ROWS", length=0)
diff --git a/tests/unit/google/test_sheets.py b/tests/unit/google/test_sheets.py
deleted file mode 100644
index d4229603f..000000000
--- a/tests/unit/google/test_sheets.py
+++ /dev/null
@@ -1,318 +0,0 @@
-"""Tests for skyvern.forge.sdk.services.google_sheets_service.
-
-Uses httpx.MockTransport to fake the Drive v3 + Sheets v4 endpoints so we can
-verify parameter encoding, id extraction, response parsing, and error mapping
-(including the 403 insufficient_scope -> reconnect_required translation) end
-to end without hitting Google.
-"""
-
-from typing import Any, Callable
-from unittest.mock import patch
-
-import httpx
-import pytest
-
-from skyvern.forge.sdk.services import google_sheets_service
-
-
-def _install_transport(
- monkeypatch: pytest.MonkeyPatch,
- handler: Callable[[httpx.Request], httpx.Response],
-) -> None:
- transport = httpx.MockTransport(handler)
- real_client = httpx.AsyncClient
-
- def fake_async_client(*args: Any, **kwargs: Any) -> httpx.AsyncClient:
- kwargs["transport"] = transport
- return real_client(*args, **kwargs)
-
- monkeypatch.setattr(google_sheets_service.httpx, "AsyncClient", fake_async_client)
-
-
-def test_extract_spreadsheet_id_from_url() -> None:
- url = "https://docs.google.com/spreadsheets/d/1AbC-XyZ_123/edit#gid=0"
- assert google_sheets_service.extract_spreadsheet_id(url) == "1AbC-XyZ_123"
-
-
-def test_extract_spreadsheet_id_bare() -> None:
- bare = "1AbCdEfGhIjKlMnOpQrSt_12345"
- assert google_sheets_service.extract_spreadsheet_id(bare) == bare
-
-
-def test_extract_spreadsheet_id_invalid() -> None:
- with pytest.raises(ValueError):
- google_sheets_service.extract_spreadsheet_id("")
- with pytest.raises(ValueError):
- google_sheets_service.extract_spreadsheet_id("not-a-sheet")
-
-
-def test_build_drive_q_escapes_user_input() -> None:
- q = google_sheets_service._build_drive_q("Jen's sheet")
- assert "Jen\\'s sheet" in q
- assert "mimeType = 'application/vnd.google-apps.spreadsheet'" in q
- assert "trashed = false" in q
-
-
-async def test_list_spreadsheets_sends_expected_params(monkeypatch: pytest.MonkeyPatch) -> None:
- captured: dict[str, Any] = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["url"] = str(request.url)
- captured["auth"] = request.headers.get("Authorization")
- return httpx.Response(
- 200,
- json={
- "nextPageToken": "tok-2",
- "files": [
- {
- "id": "1xyz",
- "name": "Leads",
- "modifiedTime": "2026-04-10T00:00:00Z",
- "webViewLink": "https://docs.google.com/spreadsheets/d/1xyz",
- },
- {"id": "", "name": "skip-empty-id"},
- ],
- },
- )
-
- _install_transport(monkeypatch, handler)
-
- paged = await google_sheets_service.list_spreadsheets(
- access_token="at-1",
- query="leads",
- page_token="tok-1",
- page_size=50,
- )
-
- assert paged.next_page_token == "tok-2"
- assert len(paged.spreadsheets) == 1
- assert paged.spreadsheets[0].id == "1xyz"
- assert paged.spreadsheets[0].name == "Leads"
- assert captured["auth"] == "Bearer at-1"
- assert "pageSize=50" in captured["url"]
- assert "pageToken=tok-1" in captured["url"]
- # Shared-drive support is required so picker results include sheets
- # owned by shared drives, not just the user's My Drive.
- assert "supportsAllDrives=true" in captured["url"]
- assert "includeItemsFromAllDrives=true" in captured["url"]
-
-
-async def test_list_spreadsheets_403_insufficient_scope_maps_to_reconnect(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 403,
- json={
- "error": {
- "message": "Request had insufficient authentication scopes.",
- "errors": [{"reason": "insufficientPermissions"}],
- }
- },
- )
-
- _install_transport(monkeypatch, handler)
-
- with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc_info:
- await google_sheets_service.list_spreadsheets(access_token="at")
-
- assert exc_info.value.status == 403
- assert exc_info.value.code == "reconnect_required"
-
-
-async def test_get_spreadsheet_tabs_parses_sheet_metadata(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- assert "/v4/spreadsheets/1xyz" in str(request.url)
- return httpx.Response(
- 200,
- json={
- "sheets": [
- {"properties": {"sheetId": 0, "title": "Sheet1", "index": 0}},
- {"properties": {"sheetId": 123, "title": "Q2", "index": 1}},
- {"properties": {"title": "no-id-skip"}},
- ]
- },
- )
-
- _install_transport(monkeypatch, handler)
-
- tabs = await google_sheets_service.get_spreadsheet_tabs(
- access_token="at",
- spreadsheet_id="https://docs.google.com/spreadsheets/d/1xyz/edit",
- )
-
- assert [t.title for t in tabs] == ["Sheet1", "Q2"]
- assert [t.sheet_id for t in tabs] == [0, 123]
-
-
-async def test_create_spreadsheet_posts_title(monkeypatch: pytest.MonkeyPatch) -> None:
- captured: dict[str, Any] = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["body"] = request.content.decode()
- return httpx.Response(
- 200,
- json={
- "spreadsheetId": "1newid",
- "properties": {"title": "My Sheet"},
- "spreadsheetUrl": "https://docs.google.com/spreadsheets/d/1newid",
- "sheets": [{"properties": {"sheetId": 0, "title": "Sheet1", "index": 0}}],
- },
- )
-
- _install_transport(monkeypatch, handler)
-
- created = await google_sheets_service.create_spreadsheet(access_token="at", title="My Sheet")
-
- assert created.id == "1newid"
- assert created.title == "My Sheet"
- assert created.web_view_link and "1newid" in created.web_view_link
- assert created.first_sheet_name == "Sheet1"
- assert '"My Sheet"' in captured["body"]
-
-
-async def test_create_sheet_tab_returns_new_tab(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- assert ":batchUpdate" in str(request.url)
- return httpx.Response(
- 200,
- json={"replies": [{"addSheet": {"properties": {"sheetId": 55, "title": "New Tab", "index": 3}}}]},
- )
-
- _install_transport(monkeypatch, handler)
-
- tab = await google_sheets_service.create_sheet_tab(
- access_token="at",
- spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
- title="New Tab",
- )
-
- assert tab.sheet_id == 55
- assert tab.title == "New Tab"
- assert tab.index == 3
-
-
-async def test_api_error_maps_status_and_message(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 404,
- json={"error": {"message": "Requested entity was not found.", "errors": [{"reason": "notFound"}]}},
- )
-
- _install_transport(monkeypatch, handler)
-
- with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc_info:
- await google_sheets_service.get_spreadsheet_tabs(
- access_token="at", spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345"
- )
-
- assert exc_info.value.status == 404
- assert "not found" in exc_info.value.message.lower()
-
-
-async def test_get_sheet_grid_properties_returns_dimensions(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "sheets": [
- {
- "properties": {
- "sheetId": 0,
- "title": "Other",
- "gridProperties": {"columnCount": 50, "rowCount": 1000},
- }
- },
- {
- "properties": {
- "sheetId": 42,
- "title": "Target",
- "gridProperties": {"columnCount": 26, "rowCount": 1000},
- }
- },
- ]
- },
- )
-
- _install_transport(monkeypatch, handler)
-
- grid = await google_sheets_service.get_sheet_grid_properties(
- access_token="at",
- spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
- sheet_title="Target",
- )
-
- assert grid is not None
- assert grid.sheet_id == 42
- assert grid.title == "Target"
- assert grid.column_count == 26
- assert grid.row_count == 1000
-
-
-async def test_get_sheet_grid_properties_by_id_matches_numeric_id(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "sheets": [
- {
- "properties": {
- "sheetId": 7,
- "title": "Target",
- "gridProperties": {"columnCount": 26, "rowCount": 1000},
- }
- }
- ]
- },
- )
-
- _install_transport(monkeypatch, handler)
-
- grid = await google_sheets_service.get_sheet_grid_properties_by_id(
- access_token="at",
- spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
- sheet_id=7,
- )
-
- assert grid is not None
- assert grid.sheet_id == 7
- assert grid.title == "Target"
- assert grid.column_count == 26
-
-
-async def test_get_sheet_grid_properties_returns_none_when_missing(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(200, json={"sheets": []})
-
- _install_transport(monkeypatch, handler)
-
- grid = await google_sheets_service.get_sheet_grid_properties(
- access_token="at",
- spreadsheet_id="1AbCdEfGhIjKlMnOpQrSt_12345",
- sheet_title="Missing",
- )
-
- assert grid is None
-
-
-def test_build_append_dimension_request_validates_inputs() -> None:
- from skyvern.schemas.google_sheets import build_append_dimension_request
-
- req = build_append_dimension_request(sheet_id=42, dimension="COLUMNS", length=5)
- assert req == {"appendDimension": {"sheetId": 42, "dimension": "COLUMNS", "length": 5}}
-
- with pytest.raises(ValueError):
- build_append_dimension_request(sheet_id=42, dimension="DIAGONAL", length=1)
- with pytest.raises(ValueError):
- build_append_dimension_request(sheet_id=42, dimension="ROWS", length=0)
-
-
-# Ensure patch is not flagged as unused by linters in case of future use
-_ = patch
diff --git a/tests/unit/google/test_sheets_headers.py b/tests/unit/google/test_sheets_headers.py
deleted file mode 100644
index 4202b329d..000000000
--- a/tests/unit/google/test_sheets_headers.py
+++ /dev/null
@@ -1,161 +0,0 @@
-"""Tests for skyvern.forge.sdk.services.google_sheets_service.get_sheet_headers and the
-GET /spreadsheets/{id}/sheets/{title}/headers route.
-
-Follows the house pattern: httpx.MockTransport installed via monkeypatch.
-"""
-
-from typing import Any, Callable
-
-import httpx
-import pytest
-
-from skyvern.forge.sdk.services import google_sheets_service
-
-
-def _install_transport(
- monkeypatch: pytest.MonkeyPatch,
- handler: Callable[[httpx.Request], httpx.Response],
-) -> None:
- transport = httpx.MockTransport(handler)
- real_client = httpx.AsyncClient
-
- def fake_async_client(*args: Any, **kwargs: Any) -> httpx.AsyncClient:
- kwargs["transport"] = transport
- return real_client(*args, **kwargs)
-
- monkeypatch.setattr(google_sheets_service.httpx, "AsyncClient", fake_async_client)
-
-
-async def test_get_sheet_headers_returns_row_one_keyed_by_letter(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- assert "/v4/spreadsheets/1abcdefghijklmnopqrst_12345/values/%27Sheet1%27%21A1%3AZZZ1" in str(request.url)
- return httpx.Response(
- 200,
- json={"range": "Sheet1!A1:ZZZ1", "values": [["Name", "Email", "Date"]]},
- )
-
- _install_transport(monkeypatch, handler)
-
- headers = await google_sheets_service.get_sheet_headers(
- access_token="tok",
- spreadsheet_id="1abcdefghijklmnopqrst_12345",
- sheet_title="Sheet1",
- )
-
- assert headers == [
- google_sheets_service.SheetHeader(letter="A", name="Name"),
- google_sheets_service.SheetHeader(letter="B", name="Email"),
- google_sheets_service.SheetHeader(letter="C", name="Date"),
- ]
-
-
-async def test_get_sheet_headers_returns_empty_when_no_values(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(200, json={"range": "Tab!A1:ZZZ1"})
-
- _install_transport(monkeypatch, handler)
-
- headers = await google_sheets_service.get_sheet_headers(
- access_token="tok",
- spreadsheet_id="1abcdefghijklmnopqrst_12345",
- sheet_title="Tab",
- )
-
- assert headers == []
-
-
-async def test_get_sheet_headers_skips_blank_header_cells(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(200, json={"values": [["Name", "", "Date"]]})
-
- _install_transport(monkeypatch, handler)
-
- headers = await google_sheets_service.get_sheet_headers(
- access_token="tok",
- spreadsheet_id="1abcdefghijklmnopqrst_12345",
- sheet_title="S",
- )
-
- assert headers == [
- google_sheets_service.SheetHeader(letter="A", name="Name"),
- google_sheets_service.SheetHeader(letter="C", name="Date"),
- ]
-
-
-async def test_get_sheet_headers_translates_403_insufficient_scope(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 403,
- json={
- "error": {
- "message": "Request had insufficient authentication scopes.",
- "errors": [{"reason": "insufficientPermissions"}],
- }
- },
- )
-
- _install_transport(monkeypatch, handler)
-
- with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc_info:
- await google_sheets_service.get_sheet_headers(
- access_token="tok",
- spreadsheet_id="1abcdefghijklmnopqrst_12345",
- sheet_title="S",
- )
- assert exc_info.value.status == 403
- assert exc_info.value.code == "reconnect_required"
-
-
-async def test_get_sheet_headers_quotes_titles_with_spaces(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- captured: dict[str, str] = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["url"] = str(request.url)
- return httpx.Response(200, json={"values": [["Name"]]})
-
- _install_transport(monkeypatch, handler)
-
- await google_sheets_service.get_sheet_headers(
- access_token="tok",
- spreadsheet_id="1abcdefghijklmnopqrst_12345",
- sheet_title="Q1 Leads",
- )
- # Quoted 'Q1 Leads' URL-encodes to %27Q1%20Leads%27 (or %27Q1+Leads%27) + !A1:ZZZ1
- assert "%27Q1" in captured["url"] and "Leads%27%21A1%3AZZZ1" in captured["url"]
-
-
-async def test_get_sheet_headers_generates_letters_beyond_Z(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Sanity-check the column-index-to-letter conversion wraps past Z."""
- row = ["h" + str(i) for i in range(28)] # AA and AB columns
- expected_letters = [chr(ord("A") + i) for i in range(26)] + ["AA", "AB"]
-
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(200, json={"values": [row]})
-
- _install_transport(monkeypatch, handler)
-
- headers = await google_sheets_service.get_sheet_headers(
- access_token="tok",
- spreadsheet_id="1abcdefghijklmnopqrst_12345",
- sheet_title="S",
- )
-
- assert [h.letter for h in headers] == expected_letters
diff --git a/tests/unit/google/test_sheets_retry.py b/tests/unit/google/test_sheets_retry.py
deleted file mode 100644
index c87bd8e9e..000000000
--- a/tests/unit/google/test_sheets_retry.py
+++ /dev/null
@@ -1,228 +0,0 @@
-"""Verify the Sheets client retries 429 + 5xx with exponential backoff.
-
-Uses httpx.MockTransport to emit a 429 with Retry-After, then a 200. The
-helper must honor Retry-After, backoff, and eventually succeed.
-"""
-
-from datetime import datetime, timezone
-from typing import Any, Callable
-
-import httpx
-import pytest
-
-from skyvern.forge.sdk.services import google_sheets_service
-
-
-def _install_transport(monkeypatch: pytest.MonkeyPatch, handler: Callable[[httpx.Request], httpx.Response]) -> None:
- transport = httpx.MockTransport(handler)
- real_client = httpx.AsyncClient
-
- def fake_async_client(*args: Any, **kwargs: Any) -> httpx.AsyncClient:
- kwargs["transport"] = transport
- return real_client(*args, **kwargs)
-
- monkeypatch.setattr(google_sheets_service.httpx, "AsyncClient", fake_async_client)
-
-
-async def test_values_append_does_not_retry_on_429(monkeypatch: pytest.MonkeyPatch) -> None:
- """POST mutations must not retry on 429 either: Google does not guarantee
- the quota check rejected the request before the write landed."""
- calls = {"n": 0}
- sleeps: list[float] = []
-
- async def fake_sleep(delay: float) -> None:
- sleeps.append(delay)
-
- monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
-
- def handler(request: httpx.Request) -> httpx.Response:
- calls["n"] += 1
- return httpx.Response(429, headers={"Retry-After": "2"}, json={"error": {"message": "rate limit"}})
-
- _install_transport(monkeypatch, handler)
-
- with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc:
- await google_sheets_service.values_append(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- range_="Sheet1!A1",
- values=[["a"]],
- )
- assert exc.value.status == 429
- assert calls["n"] == 1
- assert sleeps == []
-
-
-async def test_values_get_retries_on_429(monkeypatch: pytest.MonkeyPatch) -> None:
- """GET is idempotent so 429 still retries with Retry-After backoff."""
- calls = {"n": 0}
- sleeps: list[float] = []
-
- async def fake_sleep(delay: float) -> None:
- sleeps.append(delay)
-
- monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
-
- def handler(request: httpx.Request) -> httpx.Response:
- calls["n"] += 1
- if calls["n"] == 1:
- return httpx.Response(429, headers={"Retry-After": "2"}, json={"error": {"message": "rate limit"}})
- return httpx.Response(200, json={"values": [["a"]]})
-
- _install_transport(monkeypatch, handler)
-
- payload = await google_sheets_service.values_get(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- ranges="Sheet1!A1",
- )
- assert payload == {"values": [["a"]]}
- assert calls["n"] == 2
- assert sleeps == [2.0]
-
-
-async def test_values_get_honors_http_date_retry_after(monkeypatch: pytest.MonkeyPatch) -> None:
- """RFC 7231 allows Retry-After as an HTTP-date; we must sleep until that instant
- instead of falling through to exponential backoff."""
- calls = {"n": 0}
- sleeps: list[float] = []
-
- async def fake_sleep(delay: float) -> None:
- sleeps.append(delay)
-
- monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
-
- frozen_now = datetime(2026, 4, 21, 12, 0, 0, tzinfo=timezone.utc)
-
- class _FrozenDatetime(datetime):
- @classmethod
- def now(cls, tz: Any = None) -> datetime:
- return frozen_now if tz is None else frozen_now.astimezone(tz)
-
- monkeypatch.setattr(google_sheets_service, "datetime", _FrozenDatetime)
-
- def handler(request: httpx.Request) -> httpx.Response:
- calls["n"] += 1
- if calls["n"] == 1:
- return httpx.Response(
- 429,
- headers={"Retry-After": "Tue, 21 Apr 2026 12:00:05 GMT"},
- json={"error": {"message": "rate limit"}},
- )
- return httpx.Response(200, json={"values": [["a"]]})
-
- _install_transport(monkeypatch, handler)
-
- payload = await google_sheets_service.values_get(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- ranges="Sheet1!A1",
- )
- assert payload == {"values": [["a"]]}
- assert calls["n"] == 2
- assert sleeps == [5.0]
-
-
-async def test_values_get_retries_on_transport_error(monkeypatch: pytest.MonkeyPatch) -> None:
- """GET is idempotent so transient transport failures retry with backoff."""
- calls = {"n": 0}
- sleeps: list[float] = []
-
- async def fake_sleep(delay: float) -> None:
- sleeps.append(delay)
-
- monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
-
- def handler(request: httpx.Request) -> httpx.Response:
- calls["n"] += 1
- if calls["n"] == 1:
- raise httpx.ConnectError("connection refused", request=request)
- return httpx.Response(200, json={"sheets": []})
-
- _install_transport(monkeypatch, handler)
-
- payload = await google_sheets_service.values_get(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- ranges="Sheet1!A1",
- )
- assert payload == {"sheets": []}
- assert calls["n"] == 2
- assert sleeps == [1.0]
-
-
-async def test_values_append_does_not_replay_post_on_transport_error(monkeypatch: pytest.MonkeyPatch) -> None:
- """POST mutations must not replay on transport failures: Google may have
- processed the write before the response was lost, and a retry would
- duplicate rows."""
- calls = {"n": 0}
-
- async def fake_sleep(delay: float) -> None:
- return None
-
- monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
-
- def handler(request: httpx.Request) -> httpx.Response:
- calls["n"] += 1
- raise httpx.ReadTimeout("response lost", request=request)
-
- _install_transport(monkeypatch, handler)
-
- with pytest.raises(google_sheets_service.GoogleSheetsAPIError):
- await google_sheets_service.values_append(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- range_="Sheet1!A1",
- values=[["a"]],
- )
- assert calls["n"] == 1 # one attempt, no retry
-
-
-async def test_values_append_terminal_transport_error_becomes_api_error(monkeypatch: pytest.MonkeyPatch) -> None:
- async def fake_sleep(delay: float) -> None:
- return None
-
- monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
-
- def handler(request: httpx.Request) -> httpx.Response:
- raise httpx.ConnectError("connection refused", request=request)
-
- _install_transport(monkeypatch, handler)
-
- with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc:
- await google_sheets_service.values_append(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- range_="Sheet1!A1",
- values=[["a"]],
- )
- assert exc.value.status == 503
- assert exc.value.code == "upstream_unavailable"
-
-
-async def test_values_append_gives_up_after_max_attempts(monkeypatch: pytest.MonkeyPatch) -> None:
- async def fake_sleep(delay: float) -> None:
- return None
-
- monkeypatch.setattr(google_sheets_service.asyncio, "sleep", fake_sleep)
-
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(503, json={"error": {"message": "upstream down"}})
-
- _install_transport(monkeypatch, handler)
-
- with pytest.raises(google_sheets_service.GoogleSheetsAPIError) as exc:
- await google_sheets_service.values_append(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- range_="Sheet1!A1",
- values=[["a"]],
- )
- assert exc.value.status == 503
diff --git a/tests/unit/google/test_sheets_runtime.py b/tests/unit/google/test_sheets_runtime.py
deleted file mode 100644
index 243c316c9..000000000
--- a/tests/unit/google/test_sheets_runtime.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Runtime-side Sheets verbs (values.get / append / update, batchUpdate).
-
-These are the methods the workflow runtime calls via app.AGENT_FUNCTION; the
-picker UX already covered in test_sheets.py.
-"""
-
-from typing import Any, Callable
-
-import httpx
-import pytest
-
-from skyvern.forge.sdk.services import google_sheets_service
-
-
-def _install_transport(monkeypatch: pytest.MonkeyPatch, handler: Callable[[httpx.Request], httpx.Response]) -> None:
- transport = httpx.MockTransport(handler)
- real_client = httpx.AsyncClient
-
- def fake_async_client(*args: Any, **kwargs: Any) -> httpx.AsyncClient:
- kwargs["transport"] = transport
- return real_client(*args, **kwargs)
-
- monkeypatch.setattr(google_sheets_service.httpx, "AsyncClient", fake_async_client)
-
-
-async def test_values_get_returns_payload(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- assert "1abc_xyz_1234567890ABCDEF" in request.url.path
- return httpx.Response(200, json={"sheets": [{"properties": {"title": "t"}, "data": [{"rowData": []}]}]})
-
- _install_transport(monkeypatch, handler)
- payload = await google_sheets_service.values_get(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- ranges="A1:B2",
- fields="sheets(properties(title))",
- )
- assert payload["sheets"][0]["properties"]["title"] == "t"
-
-
-async def test_values_append_posts_to_append_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
- captured: dict[str, Any] = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["path"] = request.url.path
- captured["params"] = dict(request.url.params)
- return httpx.Response(200, json={"updates": {"updatedRows": 1}})
-
- _install_transport(monkeypatch, handler)
- payload = await google_sheets_service.values_append(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- range_="Sheet1!A1",
- values=[["a", "b"]],
- )
- assert payload["updates"]["updatedRows"] == 1
- assert captured["path"].endswith(":append")
- assert captured["params"]["valueInputOption"] == "USER_ENTERED"
-
-
-async def test_batch_update_sends_requests(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- assert request.url.path.endswith(":batchUpdate")
- return httpx.Response(200, json={"replies": [{"addSheet": {"properties": {"sheetId": 7, "title": "new"}}}]})
-
- _install_transport(monkeypatch, handler)
- payload = await google_sheets_service.batch_update(
- access_token="tok",
- spreadsheet_id="1abc_xyz_1234567890ABCDEF",
- requests=[{"addSheet": {"properties": {"title": "new"}}}],
- )
- assert payload["replies"][0]["addSheet"]["properties"]["sheetId"] == 7
-
-
-async def test_get_sheet_id_by_title_matches(monkeypatch: pytest.MonkeyPatch) -> None:
- def handler(request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "sheets": [
- {"properties": {"sheetId": 1, "title": "A"}},
- {"properties": {"sheetId": 42, "title": "Leads"}},
- ]
- },
- )
-
- _install_transport(monkeypatch, handler)
- sheet_id = await google_sheets_service.get_sheet_id_by_title(
- access_token="tok", spreadsheet_id="1abc_xyz_1234567890ABCDEF", sheet_title="Leads"
- )
- assert sheet_id == 42
diff --git a/tests/unit/test_extraction_cache.py b/tests/unit/test_extraction_cache.py
index 23b8085f0..6e19cb63c 100644
--- a/tests/unit/test_extraction_cache.py
+++ b/tests/unit/test_extraction_cache.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from collections.abc import Callable
+
import pytest
from skyvern.forge.sdk.cache import extraction_cache
@@ -28,92 +30,132 @@ def _key(**overrides: object) -> str:
return extraction_cache.compute_cache_key(**defaults) # type: ignore[arg-type]
-def test_identical_inputs_produce_identical_key() -> None:
- assert _key() == _key()
-
-
-def test_key_changes_when_element_tree_changes() -> None:
- assert _key() != _key(element_tree="<html><body>different</body></html>")
-
-
-def test_key_changes_when_schema_changes() -> None:
- assert _key() != _key(extracted_information_schema={"type": "object", "properties": {}})
-
-
-def test_key_changes_when_extracted_text_changes() -> None:
- assert _key() != _key(extracted_text="Something else entirely")
-
-
-def test_key_changes_when_url_changes() -> None:
- assert _key() != _key(current_url="https://example.com/other")
-
-
-def test_key_changes_when_error_code_mapping_changes() -> None:
- # RFC review: error_code_mapping is rendered into the prompt,
- # so it must be part of the key.
- assert _key(error_code_mapping={"E1": "oops"}) != _key(error_code_mapping={"E1": "different"})
+def _canonical_element_tree(html: str | None) -> str | None:
+ return extraction_cache._canonical_element_tree(html)
+
+
+def test_cache_key_changes_for_output_affecting_inputs() -> None:
+ cases: tuple[tuple[str, str, str], ...] = (
+ ("element-tree", _key(), _key(element_tree="<html><body>different</body></html>")),
+ ("schema", _key(), _key(extracted_information_schema={"type": "object", "properties": {}})),
+ ("extracted-text", _key(), _key(extracted_text="Something else entirely")),
+ ("url", _key(), _key(current_url="https://example.com/other")),
+ (
+ "error-code-mapping",
+ _key(error_code_mapping={"E1": "oops"}),
+ _key(error_code_mapping={"E1": "different"}),
+ ),
+ (
+ "previous-extracted-information",
+ _key(previous_extracted_information=None),
+ _key(previous_extracted_information={"prior": "value"}),
+ ),
+ ("llm-key", _key(llm_key="gpt-4o"), _key(llm_key="claude-sonnet-4-6")),
+ (
+ "different-extracted-text-dates",
+ _key(extracted_text="Report\n2026-04-10T23:59:59\nEnd"),
+ _key(extracted_text="Report\n2026-04-11T00:00:01\nEnd"),
+ ),
+ ("call-path-handler-script", _key(call_path="handler"), _key(call_path="script")),
+ ("call-path-handler-agent", _key(call_path="handler"), _key(call_path="agent")),
+ ("call-path-script-agent", _key(call_path="script"), _key(call_path="agent")),
+ )
+
+ for case_id, first, second in cases:
+ assert first != second, case_id
+
+
+def test_cache_key_is_stable_for_equivalent_inputs() -> None:
+ schema_a = {"type": "object", "properties": {"a": {"type": "string"}, "b": {"type": "string"}}}
+ schema_b = {"properties": {"b": {"type": "string"}, "a": {"type": "string"}}, "type": "object"}
+ uuid_html_a = '<div id="3f8a9b12-1234-4678-9abc-def012345678">doc</div>'
+ uuid_html_b = '<div id="fedcba98-8765-4321-abcd-123456789abc">doc</div>'
+ csrf_html_a = '<input name="_csrf" value="abc123">'
+ csrf_html_b = '<input name="_csrf" value="zyx987">'
+ extracted_text_a = "Report\n2026-04-10T08:30:15.123456\nEnd"
+ extracted_text_b = "Report\n2026-04-10T23:59:59.999999\nEnd"
+ goal_a = "Extract records updated after\n2026-04-10T08:30:15.123456\nonward"
+ goal_b = "Extract records updated after\n2026-04-10T23:59:59.999999\nonward"
+ cases: tuple[tuple[str, str, str], ...] = (
+ ("identical-inputs", _key(), _key()),
+ ("schema-order", _key(extracted_information_schema=schema_a), _key(extracted_information_schema=schema_b)),
+ (
+ "nonce-url-values",
+ _key(current_url="https://x/y?a=1&_csrf=abc"),
+ _key(current_url="https://x/y?a=1&_csrf=xyz"),
+ ),
+ ("uuid-element-tree", _key(element_tree=uuid_html_a), _key(element_tree=uuid_html_b)),
+ ("csrf-element-tree", _key(element_tree=csrf_html_a), _key(element_tree=csrf_html_b)),
+ (
+ "same-day-extracted-text-timestamps",
+ _key(extracted_text=extracted_text_a),
+ _key(extracted_text=extracted_text_b),
+ ),
+ ("same-day-goal-timestamps", _key(data_extraction_goal=goal_a), _key(data_extraction_goal=goal_b)),
+ )
+
+ for case_id, first, second in cases:
+ assert first == second, case_id
-def test_key_changes_when_previous_extracted_information_changes() -> None:
- # RFC review: previous_extracted_information is rendered into the prompt as
- # prior context. In a loop where each iteration is a fresh task so
- # this is None on step 1 — the cross-iteration cache hits still land —
- # but if an intra-task second-step extraction happens, the key must change.
- assert _key(previous_extracted_information=None) != _key(previous_extracted_information={"prior": "value"})
+def test_compute_cache_key_rejects_legacy_local_datetime_kwarg() -> None:
+ with pytest.raises(TypeError):
+ extraction_cache.compute_cache_key(call_path="test", local_datetime="2026-04-10T00:00:00") # type: ignore[call-arg]
-def test_key_changes_when_llm_key_changes() -> None:
- # RFC review: include llm_key so swapping models forces a fresh extraction
- # once this cache is backed by an off-process store.
- assert _key(llm_key="gpt-4o") != _key(llm_key="claude-sonnet-4-6")
+def test_none_and_empty_string_produce_different_keys() -> None:
+ cases: tuple[tuple[str, dict[str, object], dict[str, object]], ...] = (
+ ("extracted-text", {"extracted_text": None}, {"extracted_text": ""}),
+ ("current-url", {"current_url": None}, {"current_url": ""}),
+ ("data-extraction-goal", {"data_extraction_goal": None}, {"data_extraction_goal": ""}),
+ )
+ for case_id, none_override, empty_override in cases:
+ assert _key(**none_override) != _key(**empty_override), case_id
-def test_key_is_stable_across_equivalent_schema_dict_orderings() -> None:
- schema_a = {"type": "object", "properties": {"a": {"type": "string"}, "b": {"type": "string"}}}
- schema_b = {"properties": {"b": {"type": "string"}, "a": {"type": "string"}}, "type": "object"}
- assert _key(extracted_information_schema=schema_a) == _key(extracted_information_schema=schema_b)
+def test_lookup_miss_matrix() -> None:
+ key = _key()
-def test_lookup_returns_miss_on_empty_cache() -> None:
- result = extraction_cache.lookup("wfr_1", _key())
- assert result.hit is False
- assert result.value is None
- assert result.age_seconds is None
- assert result.fallback_reason == extraction_cache.FALLBACK_FIRST_CALL_IN_RUN
- assert result.scope == extraction_cache.SCOPE_RUN
+ first_call = extraction_cache.lookup("wfr_1", key)
+ assert first_call.hit is False
+ assert first_call.value is None
+ assert first_call.age_seconds is None
+ assert first_call.fallback_reason == extraction_cache.FALLBACK_FIRST_CALL_IN_RUN
+ assert first_call.scope == extraction_cache.SCOPE_RUN
+ extraction_cache.store("wfr_1", _key(current_url="https://example.com/A"), {"a": 1})
+ missing_key = extraction_cache.lookup("wfr_1", _key(current_url="https://example.com/B"))
+ assert missing_key.hit is False
+ assert missing_key.value is None
+ assert missing_key.fallback_reason == extraction_cache.FALLBACK_KEY_NOT_FOUND
+
+ isolated_run = extraction_cache.lookup("wfr_2", _key(current_url="https://example.com/A"))
+ assert isolated_run.hit is False
+ assert isolated_run.fallback_reason == extraction_cache.FALLBACK_FIRST_CALL_IN_RUN
+
+
+ ("value", "key_suffix"),
+ (
+ pytest.param({"docs": ["a.pdf"]}, "dict", id="dict-result"),
+ pytest.param([{"doc": "a.pdf"}, {"doc": "b.pdf"}], "list", id="list-result"),
+ pytest.param("plain text extraction", "string", id="string-result"),
+ ),
+)
+def test_store_then_lookup_returns_hit_with_supported_result_shapes(value: object, key_suffix: str) -> None:
+ key = _key(current_url=f"https://example.com/{key_suffix}")
+ extraction_cache.store("wfr_1", key, value)
-def test_store_then_lookup_returns_hit_with_age() -> None:
- key = _key()
- extraction_cache.store("wfr_1", key, {"docs": ["a.pdf"]})
result = extraction_cache.lookup("wfr_1", key)
assert result.hit is True
- assert result.value == {"docs": ["a.pdf"]}
+ assert result.value == value
assert result.age_seconds is not None
assert result.age_seconds >= 0.0
assert result.fallback_reason is None
assert result.scope == extraction_cache.SCOPE_RUN
-def test_lookup_returns_key_not_found_when_run_exists_but_key_does_not() -> None:
- """A run with other entries but missing this key must report key_not_found,
- not first_call_in_run — downstream metrics use this split to distinguish
- unavoidable first-call misses from potential normalization opportunities."""
- extraction_cache.store("wfr_1", _key(current_url="https://example.com/A"), {"a": 1})
- result = extraction_cache.lookup("wfr_1", _key(current_url="https://example.com/B"))
- assert result.hit is False
- assert result.value is None
- assert result.fallback_reason == extraction_cache.FALLBACK_KEY_NOT_FOUND
-
-
-def test_cache_is_isolated_per_workflow_run_id() -> None:
- key = _key()
- extraction_cache.store("wfr_1", key, {"docs": ["a.pdf"]})
- result = extraction_cache.lookup("wfr_2", key)
- assert result.hit is False
- assert result.fallback_reason == extraction_cache.FALLBACK_FIRST_CALL_IN_RUN
-
-
def test_empty_workflow_run_id_bypasses_cache() -> None:
key = _key()
extraction_cache.store(None, key, {"docs": ["a.pdf"]})
@@ -128,7 +170,6 @@ def test_clear_workflow_run_drops_entries() -> None:
def test_fifo_eviction_when_run_cache_is_full() -> None:
- # Insert MAX + 1 distinct entries; the oldest should be evicted.
max_entries = extraction_cache._MAX_ENTRIES_PER_RUN
first_key = _key(current_url="https://example.com/0")
extraction_cache.store("wfr_1", first_key, {"i": 0})
@@ -143,26 +184,7 @@ def test_fifo_eviction_when_run_cache_is_full() -> None:
assert last_result.value == {"i": max_entries}
-def test_store_and_lookup_list_result() -> None:
- """Extraction schemas with array roots produce list results — these must be cached too."""
- key = _key()
- extraction_cache.store("wfr_1", key, [{"doc": "a.pdf"}, {"doc": "b.pdf"}])
- result = extraction_cache.lookup("wfr_1", key)
- assert result.hit is True
- assert result.value == [{"doc": "a.pdf"}, {"doc": "b.pdf"}]
-
-
-def test_store_and_lookup_string_result() -> None:
- """Some extractions return a plain string — these must be cached too."""
- key = _key()
- extraction_cache.store("wfr_1", key, "plain text extraction")
- result = extraction_cache.lookup("wfr_1", key)
- assert result.hit is True
- assert result.value == "plain text extraction"
-
-
def test_lookup_age_seconds_is_monotonic_delta(monkeypatch: pytest.MonkeyPatch) -> None:
- """age_seconds should reflect elapsed time between store() and lookup()."""
fake_now = [1_000.0]
def _fake_monotonic() -> float:
@@ -179,8 +201,7 @@ def test_lookup_age_seconds_is_monotonic_delta(monkeypatch: pytest.MonkeyPatch)
assert result.age_seconds == pytest.approx(12.5)
-def test_invalidate_key_drops_single_entry() -> None:
- """Per-key eviction leaves sibling entries intact. Used by the retry self-heal path."""
+def test_invalidate_key_matrix() -> None:
key_a = _key()
key_b = _key(current_url="https://example.com/other")
extraction_cache.store("wfr_1", key_a, {"v": "a"})
@@ -189,459 +210,283 @@ def test_invalidate_key_drops_single_entry() -> None:
removed = extraction_cache.invalidate_key("wfr_1", key_a)
assert removed is True
assert extraction_cache.lookup("wfr_1", key_a).hit is False
- # Sibling entry must survive — invalidate is per-key, not per-run.
hit_b = extraction_cache.lookup("wfr_1", key_b)
assert hit_b.hit is True
assert hit_b.value == {"v": "b"}
-
-def test_invalidate_key_returns_false_for_unknown_key() -> None:
- extraction_cache.store("wfr_1", _key(), {"v": "a"})
assert extraction_cache.invalidate_key("wfr_1", "nonexistent-key") is False
-
-
-def test_invalidate_key_returns_false_for_unknown_workflow_run() -> None:
assert extraction_cache.invalidate_key("wfr_missing", _key()) is False
-
-
-def test_invalidate_key_returns_false_for_empty_workflow_run_id() -> None:
- """Falsy workflow_run_id is a no-op, matching the store/lookup contract."""
assert extraction_cache.invalidate_key(None, _key()) is False
assert extraction_cache.invalidate_key("", _key()) is False
-def test_compute_cache_key_rejects_legacy_local_datetime_kwarg() -> None:
- """``local_datetime`` was dropped from the signature (SKY-8873): content
- hash alone defines cache identity, so callers that still try to pass it
- must fail loudly rather than silently producing a key that happens to be
- stable-for-the-wrong-reason."""
- with pytest.raises(TypeError):
- extraction_cache.compute_cache_key(call_path="test", local_datetime="2026-04-10T00:00:00") # type: ignore[call-arg]
-
-
-def test_none_and_empty_string_produce_different_keys() -> None:
- """None and '' are distinct states and must not collide in the cache key."""
- assert _key(extracted_text=None) != _key(extracted_text="")
- assert _key(current_url=None) != _key(current_url="")
- assert _key(data_extraction_goal=None) != _key(data_extraction_goal="")
-
-
def test_lookup_refreshes_lru_position() -> None:
- """A cache hit should refresh the run's LRU position, preventing eviction."""
max_runs = extraction_cache._MAX_WORKFLOW_RUNS
key = _key()
- # Fill the global cache to capacity: wfr_oldest first, then wfr_1..wfr_(N-1).
extraction_cache.store("wfr_oldest", key, {"v": 0})
for i in range(1, max_runs):
extraction_cache.store(f"wfr_{i}", key, {"v": i})
- # Cache is at capacity. wfr_oldest is the LRU candidate.
- # A lookup() hit should refresh its position to most-recent.
refreshed = extraction_cache.lookup("wfr_oldest", key)
assert refreshed.hit is True
assert refreshed.value == {"v": 0}
- # Adding one more run triggers eviction. Without the LRU refresh,
- # wfr_oldest would be evicted; with it, wfr_1 (now the oldest) goes.
extraction_cache.store("wfr_new", key, {"v": 999})
oldest_after = extraction_cache.lookup("wfr_oldest", key)
assert oldest_after.hit is True
assert oldest_after.value == {"v": 0}
- assert extraction_cache.lookup("wfr_1", key).hit is False # evicted
-
-
-# ---------------------------------------------------------------------------
-# _canonical_url primitive
-# ---------------------------------------------------------------------------
-
-
-class TestCanonicalUrl:
- def test_returns_none_for_none(self) -> None:
- assert extraction_cache._canonical_url(None) is None
-
- def test_returns_empty_for_empty(self) -> None:
- assert extraction_cache._canonical_url("") == ""
-
- def test_leaves_simple_url_unchanged(self) -> None:
- assert extraction_cache._canonical_url("https://example.com/docs") == "https://example.com/docs"
-
- def test_sorts_query_params_by_key(self) -> None:
- assert extraction_cache._canonical_url("https://x/y?b=2&a=1") == "https://x/y?a=1&b=2"
-
- def test_redacts_nonce_param_values_and_preserves_keys(self) -> None:
- """Nonce values are replaced with a sentinel but keys are preserved so
- presence/absence of the param still differentiates cache keys.
- """
- out = extraction_cache._canonical_url("https://x/y?a=1&_csrf=abc&b=2")
- assert "_csrf=__NONCE__" in out
- assert "a=1" in out and "b=2" in out
-
- def test_same_nonce_key_different_values_produce_same_canonical(self) -> None:
- """Two URLs that differ only in a nonce value must hash identically."""
- a = extraction_cache._canonical_url("https://x/y?_csrf=abc")
- b = extraction_cache._canonical_url("https://x/y?_csrf=xyz")
- assert a == b
-
- def test_nonce_key_absent_vs_present_produce_different_canonical(self) -> None:
- """A URL with the nonce key absent must canonicalize differently than one with the key present."""
- with_nonce = extraction_cache._canonical_url("https://x/y?_csrf=abc")
- without = extraction_cache._canonical_url("https://x/y")
- assert with_nonce != without
-
- def test_empty_nonce_value_does_not_collide_with_populated_value(self) -> None:
- """`?_csrf=` (empty) must canonicalize differently than `?_csrf=abc`."""
- empty = extraction_cache._canonical_url("https://x/y?_csrf=")
- populated = extraction_cache._canonical_url("https://x/y?_csrf=abc")
- assert empty != populated
- assert "_csrf=__NONCE__" not in empty
-
- def test_bare_flag_does_not_collide_with_empty_value(self) -> None:
- """`?flag` (no `=`) must canonicalize differently than `?flag=`."""
- bare = extraction_cache._canonical_url("https://x/y?flag")
- empty = extraction_cache._canonical_url("https://x/y?flag=")
- assert bare != empty
- assert bare.endswith("?flag")
- assert empty.endswith("?flag=")
-
- def test_preserves_fragment(self) -> None:
- """SPAs with hash routing encode page identity in the fragment (e.g. `#/orders/123` vs
- `#/orders/456`); stripping the fragment would collapse structurally-different pages."""
- assert extraction_cache._canonical_url("https://x/y?a=1#section") == "https://x/y?a=1#section"
-
- def test_different_fragments_produce_different_canonical(self) -> None:
- """Hash-routed SPA URLs must canonicalize distinctly when the fragment differs."""
- a = extraction_cache._canonical_url("https://x/y#/orders/123")
- b = extraction_cache._canonical_url("https://x/y#/orders/456")
- assert a != b
-
- def test_preserves_duplicate_keys_in_order(self) -> None:
- # Repeated keys can be semantically ordered (first-wins handlers,
- # ordered multi-sort). Python's stable sort preserves insertion order
- # within the same key.
- url = "https://x/y?sort=price&sort=rating"
- assert extraction_cache._canonical_url(url) == "https://x/y?sort=price&sort=rating"
-
- def test_trailing_punctuation_is_not_stripped(self) -> None:
- # _canonical_url operates on pre-parsed URL strings, not on URLs
- # embedded in prose. Callers pass `current_url` directly.
- assert extraction_cache._canonical_url("https://x/y.") == "https://x/y."
-
- def test_malformed_url_returns_input_unchanged(self) -> None:
- # Never raise — cache lookup must degrade gracefully.
- assert extraction_cache._canonical_url("not a url at all") == "not a url at all"
-
- def test_case_insensitive_nonce_match_redacts_value(self) -> None:
- """Uppercase nonce keys are still matched; the value is redacted, the key preserved."""
- out = extraction_cache._canonical_url("https://x/y?CSRF=abc&a=1")
- assert "CSRF=__NONCE__" in out
- assert "a=1" in out
-
-
-# ---------------------------------------------------------------------------
-# _canonical_element_tree primitive
-# ---------------------------------------------------------------------------
-
-
-class TestCanonicalElementTree:
- def test_returns_none_for_none(self) -> None:
- assert extraction_cache._canonical_element_tree(None) is None
-
- def test_returns_empty_for_empty(self) -> None:
- assert extraction_cache._canonical_element_tree("") == ""
-
- def test_scrubs_uuid_in_id_attribute(self) -> None:
- h1 = '<div id="3f8a9b12-1234-4678-9abc-def012345678">x</div>'
- h2 = '<div id="fedcba98-8765-4321-abcd-123456789abc">x</div>'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_random_hex_suffix_in_id_attribute(self) -> None:
- h1 = '<div id="row-abc123def">x</div>'
- h2 = '<div id="row-fedcba987">x</div>'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_data_testid(self) -> None:
- h1 = '<button data-testid="btn-1a2b3c4d">go</button>'
- h2 = '<button data-testid="btn-5e6f7a8b">go</button>'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_leaves_class_and_href_untouched(self) -> None:
- # class and href carry semantic weight — they must differentiate pages.
- h1 = '<a class="btn primary" href="/docs">go</a>'
- h2 = '<a class="btn danger" href="/docs">go</a>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_csrf_input_value(self) -> None:
- h1 = '<input name="_csrf" value="abc123">'
- h2 = '<input name="_csrf" value="zyx987">'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_csrf_meta_content(self) -> None:
- h1 = '<meta name="csrf-token" content="abc123">'
- h2 = '<meta name="csrf-token" content="zyx987">'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_canonical_element_tree_returns_string_for_valid_html(self) -> None:
- # selectolax is permissive enough that we can't reliably force its
- # parser to raise from pytest; the except-path fallback is exercised
- # indirectly by the None/empty-string guards at the top of the function.
- assert extraction_cache._canonical_element_tree("<div>ok</div>") is not None
-
- def test_preserves_text_content(self) -> None:
- out = extraction_cache._canonical_element_tree('<div id="x-abc123def">hello world</div>')
- assert "hello world" in out
-
- def test_different_text_produces_different_output(self) -> None:
- out1 = extraction_cache._canonical_element_tree("<div>alpha</div>")
- out2 = extraction_cache._canonical_element_tree("<div>beta</div>")
- assert out1 != out2
-
- def test_scrubs_csrf_input_case_insensitive(self) -> None:
- """CSRF <input name=...> match must be case-insensitive, matching prior regex behavior."""
- h1 = '<input name="CSRF_TOKEN" value="abc123">'
- h2 = '<input name="CSRF_TOKEN" value="zyx987">'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_csrf_meta_case_insensitive(self) -> None:
- """CSRF <meta name=...> match must be case-insensitive, matching prior regex behavior."""
- h1 = '<meta name="CSRF-TOKEN" content="abc123">'
- h2 = '<meta name="CSRF-TOKEN" content="zyx987">'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_preserves_semantic_input_name_values(self) -> None:
- """<input name=...> values carry field-name semantics (not transient IDs).
- Two forms with different input names must NOT collapse to the same canonical.
- """
- h1 = '<form><input name="company_name" type="text"><button>Go</button></form>'
- h2 = '<form><input name="contact_phone" type="text"><button>Go</button></form>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_preserves_stable_business_ids_in_suspect_attrs(self) -> None:
- """Semantic identifiers without transient patterns must survive canonicalization.
-
- Only UUIDs and random-looking hex suffixes are redacted inside suspect
- attributes; stable business IDs like id='submit-button' must differentiate.
- """
- h1 = '<button id="submit-button">go</button>'
- h2 = '<button id="cancel-button">go</button>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_preserves_numeric_only_suffix_in_suspect_attrs(self) -> None:
- """Purely numeric suffixes (e.g. 'order-123456') are stable business IDs; don't collapse them."""
- h1 = '<div id="order-123456">go</div>'
- h2 = '<div id="order-987654">go</div>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_preserves_hex_letter_only_english_words_in_suspect_attrs(self) -> None:
- """Hex-letter-only strings like 'facade' or 'decade' are English words, not random IDs."""
- h1 = '<div id="zone-facade">go</div>'
- h2 = '<div id="zone-decade">go</div>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_preserves_non_v4_uuid_in_suspect_attrs(self) -> None:
- """v1/v3/v5 UUIDs are deterministic / namespace-based and can be stable business keys."""
- # v1 UUID (version nibble = 1) — must NOT be collapsed
- h1 = '<div id="3f8a9b12-1234-1678-9abc-def012345678">x</div>'
- h2 = '<div id="fedcba98-8765-1321-abcd-123456789abc">x</div>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_attr_case_insensitively(self) -> None:
- """Even if a parser surfaces an uppercase attribute name, it must still match the suspect set."""
- # selectolax 0.3.34 normalizes to lowercase, but we want robustness if that ever changes.
- # Exercise via direct set membership: this test pins the lower() call.
- h1 = '<div ID="3f8a9b12-1234-4678-9abc-def012345678">x</div>'
- h2 = '<div ID="fedcba98-8765-4321-abcd-123456789abc">x</div>'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_preserves_content_inside_frame_tags(self) -> None:
- """Regression for SKY-9524: legacy framed apps place form controls
- inside <frame> tags. HTML5-strict parsers treat <frame> as void and
- drop child content on serialize, collapsing distinct per-record pages
- into the same canonical output. Two pages whose only difference is
- per-record form input values must produce different canonical output.
- """
- h1 = (
- '<frameset><frame name="criteria" src="criteria.aspx">'
- '<input name="txtLastName" value="Lastname1">'
- '<input name="txtFirstName" value="Firstname1">'
- "</frame></frameset>"
- )
- h2 = (
- '<frameset><frame name="criteria" src="criteria.aspx">'
- '<input name="txtLastName" value="Lastname2">'
- '<input name="txtFirstName" value="Firstname2">'
- "</frame></frameset>"
- )
- c1 = extraction_cache._canonical_element_tree(h1)
- c2 = extraction_cache._canonical_element_tree(h2)
- assert c1 != c2
- assert c1 is not None and "Lastname1" in c1
- assert c2 is not None and "Lastname2" in c2
-
- def test_preserves_input_value_attributes(self) -> None:
- """`value=` attributes on form inputs carry per-record data (member IDs,
- patient names) and must always survive canonicalization unchanged.
- """
- h1 = '<input name="memberId" value="200002578">'
- h2 = '<input name="memberId" value="200451314">'
- c1 = extraction_cache._canonical_element_tree(h1)
- c2 = extraction_cache._canonical_element_tree(h2)
- assert c1 != c2
- assert c1 is not None and "200002578" in c1
- assert c2 is not None and "200451314" in c2
-
- def test_preserves_selected_attribute_on_select(self) -> None:
- """<select selected="..."> indicates the active option (e.g. DOB year)
- and must differentiate two records.
- """
- h1 = '<select name="ddlDOBYear" selected="1968"><option>1968</option></select>'
- h2 = '<select name="ddlDOBYear" selected="1957"><option>1957</option></select>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_does_not_corrupt_text_with_angle_brackets(self) -> None:
- """Stray `<` and `>` in text content (e.g. inequality math) must not
- be tokenized as tag fragments by the walker."""
- h = "<p>If x < 5 and y > 0 then z = x + y</p>"
- out = extraction_cache._canonical_element_tree(h)
- assert out is not None
- assert "If x < 5 and y > 0 then z = x + y" in out
-
- def test_scrubs_csrf_with_unquoted_value(self) -> None:
- """Unquoted CSRF token values must still be scrubbed to empty so the
- token doesn't leak into the cache key."""
- h1 = '<input name="_csrf" value=abc123def>'
- h2 = '<input name="_csrf" value=xyz789ghi>'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_preserves_non_redacted_aria_attributes(self) -> None:
- """`aria-controls` / `aria-owns` are NOT in the suspect set — they
- identify component anchors and must differentiate pages.
- """
- h1 = '<button aria-controls="panel-3f8a9b12c4">Toggle</button>'
- h2 = '<button aria-controls="panel-fedcba9876">Toggle</button>'
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_does_not_redact_id_inside_attribute_value(self) -> None:
- """Substring `id='...'` inside another attribute's quoted value must
- NOT be redacted — only attribute-position `id=` is in scope."""
- h1 = "<div onclick=\"fn(id='abc123def')\">click</div>"
- h2 = "<div onclick=\"fn(id='xyz789ghi')\">click</div>"
- assert extraction_cache._canonical_element_tree(h1) != extraction_cache._canonical_element_tree(h2)
-
- def test_url_with_id_query_param_in_src_does_not_collide(self) -> None:
- """`<frame src="page?id=A">` and `<frame src="page?id=B">` must produce
- DIFFERENT canonical output — the id query string is a real
- differentiator and must survive."""
- h1 = '<frame src="page.aspx?id=A&action=show">'
- h2 = '<frame src="page.aspx?id=B&action=show">'
- c1 = extraction_cache._canonical_element_tree(h1)
- c2 = extraction_cache._canonical_element_tree(h2)
- assert c1 != c2
- assert c1 is not None and "id=A" in c1
- assert c2 is not None and "id=B" in c2
-
- def test_preserves_textarea_text_with_angle_brackets(self) -> None:
- """`<textarea>` body is raw-text per HTML spec — its content must pass
- through verbatim, including literal `<` and `>` from user input,
- without being tokenized as tags by the canonicalizer.
- """
- h = "<textarea>if x < 5 and y > 0 then z = x + y</textarea>"
- out = extraction_cache._canonical_element_tree(h)
+ assert extraction_cache.lookup("wfr_1", key).hit is False
+
+
+ "cases",
+ (
+ pytest.param(
+ (
+ (None, None),
+ ("", ""),
+ ),
+ id="empty-inputs",
+ ),
+ pytest.param(
+ (
+ ("https://example.com/docs", "https://example.com/docs"),
+ ("https://x/y.", "https://x/y."),
+ ("not a url at all", "not a url at all"),
+ ),
+ id="simple-urls",
+ ),
+ pytest.param(
+ (
+ ("https://x/y?b=2&a=1", "https://x/y?a=1&b=2"),
+ ("https://x/y?sort=price&sort=rating", "https://x/y?sort=price&sort=rating"),
+ ),
+ id="query-order",
+ ),
+ pytest.param(
+ (
+ ("https://x/y?_csrf=abc", "https://x/y?_csrf=__NONCE__"),
+ ("https://x/y?_csrf=xyz", "https://x/y?_csrf=__NONCE__"),
+ ),
+ id="nonce-value-equivalence",
+ ),
+ pytest.param(
+ (
+ ("https://x/y?_csrf=", "https://x/y?_csrf="),
+ ("https://x/y?_csrf=abc", "https://x/y?_csrf=__NONCE__"),
+ ),
+ id="empty-nonce-value",
+ ),
+ pytest.param(
+ (
+ ("https://x/y?flag", "https://x/y?flag"),
+ ("https://x/y?flag=", "https://x/y?flag="),
+ ),
+ id="bare-vs-empty-flag",
+ ),
+ pytest.param(
+ (
+ ("https://x/y?a=1#section", "https://x/y?a=1#section"),
+ ("https://x/y#/orders/123", "https://x/y#/orders/123"),
+ ("https://x/y#/orders/456", "https://x/y#/orders/456"),
+ ),
+ id="fragments",
+ ),
+ pytest.param(
+ (
+ ("https://x/y?a=1&b=2", "https://x/y?a=1&b=2"),
+ ("https://x/y?b=2&a=1", "https://x/y?a=1&b=2"),
+ ),
+ id="already-canonical-vs-unsorted",
+ ),
+ ),
+)
+def test_canonical_url_normalization_matrix(cases: tuple[tuple[str | None, str | None], ...]) -> None:
+ for raw, expected in cases:
+ assert extraction_cache._canonical_url(raw) == expected
+
+
+def test_canonical_url_redacts_nonce_param_values_and_preserves_keys() -> None:
+ out = extraction_cache._canonical_url("https://x/y?a=1&_csrf=abc&b=2")
+ assert "_csrf=__NONCE__" in out
+ assert "a=1" in out and "b=2" in out
+
+
+def test_canonical_url_case_insensitive_nonce_match_redacts_value() -> None:
+ out = extraction_cache._canonical_url("https://x/y?CSRF=abc&a=1")
+ assert "CSRF=__NONCE__" in out
+ assert "a=1" in out
+
+
+ElementTreeCheck = Callable[[], None]
+
+
+def _same_canonical(h1: str, h2: str) -> ElementTreeCheck:
+ def check() -> None:
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
+
+ return check
+
+
+def _different_canonical(h1: str, h2: str) -> ElementTreeCheck:
+ def check() -> None:
+ assert _canonical_element_tree(h1) != _canonical_element_tree(h2)
+
+ return check
+
+
+def _contains(html: str, *needles: str) -> ElementTreeCheck:
+ def check() -> None:
+ out = _canonical_element_tree(html)
assert out is not None
- assert "if x < 5 and y > 0 then z = x + y" in out
-
- def test_handles_attribute_value_containing_angle_bracket(self) -> None:
- """A `>` inside a quoted attribute value must NOT close the tag —
- the walker is quote-aware so the tag boundary is the outer `>`.
- Suspect-attribute redaction still runs on subsequent attributes.
- """
- h1 = '<input value="a>b" id="x-3f8a9b12c4">'
- h2 = '<input value="a>b" id="x-fedcba9876">'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_csrf_with_apostrophe_in_double_quoted_value(self) -> None:
- """Double-quoted attribute values are allowed to contain `'` per HTML
- spec. The CSRF scrubber must still match and zero the value — two
- tokens that differ only by the apostrophe-bearing payload must hash
- identically after scrubbing.
- """
- h1 = '<input name="_csrf" value="abc\'123">'
- h2 = '<input name="_csrf" value="xyz\'789">'
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_scrubs_csrf_with_double_quote_in_single_quoted_value(self) -> None:
- """Single-quoted attribute values are allowed to contain `"` per HTML
- spec. Symmetric case to the apostrophe test.
- """
- h1 = "<input name='_csrf' value='abc\"123'>"
- h2 = "<input name='_csrf' value='xyz\"789'>"
- assert extraction_cache._canonical_element_tree(h1) == extraction_cache._canonical_element_tree(h2)
-
- def test_handles_unescaped_double_quote_in_attribute_value(self) -> None:
- """Pinned behavior under malformed scraper input (a known scraper bug:
- `build_attribute` does not escape `"`). Must not crash, and two
- distinct malformed inputs must NOT collapse to the same canonical
- (graceful miss-churn is acceptable; cross-record collision is not).
- """
- h1 = '<input value="a"b" id="x-3f8a9b12c4">'
- h2 = '<input value="c"d" id="x-fedcba9876">'
- c1 = extraction_cache._canonical_element_tree(h1)
- c2 = extraction_cache._canonical_element_tree(h2)
- assert c1 is not None and c2 is not None
- assert c1 != c2
-
-
-# ---------------------------------------------------------------------------
-# compute_cache_key — structured-path canonicalization integration
-# ---------------------------------------------------------------------------
-
-
-def test_key_stable_across_nonce_params_in_url() -> None:
- """current_url with different nonce param values should still hit."""
- assert _key(current_url="https://x/y?a=1&_csrf=abc") == _key(current_url="https://x/y?a=1&_csrf=xyz")
-
-
-def test_key_stable_across_uuid_in_element_tree() -> None:
- """element_tree with different UUIDs in id= attributes should still hit."""
- h1 = '<div id="3f8a9b12-1234-4678-9abc-def012345678">doc</div>'
- h2 = '<div id="fedcba98-8765-4321-abcd-123456789abc">doc</div>'
- assert _key(element_tree=h1) == _key(element_tree=h2)
-
-
-def test_key_stable_across_csrf_token_in_element_tree() -> None:
- """element_tree with different CSRF tokens should still hit."""
+ for needle in needles:
+ assert needle in out
+
+ return check
+
+
+def _canonical_is(html: str | None, expected: str | None) -> ElementTreeCheck:
+ def check() -> None:
+ assert _canonical_element_tree(html) == expected
+
+ return check
+
+
+def _canonical_is_not_none(html: str) -> ElementTreeCheck:
+ def check() -> None:
+ assert _canonical_element_tree(html) is not None
+
+ return check
+
+
+ "checks",
+ (
+ pytest.param(
+ (
+ _canonical_is(None, None),
+ _canonical_is("", ""),
+ _same_canonical(
+ '<div id="3f8a9b12-1234-4678-9abc-def012345678">x</div>',
+ '<div id="fedcba98-8765-4321-abcd-123456789abc">x</div>',
+ ),
+ _same_canonical('<div id="row-abc123def">x</div>', '<div id="row-fedcba987">x</div>'),
+ _same_canonical(
+ '<button data-testid="btn-1a2b3c4d">go</button>',
+ '<button data-testid="btn-5e6f7a8b">go</button>',
+ ),
+ _same_canonical(
+ '<div ID="3f8a9b12-1234-4678-9abc-def012345678">x</div>',
+ '<div ID="fedcba98-8765-4321-abcd-123456789abc">x</div>',
+ ),
+ _same_canonical('<input value="a>b" id="x-3f8a9b12c4">', '<input value="a>b" id="x-fedcba9876">'),
+ ),
+ id="transient-identity-redaction",
+ ),
+ pytest.param(
+ (
+ _canonical_is_not_none("<div>ok</div>"),
+ _contains('<div id="x-abc123def">hello world</div>', "hello world"),
+ _different_canonical("<div>alpha</div>", "<div>beta</div>"),
+ _different_canonical(
+ '<a class="btn primary" href="/docs">go</a>', '<a class="btn danger" href="/docs">go</a>'
+ ),
+ _different_canonical(
+ '<form><input name="company_name" type="text"><button>Go</button></form>',
+ '<form><input name="contact_phone" type="text"><button>Go</button></form>',
+ ),
+ _different_canonical(
+ '<button id="submit-button">go</button>', '<button id="cancel-button">go</button>'
+ ),
+ _different_canonical('<div id="order-123456">go</div>', '<div id="order-987654">go</div>'),
+ _different_canonical('<div id="zone-facade">go</div>', '<div id="zone-decade">go</div>'),
+ _different_canonical(
+ '<div id="3f8a9b12-1234-1678-9abc-def012345678">x</div>',
+ '<div id="fedcba98-8765-1321-abcd-123456789abc">x</div>',
+ ),
+ _different_canonical(
+ '<frameset><frame name="criteria" src="criteria.aspx"><input name="txtLastName" value="Lastname1"><input name="txtFirstName" value="Firstname1"></frame></frameset>',
+ '<frameset><frame name="criteria" src="criteria.aspx"><input name="txtLastName" value="Lastname2"><input name="txtFirstName" value="Firstname2"></frame></frameset>',
+ ),
+ _contains(
+ '<frameset><frame name="criteria" src="criteria.aspx"><input name="txtLastName" value="Lastname1"></frame></frameset>',
+ "Lastname1",
+ ),
+ _different_canonical(
+ '<input name="memberId" value="200002578">', '<input name="memberId" value="200451314">'
+ ),
+ _contains('<input name="memberId" value="200002578">', "200002578"),
+ _different_canonical(
+ '<select name="ddlDOBYear" selected="1968"><option>1968</option></select>',
+ '<select name="ddlDOBYear" selected="1957"><option>1957</option></select>',
+ ),
+ _contains("<p>If x < 5 and y > 0 then z = x + y</p>", "If x < 5 and y > 0 then z = x + y"),
+ _different_canonical(
+ '<button aria-controls="panel-3f8a9b12c4">Toggle</button>',
+ '<button aria-controls="panel-fedcba9876">Toggle</button>',
+ ),
+ _different_canonical(
+ "<div onclick=\"fn(id='abc123def')\">click</div>",
+ "<div onclick=\"fn(id='xyz789ghi')\">click</div>",
+ ),
+ _different_canonical(
+ '<frame src="page.aspx?id=A&action=show">', '<frame src="page.aspx?id=B&action=show">'
+ ),
+ _contains('<frame src="page.aspx?id=A&action=show">', "id=A"),
+ _contains(
+ "<textarea>if x < 5 and y > 0 then z = x + y</textarea>", "if x < 5 and y > 0 then z = x + y"
+ ),
+ _canonical_is_not_none('<input value="a"b" id="x-3f8a9b12c4">'),
+ _different_canonical('<input value="a"b" id="x-3f8a9b12c4">', '<input value="c"d" id="x-fedcba9876">'),
+ ),
+ id="semantic-identity-preservation",
+ ),
+ ),
+)
+def test_canonical_element_tree_identity_matrix(checks: tuple[ElementTreeCheck, ...]) -> None:
+ for check in checks:
+ check()
+
+
+def test_canonical_element_tree_scrubs_csrf_input_value() -> None:
h1 = '<input name="_csrf" value="abc123">'
h2 = '<input name="_csrf" value="zyx987">'
- assert _key(element_tree=h1) == _key(element_tree=h2)
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
+
+
+def test_canonical_element_tree_scrubs_csrf_meta_content() -> None:
+ h1 = '<meta name="csrf-token" content="abc123">'
+ h2 = '<meta name="csrf-token" content="zyx987">'
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
+
+
+def test_canonical_element_tree_scrubs_csrf_input_case_insensitive() -> None:
+ h1 = '<input name="CSRF_TOKEN" value="abc123">'
+ h2 = '<input name="CSRF_TOKEN" value="zyx987">'
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
-def test_key_stable_across_iso_timestamps_in_extracted_text() -> None:
- """extracted_text with same-day ISO timestamps should still hit."""
- t1 = "Report\n2026-04-10T08:30:15.123456\nEnd"
- t2 = "Report\n2026-04-10T23:59:59.999999\nEnd"
- assert _key(extracted_text=t1) == _key(extracted_text=t2)
+def test_canonical_element_tree_scrubs_csrf_meta_case_insensitive() -> None:
+ h1 = '<meta name="CSRF-TOKEN" content="abc123">'
+ h2 = '<meta name="CSRF-TOKEN" content="zyx987">'
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
-def test_key_changes_across_different_dates_in_extracted_text() -> None:
- """Midnight crossing in extracted_text must produce a different key."""
- t1 = "Report\n2026-04-10T23:59:59\nEnd"
- t2 = "Report\n2026-04-11T00:00:01\nEnd"
- assert _key(extracted_text=t1) != _key(extracted_text=t2)
+def test_canonical_element_tree_scrubs_csrf_with_unquoted_value() -> None:
+ h1 = '<input name="_csrf" value=abc123def>'
+ h2 = '<input name="_csrf" value=xyz789ghi>'
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
-def test_call_path_discriminator_isolates_otherwise_identical_keys() -> None:
- """Different call_paths must produce different keys even when every other
- input is identical — guards against silent cross-path cache hits (e.g.
- script path replaying an agent-path extraction result)."""
- assert _key(call_path="handler") != _key(call_path="script")
- assert _key(call_path="handler") != _key(call_path="agent")
- assert _key(call_path="script") != _key(call_path="agent")
+def test_canonical_element_tree_scrubs_csrf_with_apostrophe_in_double_quoted_value() -> None:
+ h1 = '<input name="_csrf" value="abc\'123">'
+ h2 = '<input name="_csrf" value="xyz\'789">'
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
-def test_key_stable_across_iso_timestamps_in_data_extraction_goal() -> None:
- """Same-day ISO timestamps in the goal (e.g. 'extract updated after <ts>')
- must not cause per-second key churn."""
- g1 = "Extract records updated after\n2026-04-10T08:30:15.123456\nonward"
- g2 = "Extract records updated after\n2026-04-10T23:59:59.999999\nonward"
- assert _key(data_extraction_goal=g1) == _key(data_extraction_goal=g2)
+def test_canonical_element_tree_scrubs_csrf_with_double_quote_in_single_quoted_value() -> None:
+ h1 = "<input name='_csrf' value='abc\"123'>"
+ h2 = "<input name='_csrf' value='xyz\"789'>"
+ assert _canonical_element_tree(h1) == _canonical_element_tree(h2)
diff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.py
index e9b46064e..2149d288e 100644
--- a/tests/unit/test_failure_classifier.py
+++ b/tests/unit/test_failure_classifier.py
@@ -5,392 +5,212 @@ import pytest
from skyvern.forge.failure_classifier import classify_from_failure_reason
-class TestNoneAndEmptyInput:
- def test_none_input_returns_none(self) -> None:
- assert classify_from_failure_reason(None) is None
-
- def test_empty_string_returns_none(self) -> None:
- assert classify_from_failure_reason("") is None
-
- def test_none_with_none_exception_returns_none(self) -> None:
- assert classify_from_failure_reason(None, exception=None) is None
-
- def test_unrecognized_reason_returns_none(self) -> None:
- assert classify_from_failure_reason("something completely unrelated happened") is None
-
-
-class TestAntiBotDetection:
- @pytest.mark.parametrize(
- "reason",
- [
- "Page blocked by captcha challenge",
- "Cloudflare protection detected",
- "Bot detected on the page",
- "IP blocked by server",
- "Request blocked due to suspicious activity",
- "Access denied by WAF",
- "Anti-bot system triggered",
- "Human verification required",
- "Cloudflare Turnstile still says verify you are human",
- "The current page shows an 'Access Denied' error",
- "Access Denied - website blocked the request",
- ],
- )
- def test_keywords_match(self, reason: str) -> None:
- result = classify_from_failure_reason(reason)
- assert result is not None
- categories = [r["category"] for r in result]
- assert "ANTI_BOT_DETECTION" in categories
-
- def test_access_denied_with_auth_context_is_not_antibot(self) -> None:
- """'Access denied' + auth keywords → AUTH_FAILURE, not ANTI_BOT_DETECTION."""
- result = classify_from_failure_reason("Access denied after login - user does not have permission")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "AUTH_FAILURE" in categories
- assert "ANTI_BOT_DETECTION" not in categories
-
- def test_access_denied_with_password_context_is_not_antibot(self) -> None:
- """'Access denied' when password is mentioned → AUTH_FAILURE."""
- result = classify_from_failure_reason("The page shows 'Access Denied'. Unable to enter your password.")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "AUTH_FAILURE" in categories
- assert "ANTI_BOT_DETECTION" not in categories
-
- def test_broad_blocked_does_not_match(self) -> None:
- """'blocked' alone should NOT trigger ANTI_BOT_DETECTION (narrowed keywords)."""
- result = classify_from_failure_reason("UI element blocked by overlay")
- if result:
- categories = [r["category"] for r in result]
- assert "ANTI_BOT_DETECTION" not in categories
+class NoProxyAvailable(Exception):
+ pass
- def test_broad_forbidden_does_not_match(self) -> None:
- result = classify_from_failure_reason("403 Forbidden from auth endpoint")
- if result:
- categories = [r["category"] for r in result]
- assert "ANTI_BOT_DETECTION" not in categories
+class UnknownErrorWhileCreatingBrowserContext(Exception):
+ pass
-class TestProxyError:
- def test_no_proxy_exception_is_proxy_not_browser(self) -> None:
- """NoProxyAvailable exception should be PROXY_ERROR, not BROWSER_ERROR."""
- class NoProxyAvailable(Exception):
- pass
+class ProxyErrorOccurred(Exception):
+ pass
- result = classify_from_failure_reason(
- "Failed to create browser context for dynamic-browser (NoProxyAvailable). No proxy available",
- exception=NoProxyAvailable(),
- )
- assert result is not None
- assert result[0]["category"] == "PROXY_ERROR"
- categories = [r["category"] for r in result]
- assert "BROWSER_ERROR" not in categories
- def test_unknown_error_creating_browser_context_with_proxy_reason(self) -> None:
- """UnknownErrorWhileCreatingBrowserContext caused by proxy should be PROXY_ERROR."""
+class BrowserCrashError(Exception):
+ pass
+
+
+class CDPConnectionError(Exception):
+ pass
+
+
+class TargetClosedError(Exception):
+ pass
+
+
+class FailedToNavigateToUrl(Exception):
+ pass
+
+
+class BitwardenVaultError(Exception):
+ pass
+
+
+class LLMProviderError(Exception):
+ pass
+
+
+class RateLimitExceeded(Exception):
+ pass
+
+
+class ScrapingFailedError(Exception):
+ pass
+
+
+class ElementNotFoundError(Exception):
+ pass
+
+
+def _classify(
+ reason: str | None,
+ exception: Exception | None = None,
+ *,
+ fallback_to_unknown: bool = False,
+) -> list[dict]:
+ result = classify_from_failure_reason(reason, exception=exception, fallback_to_unknown=fallback_to_unknown)
+ assert result is not None
+ return result
+
+
+def _categories_for(
+ reason: str | None,
+ exception: Exception | None = None,
+ *,
+ fallback_to_unknown: bool = False,
+) -> list[str]:
+ return [result["category"] for result in _classify(reason, exception, fallback_to_unknown=fallback_to_unknown)]
+
- class UnknownErrorWhileCreatingBrowserContext(Exception):
- pass
+def test_none_input_returns_none() -> None:
+ assert classify_from_failure_reason(None) is None
- result = classify_from_failure_reason(
+
+def test_empty_string_returns_none() -> None:
+ assert classify_from_failure_reason("") is None
+
+
+ ("reason", "expected_categories"),
+ [
+ pytest.param(
+ "Reached the max steps because captcha kept appearing",
+ ["ANTI_BOT_DETECTION", "MAX_STEPS_EXCEEDED"],
+ id="captcha-max-steps",
+ ),
+ pytest.param(
+ "Failed to navigate after redirect loop; page load timeout on wrong page loaded",
+ ["NAVIGATION_FAILURE", "PAGE_LOAD_TIMEOUT", "WRONG_PAGE_STATE"],
+ id="navigation-timeout-state",
+ ),
+ pytest.param(
+ "Login failed with invalid credentials; credential not found; LLM rate limit",
+ ["AUTH_FAILURE", "CREDENTIAL_ERROR", "LLM_ERROR"],
+ id="auth-credential-llm",
+ ),
+ pytest.param(
+ "Scraping failed; target element not found; agent took wrong action; "
+ "Value should have already been set through workflow run parameters",
+ [
+ "DATA_EXTRACTION_FAILURE",
+ "ELEMENT_NOT_FOUND",
+ "LLM_REASONING_ERROR",
+ "PARAMETER_BINDING_ERROR",
+ ],
+ id="extraction-element-reasoning-params",
+ ),
+ ],
+)
+def test_keyword_category_matrix(reason: str, expected_categories: list[str]) -> None:
+ categories = _categories_for(reason)
+
+ for category in expected_categories:
+ assert category in categories
+
+
+def test_exception_category_matrix() -> None:
+ cases = [
+ (
+ "no-proxy-exception",
+ "Failed to create browser context for dynamic-browser (NoProxyAvailable). No proxy available",
+ NoProxyAvailable(),
+ ["PROXY_ERROR"],
+ ["BROWSER_ERROR"],
+ ),
+ (
+ "proxy-reason-over-browser-exception",
"No proxy available, proxy_location=RESIDENTIAL, retry_count=15",
- exception=UnknownErrorWhileCreatingBrowserContext(),
- )
- assert result is not None
- categories = [r["category"] for r in result]
- assert "PROXY_ERROR" in categories
- assert "BROWSER_ERROR" not in categories
-
- def test_proxy_error_exception(self) -> None:
- class ProxyErrorOccurred(Exception):
- pass
-
- result = classify_from_failure_reason("proxy connection failed", exception=ProxyErrorOccurred())
- assert result is not None
- assert result[0]["category"] == "PROXY_ERROR"
-
-
-class TestBrowserError:
- def test_keyword_browser_context_closed(self) -> None:
- result = classify_from_failure_reason("browser context closed unexpectedly")
- assert result is not None
- assert result[0]["category"] == "BROWSER_ERROR"
-
- def test_keyword_page_closed(self) -> None:
- result = classify_from_failure_reason("page closed before action completed")
- assert result is not None
- assert result[0]["category"] == "BROWSER_ERROR"
-
- def test_exception_type_browser(self) -> None:
- class BrowserCrashError(Exception):
- pass
-
- result = classify_from_failure_reason("something failed", exception=BrowserCrashError())
- assert result is not None
- assert result[0]["category"] == "BROWSER_ERROR"
- assert "BrowserCrashError" in result[0]["reasoning"]
-
- def test_exception_type_cdp(self) -> None:
- class CDPConnectionError(Exception):
- pass
-
- result = classify_from_failure_reason("connection lost", exception=CDPConnectionError())
- assert result is not None
- assert result[0]["category"] == "BROWSER_ERROR"
-
- def test_exception_type_target_closed(self) -> None:
- class TargetClosedError(Exception):
- pass
-
- result = classify_from_failure_reason("target gone", exception=TargetClosedError())
- assert result is not None
- assert result[0]["category"] == "BROWSER_ERROR"
-
-
-class TestNavigationFailure:
- def test_keyword_failed_to_navigate(self) -> None:
- result = classify_from_failure_reason("Failed to navigate to the login page")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "NAVIGATION_FAILURE" in categories
-
- def test_keyword_404(self) -> None:
- result = classify_from_failure_reason("Server returned 404 for the URL")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "NAVIGATION_FAILURE" in categories
-
- def test_exception_type(self) -> None:
- class FailedToNavigateToUrl(Exception):
- pass
-
- result = classify_from_failure_reason("url error", exception=FailedToNavigateToUrl())
- assert result is not None
- assert result[0]["category"] == "NAVIGATION_FAILURE"
- assert "FailedToNavigateToUrl" in result[0]["reasoning"]
-
-
-class TestPageLoadTimeout:
- def test_keyword_timeout(self) -> None:
- result = classify_from_failure_reason("Page load timeout after 30s")
- assert result is not None
- assert result[0]["category"] == "PAGE_LOAD_TIMEOUT"
-
- def test_exception_type_timeout(self) -> None:
- result = classify_from_failure_reason("waiting for page", exception=TimeoutError())
- assert result is not None
- assert result[0]["category"] == "PAGE_LOAD_TIMEOUT"
-
-
-class TestAuthFailure:
- @pytest.mark.parametrize(
- "reason",
- [
- "Login failed with invalid credentials",
- "Authentication failed for user",
- "Auth failed - wrong token",
- "MFA verification required",
- ],
- )
- def test_keywords_match(self, reason: str) -> None:
- result = classify_from_failure_reason(reason)
- assert result is not None
- categories = [r["category"] for r in result]
- assert "AUTH_FAILURE" in categories
-
-
-class TestCredentialError:
- def test_keyword_credential_not_found(self) -> None:
- result = classify_from_failure_reason("Credential not found in vault")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "CREDENTIAL_ERROR" in categories
-
- def test_key_lookup_failure(self) -> None:
- result = classify_from_failure_reason("Credential username not found by key: login")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "CREDENTIAL_ERROR" in categories
-
- def test_exception_type_bitwarden(self) -> None:
- class BitwardenVaultError(Exception):
- pass
-
- result = classify_from_failure_reason("vault error", exception=BitwardenVaultError())
- assert result is not None
- assert result[0]["category"] == "CREDENTIAL_ERROR"
-
-
-class TestLLMError:
- def test_keyword_rate_limit(self) -> None:
- result = classify_from_failure_reason("LLM call hit rate limit")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "LLM_ERROR" in categories
-
- def test_exception_type_llm(self) -> None:
- class LLMProviderError(Exception):
- pass
-
- result = classify_from_failure_reason("provider down", exception=LLMProviderError())
- assert result is not None
- assert result[0]["category"] == "LLM_ERROR"
-
- def test_exception_type_rate_limit(self) -> None:
- class RateLimitExceeded(Exception):
- pass
-
- result = classify_from_failure_reason("too many requests", exception=RateLimitExceeded())
- assert result is not None
- categories = [r["category"] for r in result]
- assert "LLM_ERROR" in categories
-
-
-class TestDataExtractionFailure:
- def test_keyword_scraping(self) -> None:
- result = classify_from_failure_reason("Scraping failed on the results page")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "DATA_EXTRACTION_FAILURE" in categories
-
- def test_exception_type_scraping(self) -> None:
- class ScrapingFailedError(Exception):
- pass
-
- result = classify_from_failure_reason("page error", exception=ScrapingFailedError())
- assert result is not None
- categories = [r["category"] for r in result]
- assert "DATA_EXTRACTION_FAILURE" in categories
-
-
-class TestElementNotFound:
- def test_keyword(self) -> None:
- result = classify_from_failure_reason("Target element not found on the page")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "ELEMENT_NOT_FOUND" in categories
-
- def test_exception_type(self) -> None:
- class ElementNotFoundError(Exception):
- pass
-
- result = classify_from_failure_reason("missing", exception=ElementNotFoundError())
- assert result is not None
- categories = [r["category"] for r in result]
- assert "ELEMENT_NOT_FOUND" in categories
-
-
-class TestWrongPageState:
- @pytest.mark.parametrize("reason", ["Unexpected page after login", "Wrong page loaded", "Blank page detected"])
- def test_keywords_match(self, reason: str) -> None:
+ UnknownErrorWhileCreatingBrowserContext(),
+ ["PROXY_ERROR"],
+ ["BROWSER_ERROR"],
+ ),
+ ("proxy-exception", "proxy connection failed", ProxyErrorOccurred(), ["PROXY_ERROR"], []),
+ ("browser-exception-without-reason", None, BrowserCrashError(), ["BROWSER_ERROR"], []),
+ ("cdp-exception", "connection lost", CDPConnectionError(), ["BROWSER_ERROR"], []),
+ ("target-closed-exception", "target gone", TargetClosedError(), ["BROWSER_ERROR"], []),
+ ("navigation-exception", "url error", FailedToNavigateToUrl(), ["NAVIGATION_FAILURE"], []),
+ ("timeout-exception", "waiting for page", TimeoutError(), ["PAGE_LOAD_TIMEOUT"], []),
+ ("credential-exception", "vault error", BitwardenVaultError(), ["CREDENTIAL_ERROR"], []),
+ ("llm-exception", "provider down", LLMProviderError(), ["LLM_ERROR"], []),
+ ("rate-limit-exception", "too many requests", RateLimitExceeded(), ["LLM_ERROR"], []),
+ ("scraping-exception", "page error", ScrapingFailedError(), ["DATA_EXTRACTION_FAILURE"], []),
+ ("element-exception", "missing", ElementNotFoundError(), ["ELEMENT_NOT_FOUND"], []),
+ ]
+
+ for case_id, reason, exception, expected_categories, unexpected_categories in cases:
+ results = _classify(reason, exception=exception)
+ categories = [result["category"] for result in results]
+
+ for category in expected_categories:
+ assert category in categories, case_id
+ for category in unexpected_categories:
+ assert category not in categories, case_id
+ if exception:
+ assert type(exception).__name__ in results[0]["reasoning"], case_id
+
+
+def test_access_denied_with_auth_context_is_not_antibot() -> None:
+ for reason in [
+ "Access denied after login - user does not have permission",
+ "The page shows 'Access Denied'. Unable to enter your password.",
+ ]:
+ categories = _categories_for(reason)
+
+ assert "AUTH_FAILURE" in categories, reason
+ assert "ANTI_BOT_DETECTION" not in categories, reason
+
+
+def test_broad_blocked_and_forbidden_do_not_match_antibot() -> None:
+ for reason in ["UI element blocked by overlay", "403 Forbidden from auth endpoint"]:
result = classify_from_failure_reason(reason)
- assert result is not None
- categories = [r["category"] for r in result]
- assert "WRONG_PAGE_STATE" in categories
-
-
-class TestMaxStepsExceeded:
- @pytest.mark.parametrize(
- "reason",
- [
- "Reached the max steps limit",
- "Maximum steps exceeded for this task",
- "Reached the max number of 25 steps",
- "Step limit reached",
- ],
- )
- def test_keywords_match(self, reason: str) -> None:
- result = classify_from_failure_reason(reason)
- assert result is not None
- categories = [r["category"] for r in result]
- assert "MAX_STEPS_EXCEEDED" in categories
+ if result:
+ assert "ANTI_BOT_DETECTION" not in [r["category"] for r in result], reason
-class TestLLMReasoningError:
- @pytest.mark.parametrize("reason", ["Agent took wrong action on the form", "Invalid action type returned"])
- def test_keywords_match(self, reason: str) -> None:
- result = classify_from_failure_reason(reason)
- assert result is not None
- categories = [r["category"] for r in result]
- assert "LLM_REASONING_ERROR" in categories
+def test_multiple_categories_are_sorted_by_confidence_descending() -> None:
+ result = _classify("Reached the max steps because captcha kept appearing")
-class TestParameterBindingError:
- @pytest.mark.parametrize(
- "reason",
- [
- "Value should have already been set through workflow run parameters",
- "Context should have already been set through workflow run context init",
- "Pre-run invariant: workflow_definition and persisted parameter rows disagree",
- ],
+ assert len(result) >= 2
+ assert [r["confidence_float"] for r in result] == sorted(
+ [r["confidence_float"] for r in result],
+ reverse=True,
)
- def test_keywords_match(self, reason: str) -> None:
- result = classify_from_failure_reason(reason)
- assert result is not None
- categories = [r["category"] for r in result]
- assert "PARAMETER_BINDING_ERROR" in categories
-
-
-class TestMultipleCategories:
- def test_captcha_and_max_steps(self) -> None:
- """A max_steps failure caused by captcha should return both categories."""
- result = classify_from_failure_reason("Reached the max steps because captcha kept appearing")
- assert result is not None
- categories = [r["category"] for r in result]
- assert "ANTI_BOT_DETECTION" in categories
- assert "MAX_STEPS_EXCEEDED" in categories
-
- def test_sorted_by_confidence_descending(self) -> None:
- """Results should be sorted by confidence_float, highest first."""
- result = classify_from_failure_reason("Reached the max steps because captcha kept appearing")
- assert result is not None
- assert len(result) >= 2
- confidences = [r["confidence_float"] for r in result]
- assert confidences == sorted(confidences, reverse=True)
-
-
-class TestExceptionOnlyClassification:
- def test_exception_without_reason(self) -> None:
- """Exception alone (no failure_reason) should still classify."""
-
- class BrowserCrashError(Exception):
- pass
-
- result = classify_from_failure_reason(None, exception=BrowserCrashError())
- assert result is not None
- assert result[0]["category"] == "BROWSER_ERROR"
-
-
-class TestFallbackToUnknown:
- def test_unrecognized_with_fallback_returns_unknown(self) -> None:
- """When fallback_to_unknown=True and no keywords match, return UNKNOWN."""
- result = classify_from_failure_reason("The Resume/CV field is required but empty", fallback_to_unknown=True)
- assert result is not None
- assert len(result) == 1
- assert result[0]["category"] == "UNKNOWN"
- assert result[0]["confidence_float"] == 0.5
-
- def test_unrecognized_without_fallback_returns_none(self) -> None:
- """Default fallback_to_unknown=False preserves existing None behavior."""
- result = classify_from_failure_reason("The Resume/CV field is required but empty")
- assert result is None
-
- def test_none_input_with_fallback_returns_none(self) -> None:
- """None input returns None even with fallback_to_unknown=True (no data = no classification)."""
- result = classify_from_failure_reason(None, fallback_to_unknown=True)
- assert result is None
-
- def test_empty_input_with_fallback_returns_none(self) -> None:
- """Empty string returns None even with fallback_to_unknown=True."""
- result = classify_from_failure_reason("", fallback_to_unknown=True)
- assert result is None
-
- def test_keyword_match_ignores_fallback(self) -> None:
- """When keywords match, fallback_to_unknown has no effect on the result."""
- result_with = classify_from_failure_reason("browser crash detected", fallback_to_unknown=True)
- result_without = classify_from_failure_reason("browser crash detected", fallback_to_unknown=False)
- assert result_with is not None
- assert result_without is not None
- assert result_with[0]["category"] == result_without[0]["category"] == "BROWSER_ERROR"
+
+
+def test_unrecognized_with_fallback_returns_unknown() -> None:
+ result = _classify("The Resume/CV field is required but empty", fallback_to_unknown=True)
+
+ assert len(result) == 1
+ assert result[0]["category"] == "UNKNOWN"
+ assert result[0]["confidence_float"] == 0.5
+
+
+def test_unrecognized_without_fallback_returns_none() -> None:
+ assert classify_from_failure_reason("The Resume/CV field is required but empty") is None
+
+
+def test_none_input_with_fallback_returns_none() -> None:
+ assert classify_from_failure_reason(None, fallback_to_unknown=True) is None
+
+
+def test_empty_input_with_fallback_returns_none() -> None:
+ assert classify_from_failure_reason("", fallback_to_unknown=True) is None
+
+
+def test_keyword_match_ignores_fallback() -> None:
+ result_with = _classify("browser crash detected", fallback_to_unknown=True)
+ result_without = _classify("browser crash detected", fallback_to_unknown=False)
+
+ assert result_with[0]["category"] == result_without[0]["category"] == "BROWSER_ERROR"
diff --git a/tests/unit/test_mcp_clipboard.py b/tests/unit/test_mcp_clipboard.py
index b4d322bf6..0a01915a1 100644
--- a/tests/unit/test_mcp_clipboard.py
+++ b/tests/unit/test_mcp_clipboard.py
@@ -3,33 +3,14 @@
from __future__ import annotations
from typing import Any
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock
import pytest
from skyvern.cli.core.result import BrowserContext
-
-# ═══════════════════════════════════════════════════
-# Helpers
-# ═══════════════════════════════════════════════════
-
-
-def _make_mock_page(url: str = "https://example.com") -> MagicMock:
- page = MagicMock()
- page.url = url
- page.page = page # SkyvernBrowserPage wraps raw page
- page.context = MagicMock()
- page.context.grant_permissions = AsyncMock()
- return page
-
-
-def _patch_get_page(monkeypatch: pytest.MonkeyPatch, page: MagicMock, ctx: BrowserContext) -> AsyncMock:
- from skyvern.cli.mcp_tools import browser as mcp_browser
-
- mock = AsyncMock(return_value=(page, ctx))
- monkeypatch.setattr(mcp_browser, "get_page", mock)
- return mock
-
+from skyvern.cli.mcp_tools import browser as mcp_browser
+from tests.unit._mcp_browser_fakes import make_mock_page as _make_mock_page
+from tests.unit._mcp_browser_fakes import patch_get_page
# ═══════════════════════════════════════════════════
# _ensure_clipboard_permissions
@@ -67,7 +48,7 @@ async def test_clipboard_read_happy_path(monkeypatch: pytest.MonkeyPatch) -> Non
page = _make_mock_page()
page.evaluate = AsyncMock(return_value="hello world")
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_browser, page, ctx)
result = await skyvern_clipboard_read()
@@ -82,7 +63,7 @@ async def test_clipboard_read_empty(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.evaluate = AsyncMock(return_value="")
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_browser, page, ctx)
result = await skyvern_clipboard_read()
@@ -109,7 +90,7 @@ async def test_clipboard_read_evaluate_error(monkeypatch: pytest.MonkeyPatch) ->
page = _make_mock_page()
page.evaluate = AsyncMock(side_effect=Exception("Clipboard API not available"))
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_browser, page, ctx)
result = await skyvern_clipboard_read()
@@ -129,7 +110,7 @@ async def test_clipboard_write_happy_path(monkeypatch: pytest.MonkeyPatch) -> No
page = _make_mock_page()
page.evaluate = AsyncMock(return_value=None)
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_browser, page, ctx)
result = await skyvern_clipboard_write(text="copied text")
@@ -145,7 +126,7 @@ async def test_clipboard_write_empty_string(monkeypatch: pytest.MonkeyPatch) ->
page = _make_mock_page()
page.evaluate = AsyncMock(return_value=None)
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_browser, page, ctx)
result = await skyvern_clipboard_write(text="")
@@ -173,7 +154,7 @@ async def test_clipboard_write_evaluate_error(monkeypatch: pytest.MonkeyPatch) -
page = _make_mock_page()
page.evaluate = AsyncMock(side_effect=Exception("Permission denied"))
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_browser, page, ctx)
result = await skyvern_clipboard_write(text="hello")
@@ -205,7 +186,7 @@ async def test_clipboard_roundtrip(monkeypatch: pytest.MonkeyPatch) -> None:
page.evaluate = mock_evaluate
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_browser, page, ctx)
# Write
write_result = await skyvern_clipboard_write(text="roundtrip test")
diff --git a/tests/unit/test_mcp_dom_inspection.py b/tests/unit/test_mcp_dom_inspection.py
index a8c0717a2..9ca0318bf 100644
--- a/tests/unit/test_mcp_dom_inspection.py
+++ b/tests/unit/test_mcp_dom_inspection.py
@@ -2,43 +2,14 @@
from __future__ import annotations
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock
import pytest
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.mcp_tools import inspection as mcp_inspection
-
-# ═══════════════════════════════════════════════════
-# Helpers
-# ═══════════════════════════════════════════════════
-
-
-def _make_mock_page(url: str = "https://example.com") -> MagicMock:
- page = MagicMock()
- page.url = url
- locator = MagicMock()
- locator.evaluate = AsyncMock(return_value="<span>hello</span>")
- locator.input_value = AsyncMock(return_value="test-value")
- page.locator = MagicMock(return_value=locator)
- return page
-
-
-def _make_skyvern_page(page: MagicMock) -> MagicMock:
- """Mimic SkyvernBrowserPage which delegates attribute access to the raw page."""
- wrapper = MagicMock()
- wrapper.page = page
- wrapper.locator = page.locator
- wrapper.url = page.url
- return wrapper
-
-
-def _patch_get_page(monkeypatch: pytest.MonkeyPatch, page: MagicMock, ctx: BrowserContext) -> AsyncMock:
- skyvern_page = _make_skyvern_page(page)
- mock = AsyncMock(return_value=(skyvern_page, ctx))
- monkeypatch.setattr(mcp_inspection, "get_page", mock)
- return mock
-
+from tests.unit._mcp_browser_fakes import make_mock_page as _make_mock_page
+from tests.unit._mcp_browser_fakes import patch_get_page
# ═══════════════════════════════════════════════════
# skyvern_get_html
@@ -50,7 +21,7 @@ async def test_get_html_inner(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(return_value="<span>hello</span>")
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_html(selector="#content")
@@ -66,7 +37,7 @@ async def test_get_html_outer(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(return_value='<div id="content"><span>hello</span></div>')
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_html(selector="#content", outer=True)
@@ -89,7 +60,7 @@ async def test_get_html_bad_selector(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(side_effect=RuntimeError("Element not found"))
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_html(selector="#nonexistent")
@@ -102,7 +73,7 @@ async def test_get_html_empty(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(return_value="")
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_html(selector="#empty")
@@ -121,7 +92,7 @@ async def test_get_value(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.input_value = AsyncMock(return_value="[email protected]")
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_value(selector="#email")
@@ -135,7 +106,7 @@ async def test_get_value_empty(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.input_value = AsyncMock(return_value="")
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_value(selector="#empty-input")
@@ -157,7 +128,7 @@ async def test_get_value_not_input(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.input_value = AsyncMock(side_effect=RuntimeError("Not an input element"))
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_value(selector="#div-element")
@@ -175,7 +146,7 @@ async def test_get_styles_specific_props(monkeypatch: pytest.MonkeyPatch) -> Non
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(return_value={"color": "rgb(0, 0, 0)", "font-size": "16px"})
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_styles(selector="#heading", properties=["color", "font-size"])
@@ -191,7 +162,7 @@ async def test_get_styles_all(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(return_value=styles)
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_styles(selector="body")
@@ -213,7 +184,7 @@ async def test_get_styles_bad_selector(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(side_effect=RuntimeError("Selector not found"))
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_styles(selector="#nope", properties=["color"])
@@ -226,7 +197,7 @@ async def test_get_styles_empty_properties(monkeypatch: pytest.MonkeyPatch) -> N
page = _make_mock_page()
page.locator.return_value.evaluate = AsyncMock(return_value={})
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
result = await mcp_inspection.skyvern_get_styles(selector="#hidden", properties=[])
diff --git a/tests/unit/test_mcp_har_tools.py b/tests/unit/test_mcp_har_tools.py
index 3ce707272..9fe32d0f0 100644
--- a/tests/unit/test_mcp_har_tools.py
+++ b/tests/unit/test_mcp_har_tools.py
@@ -3,59 +3,15 @@
from __future__ import annotations
from collections import deque
-from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.mcp_tools import inspection as mcp_inspection
-
-# ═══════════════════════════════════════════════════
-# Helpers
-# ═══════════════════════════════════════════════════
-
-
-def _make_mock_page(url: str = "https://example.com") -> MagicMock:
- page = MagicMock()
- page.url = url
- return page
-
-
-def _make_skyvern_page(page: MagicMock) -> MagicMock:
- wrapper = MagicMock()
- wrapper.page = page
- wrapper.url = page.url
- return wrapper
-
-
-def _make_session_state(**overrides):
- import asyncio
- import itertools
-
- defaults = {
- "har_enabled": False,
- "_har_entries": deque(maxlen=5000),
- "console_messages": deque(maxlen=1000),
- "network_requests": deque(maxlen=1000),
- "dialog_events": deque(maxlen=1000),
- "page_errors": deque(maxlen=1000),
- "_hooked_page_ids": set(),
- "_hooked_handlers_map": {},
- "_request_id_counter": itertools.count(),
- "_body_store": {},
- "_body_semaphore": asyncio.Semaphore(5),
- "_pending_tasks": set(),
- }
- defaults.update(overrides)
- return SimpleNamespace(**defaults)
-
-
-def _patch_get_page(monkeypatch: pytest.MonkeyPatch, page: MagicMock, ctx: BrowserContext) -> AsyncMock:
- skyvern_page = _make_skyvern_page(page)
- mock = AsyncMock(return_value=(skyvern_page, ctx))
- monkeypatch.setattr(mcp_inspection, "get_page", mock)
- return mock
+from tests.unit._mcp_browser_fakes import make_mock_page as _make_mock_page
+from tests.unit._mcp_browser_fakes import make_session_state as _make_session_state
+from tests.unit._mcp_browser_fakes import patch_get_page
def _patch_stateless(monkeypatch: pytest.MonkeyPatch, stateless: bool = False) -> None:
@@ -191,7 +147,7 @@ def test_on_response_redacts_secret_query_params_in_har() -> None:
async def test_har_start_happy_path(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
_patch_stateless(monkeypatch, False)
state = _make_session_state()
@@ -208,7 +164,7 @@ async def test_har_start_happy_path(monkeypatch: pytest.MonkeyPatch) -> None:
async def test_har_start_already_active(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
_patch_stateless(monkeypatch, False)
state = _make_session_state(har_enabled=True)
@@ -224,7 +180,7 @@ async def test_har_start_already_active(monkeypatch: pytest.MonkeyPatch) -> None
async def test_har_start_clears_buffer(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
_patch_stateless(monkeypatch, False)
entries = deque(maxlen=5000)
@@ -267,7 +223,7 @@ async def test_har_start_stateless_mode(monkeypatch: pytest.MonkeyPatch) -> None
async def test_har_stop_happy_path(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
_patch_stateless(monkeypatch, False)
entries = deque(maxlen=5000)
@@ -304,7 +260,7 @@ async def test_har_stop_happy_path(monkeypatch: pytest.MonkeyPatch) -> None:
async def test_har_stop_not_recording(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
_patch_stateless(monkeypatch, False)
state = _make_session_state(har_enabled=False)
@@ -340,7 +296,7 @@ async def test_har_roundtrip(monkeypatch: pytest.MonkeyPatch) -> None:
"""Start → capture entries → stop → verify HAR output."""
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
_patch_stateless(monkeypatch, False)
state = _make_session_state()
diff --git a/tests/unit/test_mcp_inspection.py b/tests/unit/test_mcp_inspection.py
index f050b4678..616487033 100644
--- a/tests/unit/test_mcp_inspection.py
+++ b/tests/unit/test_mcp_inspection.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-from collections import deque
-from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
@@ -15,21 +13,8 @@ from skyvern.cli.mcp_tools.inspection import (
skyvern_handle_dialog,
skyvern_network_requests,
)
-
-
-def _make_state() -> SessionState:
- return SessionState(
- console_messages=deque(maxlen=1000),
- network_requests=deque(maxlen=1000),
- dialog_events=deque(maxlen=1000),
- )
-
-
-def _make_page(raw: MagicMock | None = None) -> SimpleNamespace:
- if raw is None:
- raw = MagicMock()
- raw.on = MagicMock()
- return SimpleNamespace(page=raw)
+from tests.unit._mcp_browser_fakes import make_page as _make_page
+from tests.unit._mcp_browser_fakes import make_session_state as _make_state
def _patch(monkeypatch: pytest.MonkeyPatch, state: SessionState) -> None:
diff --git a/tests/unit/test_mcp_network_tracking.py b/tests/unit/test_mcp_network_tracking.py
index c1db630c5..c17ed4ac8 100644
--- a/tests/unit/test_mcp_network_tracking.py
+++ b/tests/unit/test_mcp_network_tracking.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-from collections import deque
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
@@ -26,21 +25,8 @@ from skyvern.cli.mcp_tools.inspection import (
skyvern_network_route,
skyvern_network_unroute,
)
-
-
-def _make_state() -> SessionState:
- return SessionState(
- console_messages=deque(maxlen=1000),
- network_requests=deque(maxlen=1000),
- dialog_events=deque(maxlen=1000),
- )
-
-
-def _make_page(raw: MagicMock | None = None) -> SimpleNamespace:
- if raw is None:
- raw = MagicMock()
- raw.on = MagicMock()
- return SimpleNamespace(page=raw)
+from tests.unit._mcp_browser_fakes import make_page as _make_page
+from tests.unit._mcp_browser_fakes import make_session_state as _make_state
def _patch(monkeypatch: pytest.MonkeyPatch, state: SessionState) -> None:
diff --git a/tests/unit/test_mcp_page_errors.py b/tests/unit/test_mcp_page_errors.py
index 6ae428cda..f634e8dbc 100644
--- a/tests/unit/test_mcp_page_errors.py
+++ b/tests/unit/test_mcp_page_errors.py
@@ -4,51 +4,15 @@ from __future__ import annotations
import time
from collections import deque
-from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.mcp_tools import inspection as mcp_inspection
-
-# ═══════════════════════════════════════════════════
-# Helpers
-# ═══════════════════════════════════════════════════
-
-
-def _make_mock_page(url: str = "https://example.com") -> MagicMock:
- page = MagicMock()
- page.url = url
- return page
-
-
-def _make_skyvern_page(page: MagicMock) -> MagicMock:
- wrapper = MagicMock()
- wrapper.page = page
- wrapper.url = page.url
- return wrapper
-
-
-def _make_session_state(**overrides):
- defaults = {
- "page_errors": deque(maxlen=1000),
- "console_messages": deque(maxlen=1000),
- "network_requests": deque(maxlen=1000),
- "dialog_events": deque(maxlen=1000),
- "_hooked_page_ids": set(),
- "_hooked_handlers_map": {},
- }
- defaults.update(overrides)
- return SimpleNamespace(**defaults)
-
-
-def _patch_get_page(monkeypatch: pytest.MonkeyPatch, page: MagicMock, ctx: BrowserContext) -> AsyncMock:
- skyvern_page = _make_skyvern_page(page)
- mock = AsyncMock(return_value=(skyvern_page, ctx))
- monkeypatch.setattr(mcp_inspection, "get_page", mock)
- return mock
-
+from tests.unit._mcp_browser_fakes import make_mock_page as _make_mock_page
+from tests.unit._mcp_browser_fakes import make_session_state as _make_session_state
+from tests.unit._mcp_browser_fakes import patch_get_page
# ═══════════════════════════════════════════════════
# pageerror hook registration
@@ -123,7 +87,7 @@ def test_register_hooks_registers_pageerror() -> None:
async def test_get_errors_empty(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
state = _make_session_state()
monkeypatch.setattr(mcp_inspection, "get_current_session", lambda: state)
@@ -140,7 +104,7 @@ async def test_get_errors_empty(monkeypatch: pytest.MonkeyPatch) -> None:
async def test_get_errors_returns_buffered_errors(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
errors = deque(maxlen=1000)
errors.append(
@@ -173,7 +137,7 @@ async def test_get_errors_returns_buffered_errors(monkeypatch: pytest.MonkeyPatc
async def test_get_errors_text_filter(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
errors = deque(maxlen=1000)
errors.append(
@@ -207,7 +171,7 @@ async def test_get_errors_text_filter(monkeypatch: pytest.MonkeyPatch) -> None:
async def test_get_errors_clear(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
errors = deque(maxlen=1000)
errors.append({"message": "Error 1", "timestamp": time.time(), "page_url": "https://example.com", "tab_id": "1"})
@@ -227,7 +191,7 @@ async def test_get_errors_clear(monkeypatch: pytest.MonkeyPatch) -> None:
async def test_get_errors_clear_with_filter(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_inspection, page, ctx)
errors = deque(maxlen=1000)
errors.append(
diff --git a/tests/unit/test_mcp_storage_tools.py b/tests/unit/test_mcp_storage_tools.py
index 62fd9a8a4..8d9f4cf8d 100644
--- a/tests/unit/test_mcp_storage_tools.py
+++ b/tests/unit/test_mcp_storage_tools.py
@@ -2,40 +2,14 @@
from __future__ import annotations
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock
import pytest
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.mcp_tools import storage as mcp_storage
-
-# ═══════════════════════════════════════════════════
-# Helpers
-# ═══════════════════════════════════════════════════
-
-
-def _make_mock_page(url: str = "https://example.com") -> MagicMock:
- page = MagicMock()
- page.url = url
- page.evaluate = AsyncMock(return_value={})
- return page
-
-
-def _make_skyvern_page(page: MagicMock) -> MagicMock:
- """Mimic SkyvernBrowserPage which delegates attribute access to the raw page."""
- wrapper = MagicMock()
- wrapper.page = page
- wrapper.evaluate = page.evaluate
- wrapper.url = page.url
- return wrapper
-
-
-def _patch_get_page(monkeypatch: pytest.MonkeyPatch, page: MagicMock, ctx: BrowserContext) -> AsyncMock:
- skyvern_page = _make_skyvern_page(page)
- mock = AsyncMock(return_value=(skyvern_page, ctx))
- monkeypatch.setattr(mcp_storage, "get_page", mock)
- return mock
-
+from tests.unit._mcp_browser_fakes import make_mock_page as _make_mock_page
+from tests.unit._mcp_browser_fakes import patch_get_page
# ═══════════════════════════════════════════════════
# skyvern_get_session_storage
@@ -47,7 +21,7 @@ async def test_get_session_storage_all(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.evaluate = AsyncMock(return_value={"token": "abc", "lang": "en"})
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_get_session_storage()
@@ -61,7 +35,7 @@ async def test_get_session_storage_specific_keys(monkeypatch: pytest.MonkeyPatch
page = _make_mock_page()
page.evaluate = AsyncMock(side_effect=["abc", None])
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_get_session_storage(keys=["token", "missing"])
@@ -75,7 +49,7 @@ async def test_get_session_storage_empty(monkeypatch: pytest.MonkeyPatch) -> Non
page = _make_mock_page()
page.evaluate = AsyncMock(return_value={})
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_get_session_storage()
@@ -97,7 +71,7 @@ async def test_get_session_storage_evaluate_error(monkeypatch: pytest.MonkeyPatc
page = _make_mock_page()
page.evaluate = AsyncMock(side_effect=RuntimeError("page crashed"))
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_get_session_storage()
@@ -115,7 +89,7 @@ async def test_set_session_storage(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.evaluate = AsyncMock(return_value=None)
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_set_session_storage(key="theme", value="dark")
@@ -144,7 +118,7 @@ async def test_clear_session_storage(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.evaluate = AsyncMock(return_value=3)
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_clear_session_storage()
@@ -171,7 +145,7 @@ async def test_clear_local_storage(monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_mock_page()
page.evaluate = AsyncMock(return_value=5)
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_clear_local_storage()
@@ -193,7 +167,7 @@ async def test_clear_local_storage_error(monkeypatch: pytest.MonkeyPatch) -> Non
page = _make_mock_page()
page.evaluate = AsyncMock(side_effect=RuntimeError("security error"))
ctx = BrowserContext(mode="local")
- _patch_get_page(monkeypatch, page, ctx)
+ patch_get_page(monkeypatch, mcp_storage, page, ctx)
result = await mcp_storage.skyvern_clear_local_storage()
diff --git a/tests/unit/test_webhook_delivery_retry.py b/tests/unit/test_webhook_delivery_retry.py
index 182dbc41a..97365cd52 100644
--- a/tests/unit/test_webhook_delivery_retry.py
+++ b/tests/unit/test_webhook_delivery_retry.py
@@ -19,6 +19,19 @@ def _response(status_code: int, body: str = "", headers: dict[str, str] | None =
return httpx.Response(status_code=status_code, content=body.encode("utf-8"), headers=headers or {})
+async def _deliver_with_mock(deliver: AsyncMock, **kwargs) -> httpx.Response:
+ with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
+ return await deliver_webhook_with_retries(
+ url="https://example.com/hook",
+ payload="{}",
+ headers={},
+ timeout_seconds=30.0,
+ organization_id="o_1",
+ run_id="wr_1",
+ **kwargs,
+ )
+
+
@pytest.fixture
def fake_sleep(monkeypatch: pytest.MonkeyPatch) -> list[float]:
"""Replace asyncio.sleep with a no-op recorder so tests don't actually wait."""
@@ -40,15 +53,7 @@ def no_jitter(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest.mark.asyncio
async def test_returns_immediately_on_success(fake_sleep: list[float]) -> None:
deliver = AsyncMock(return_value=_response(200, "ok"))
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
+ resp = await _deliver_with_mock(deliver)
assert resp.status_code == 200
assert deliver.await_count == 1
@@ -56,17 +61,18 @@ async def test_returns_immediately_on_success(fake_sleep: list[float]) -> None:
@pytest.mark.asyncio
-async def test_retries_on_403_then_succeeds(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(side_effect=[_response(403, "forbidden"), _response(200, "ok")])
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
+ "status_code",
+ [
+ pytest.param(403, id="403"),
+ pytest.param(429, id="429"),
+ pytest.param(503, id="503"),
+ pytest.param(521, id="521"),
+ ],
+)
+async def test_retryable_status_then_success(status_code: int, fake_sleep: list[float]) -> None:
+ deliver = AsyncMock(side_effect=[_response(status_code), _response(200, "ok")])
+ resp = await _deliver_with_mock(deliver)
assert resp.status_code == 200
assert deliver.await_count == 2
@@ -74,103 +80,27 @@ async def test_retries_on_403_then_succeeds(fake_sleep: list[float]) -> None:
@pytest.mark.asyncio
-async def test_retries_on_5xx_then_succeeds(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(side_effect=[_response(503, "unavailable"), _response(200)])
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 200
- assert deliver.await_count == 2
-
-
-async def test_retries_on_429_then_succeeds(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(side_effect=[_response(429), _response(200)])
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 200
- assert deliver.await_count == 2
-
-
-async def test_does_not_retry_on_400_bad_request(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(return_value=_response(400, "bad request"))
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
+ "status_code",
+ [
+ pytest.param(400, id="400"),
+ pytest.param(401, id="401"),
+ pytest.param(404, id="404"),
+ ],
+)
+async def test_non_retryable_status_returns_without_retry(status_code: int, fake_sleep: list[float]) -> None:
+ deliver = AsyncMock(return_value=_response(status_code))
+ resp = await _deliver_with_mock(deliver)
- assert resp.status_code == 400
+ assert resp.status_code == status_code
assert deliver.await_count == 1
assert fake_sleep == []
-async def test_does_not_retry_on_401_unauthorized(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(return_value=_response(401))
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 401
- assert deliver.await_count == 1
-
-
-async def test_does_not_retry_on_404(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(return_value=_response(404))
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 404
- assert deliver.await_count == 1
-
-
@pytest.mark.asyncio
async def test_returns_final_failure_when_all_attempts_fail(fake_sleep: list[float]) -> None:
deliver = AsyncMock(return_value=_response(503, "still down"))
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
+ resp = await _deliver_with_mock(deliver)
assert resp.status_code == 503
assert deliver.await_count == WEBHOOK_DELIVERY_MAX_ATTEMPTS
@@ -178,56 +108,28 @@ async def test_returns_final_failure_when_all_attempts_fail(fake_sleep: list[flo
@pytest.mark.asyncio
-async def test_retries_on_network_error_then_succeeds(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(side_effect=[httpx.ConnectError("conn refused"), _response(200)])
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 200
- assert deliver.await_count == 2
-
-
-async def test_retries_on_timeout_then_succeeds(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(side_effect=[httpx.ReadTimeout("slow"), _response(200)])
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 200
- assert deliver.await_count == 2
-
-
-async def test_retries_on_remote_protocol_error_then_succeeds(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(
- side_effect=[
+ "exception",
+ [
+ pytest.param(httpx.ConnectError("conn refused"), id="ConnectError"),
+ pytest.param(httpx.ReadTimeout("slow"), id="ReadTimeout"),
+ pytest.param(
httpx.RemoteProtocolError("Server disconnected without sending a response"),
- _response(200),
- ],
- )
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
+ id="RemoteProtocolError",
+ ),
+ pytest.param(
+ httpx.HTTPStatusError(
+ "503",
+ request=httpx.Request("POST", "https://proxy.example/proxy/webhook"),
+ response=_response(503),
+ ),
+ id="HTTPStatusError-retryable",
+ ),
+ ],
+)
+async def test_retryable_exception_then_success(exception: Exception, fake_sleep: list[float]) -> None:
+ deliver = AsyncMock(side_effect=[exception, _response(200)])
+ resp = await _deliver_with_mock(deliver)
assert resp.status_code == 200
assert deliver.await_count == 2
@@ -277,43 +179,6 @@ def test_is_retryable_status_covers_full_5xx_range_and_curated_4xx() -> None:
assert not is_retryable_status(code)
-async def test_retries_on_521_then_succeeds(fake_sleep: list[float]) -> None:
- deliver = AsyncMock(side_effect=[_response(521, "origin down"), _response(200)])
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 200
- assert deliver.await_count == 2
-
-
-async def test_retries_on_http_status_error_5xx_then_succeeds(fake_sleep: list[float]) -> None:
- """NAT proxy client raises HTTPStatusError on proxy-side 5xx via raise_for_status()."""
- request = httpx.Request("POST", "https://proxy.example/proxy/webhook")
- err = httpx.HTTPStatusError("503", request=request, response=_response(503))
- deliver = AsyncMock(side_effect=[err, _response(200)])
- with patch("skyvern.services.webhook_delivery.app.AGENT_FUNCTION.deliver_webhook", deliver):
- resp = await deliver_webhook_with_retries(
- url="https://example.com/hook",
- payload="{}",
- headers={},
- timeout_seconds=30.0,
- organization_id="o_1",
- run_id="wr_1",
- )
-
- assert resp.status_code == 200
- assert deliver.await_count == 2
-
-
@pytest.mark.asyncio
async def test_re_raises_http_status_error_on_non_retryable(fake_sleep: list[float]) -> None:
request = httpx.Request("POST", "https://proxy.example/proxy/webhook")