Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

test(wpt): serve programmed navigation responses

ldm0b98e48013b8c
diff --git a/moli-benchmark/moli_benchmark/wpt_cross/case_set.py b/moli-benchmark/moli_benchmark/wpt_cross/case_set.py
index da1865673..4a5522a5a 100644
--- a/moli-benchmark/moli_benchmark/wpt_cross/case_set.py
+++ b/moli-benchmark/moli_benchmark/wpt_cross/case_set.py
@@ -738,6 +738,22 @@ def _script_content_type_handler_reference_patterns(directory: str) -> tuple[re.
)
+@lru_cache(maxsize=None)
+def _navigation_handler_reference_patterns(directory: str) -> tuple[re.Pattern[str], ...]:
+ resource = (
+ "navigation-api/navigation-methods/return-value/resources/"
+ "204-205-download-on-second-visit.py"
+ )
+ relative = posixpath.relpath(resource, directory)
+ return tuple(
+ re.compile(
+ rf"(?<![A-Za-z0-9_./-]){re.escape(reference)}"
+ rf"{WPTSERVE_HANDLER_TRAILING_BOUNDARY}"
+ )
+ for reference in ("/" + resource, relative, "./" + relative)
+ )
+
+
@lru_cache(maxsize=None)
def _json_module_handler_reference_patterns(directory: str) -> tuple[re.Pattern[str], ...]:
references = []
@@ -793,6 +809,7 @@ def _supported_wptserve_handler_references(
if rel is not None and rel.startswith("fetch/api/"):
supported += _empty_location_handler_reference_patterns(posixpath.dirname(rel))
if rel is not None:
+ supported += _navigation_handler_reference_patterns(posixpath.dirname(rel) or ".")
supported += _json_module_handler_reference_patterns(posixpath.dirname(rel) or ".")
if rel is not None:
supported += _script_content_type_handler_reference_patterns(posixpath.dirname(rel) or ".")
diff --git a/moli-benchmark/moli_benchmark/wpt_cross/server.py b/moli-benchmark/moli_benchmark/wpt_cross/server.py
index f29e941fe..01ca33390 100644
--- a/moli-benchmark/moli_benchmark/wpt_cross/server.py
+++ b/moli-benchmark/moli_benchmark/wpt_cross/server.py
@@ -98,6 +98,10 @@ JSON_LOAD_ERROR_PATH = (
"/html/semantics/scripting-1/the-script-element/json-module/load-error-events.py"
)
+NAVIGATION_SECOND_VISIT_PATH = (
+ "/navigation-api/navigation-methods/return-value/resources/"
+ "204-205-download-on-second-visit.py"
+)
BENCH_TIMEOUT_MULTIPLIER_QUERY = "__moli_bench_timeout_multiplier"
BENCH_REPORT_BRIDGE_SRC_RE = re.compile(
rb"(?P<prefix>\bsrc\s*=\s*)(?P<quote>['\"])"
@@ -1573,19 +1577,20 @@ def _fetch_status_response(query: str) -> tuple[int, str, str, bytes]:
class FetchStash:
- """Write-once, read-once stash scoped to /fetch/api/resources/.
+ """Write-once, read-once stash with independent resource-path namespaces.
- Every origin of one fixture server shares this namespace. UUID
+ Every origin of one fixture server shares these namespaces. UUID
normalization matches wptserve, including equivalent key spellings.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
- self._values: dict[uuid.UUID, str] = {}
+ self._values: dict[tuple[str, uuid.UUID], str] = {}
self._counts: dict[tuple[str, uuid.UUID], int] = {}
- def put(self, key: str, value: str, *, overwrite: bool = False) -> None:
- parsed_key = uuid.UUID(key)
+ def put(self, key: str, value: str, *, path: str = "/fetch/api/resources/",
+ overwrite: bool = False) -> None:
+ parsed_key = (path, uuid.UUID(key))
with self._lock:
if not overwrite and parsed_key in self._values:
raise ValueError("Tried to overwrite existing shared stash value")
@@ -1599,8 +1604,8 @@ class FetchStash:
return value
- def take(self, key: str) -> str | None:
- parsed_key = uuid.UUID(key)
+ def take(self, key: str, *, path: str = "/fetch/api/resources/") -> str | None:
+ parsed_key = (path, uuid.UUID(key))
with self._lock:
return self._values.pop(parsed_key, None)
@@ -1632,6 +1637,9 @@ def _make_handler(
return
parsed = urlparse(self.path)
path = unquote(parsed.path)
+ if path == NAVIGATION_SECOND_VISIT_PATH:
+ self._serve_navigation_second_visit()
+ return
if path in FETCH_ABORT_RESOURCE_PATHS | FETCH_RANGE_RESOURCE_PATHS | {
"/fetch/api/resources/status.py", "/fetch/api/resources/trickle.py"
}:
@@ -1661,6 +1669,9 @@ def _make_handler(
return
parsed = urlparse(self.path)
path = unquote(parsed.path)
+ if path == NAVIGATION_SECOND_VISIT_PATH:
+ self._serve_navigation_second_visit()
+ return
if path in FETCH_ABORT_RESOURCE_PATHS | FETCH_RANGE_RESOURCE_PATHS | {
"/fetch/api/resources/status.py", "/fetch/api/resources/trickle.py"
}:
@@ -1711,6 +1722,9 @@ def _make_handler(
return
parsed = urlparse(self.path)
path = unquote(parsed.path)
+ if path == NAVIGATION_SECOND_VISIT_PATH:
+ self._serve_navigation_second_visit()
+ return
if path in FETCH_RANGE_RESOURCE_PATHS:
self._serve_fetch_range_resource(path, parsed.query, emit_body=self.command != "HEAD")
return
@@ -1741,6 +1755,9 @@ def _make_handler(
self._serve_xhr_response_resource()
return
parsed = urlparse(self.path)
+ if unquote(parsed.path) == NAVIGATION_SECOND_VISIT_PATH:
+ self._serve_navigation_second_visit()
+ return
if unquote(parsed.path) in FETCH_ABORT_RESOURCE_PATHS | FETCH_RANGE_RESOURCE_PATHS | {
"/fetch/api/resources/status.py", "/fetch/api/resources/trickle.py"
}:
@@ -1872,6 +1889,9 @@ def _make_handler(
return
parsed = urlparse(self.path)
path = unquote(parsed.path)
+ if path == NAVIGATION_SECOND_VISIT_PATH:
+ self._serve_navigation_second_visit()
+ return
if path in FETCH_RANGE_RESOURCE_PATHS:
self._serve_fetch_range_resource(path, parsed.query, emit_body=emit_body)
return
@@ -2406,6 +2426,8 @@ def _make_handler(
)
def __getattr__(self, name: str):
+ if name.startswith("do_") and unquote(urlparse(self.path).path) == NAVIGATION_SECOND_VISIT_PATH:
+ return self._serve_navigation_second_visit
if name.startswith("do_") and unquote(urlparse(self.path).path) == FETCH_EMPTY_LOCATION_PATH:
return self._serve_empty_location_resource
if name.startswith("do_") and unquote(urlparse(self.path).path) in XHR_RESPONSE_RESOURCE_PATHS:
@@ -2607,6 +2629,37 @@ def _make_handler(
pass # Upstream ends its stream when a write reports disconnect.
+ def _serve_navigation_second_visit(self) -> None:
+ if not self._consume_request_body():
+ return
+ params = parse_qs(urlsplit(self.path).query, keep_blank_values=True, encoding="latin-1")
+ stash_path = NAVIGATION_SECOND_VISIT_PATH.rsplit("/", 1)[0] + "/"
+ status, content_type, body = 400, None, b""
+ headers: list[tuple[str, str]] = []
+ cache_control = None
+ try:
+ key = params["id"][0]
+ if self.command == "POST":
+ fetch_stash.put(key, params["action"][0], path=stash_path)
+ status = 204
+ elif self.command == "GET":
+ action = fetch_stash.take(key, path=stash_path)
+ if action is None:
+ status, content_type, body = 200, "text/html", b"initial page"
+ cache_control = "no-store"
+ elif action in ("204", "205"):
+ status = int(action)
+ elif action == "download":
+ status, content_type, body = 200, "text/plain", b"some text to download"
+ headers.append(("Content-Disposition", "attachment"))
+ except (KeyError, ValueError):
+ self.send_error(500)
+ return
+ self._send_bytes(
+ content_type, body, emit_body=self.command != "HEAD",
+ status_code=status, extra_headers=headers, cache_control=cache_control,
+ )
+
def _serve_fetch_abort_resource(
self, path: str, query: str, *, emit_body: bool
) -> None:
diff --git a/moli-benchmark/tests/test_wpt_navigation_response_server.py b/moli-benchmark/tests/test_wpt_navigation_response_server.py
new file mode 100644
index 000000000..60fa2101e
--- /dev/null
+++ b/moli-benchmark/tests/test_wpt_navigation_response_server.py
@@ -0,0 +1,135 @@
+from __future__ import annotations
+
+import tempfile
+import unittest
+import uuid
+from contextlib import ExitStack
+from http.client import HTTPConnection
+from pathlib import Path
+from unittest.mock import patch
+
+from moli_benchmark.wpt_cross.case_set import enumerate_cases
+from moli_benchmark.wpt_cross.server import NAVIGATION_SECOND_VISIT_PATH, WptFixtureServer
+
+
+CASE_DIRECTORY = "navigation-api/navigation-methods/return-value"
+
+
+class NavigationResponseFixtureTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.stack = ExitStack()
+ self.addCleanup(self.stack.close)
+ self.root = Path(self.stack.enter_context(tempfile.TemporaryDirectory()))
+ (self.root / "resources").mkdir()
+ (self.root / "resources/testharness.js").write_text("// testharness")
+ resource = self.root / NAVIGATION_SECOND_VISIT_PATH.lstrip("/")
+ resource.parent.mkdir(parents=True)
+ resource.write_text("# Python source must not be served")
+ self.stack.enter_context(patch(
+ "moli_benchmark.wpt_cross.server._global_ipv6_address", return_value=None,
+ ))
+ self.server = self.stack.enter_context(WptFixtureServer(self.root))
+
+ def request(self, query: str, *, method: str = "GET", port: int | None = None,
+ path: str = NAVIGATION_SECOND_VISIT_PATH):
+ connection = HTTPConnection("127.0.0.1", port or self.server.port, timeout=2)
+ try:
+ connection.request(method, path + "?" + query,
+ body=b"ignored request body" if method == "POST" else None)
+ response = connection.getresponse()
+ return response.status, response.headers, response.read()
+ finally:
+ connection.close()
+
+ def assert_initial_page(self, query: str, *, port: int | None = None) -> None:
+ status, headers, body = self.request(query, port=port)
+ self.assertEqual((status, headers["Content-Type"], body),
+ (200, "text/html", b"initial page"))
+ self.assertEqual(headers["Cache-Control"], "no-store")
+ self.assertIsNone(headers["Content-Disposition"])
+
+ def test_post_programs_one_get_response(self) -> None:
+ for action in ("204", "205", "download"):
+ with self.subTest(action=action):
+ key = uuid.uuid4()
+ query = f"id={key}"
+ self.assert_initial_page(query)
+ status, headers, body = self.request(query + f"&action={action}", method="POST")
+ self.assertEqual((status, body), (204, b""))
+ self.assertIsNone(headers["Content-Type"])
+ self.assertIsNone(headers["Cache-Control"])
+ status, headers, body = self.request(query)
+ if action == "download":
+ self.assertEqual((status, headers["Content-Type"], body),
+ (200, "text/plain", b"some text to download"))
+ self.assertEqual(headers["Content-Disposition"], "attachment")
+ else:
+ self.assertEqual((status, body), (int(action), b""))
+ self.assertIsNone(headers["Content-Type"])
+ self.assertIsNone(headers["Cache-Control"])
+ self.assert_initial_page(query)
+
+ def test_state_is_shared_across_origins_but_isolated_by_key_server_and_path(self) -> None:
+ key = uuid.uuid4()
+ query = f"id={key}"
+ self.assertEqual(self.request(query + "&action=205", method="POST")[0], 204)
+ self.assert_initial_page(f"id={uuid.uuid4()}")
+ other = self.stack.enter_context(WptFixtureServer(self.root))
+ self.assert_initial_page(query, port=other.port)
+ status, _, body = self.request(f"key={key}", path="/fetch/api/resources/stash-take.py")
+ self.assertEqual((status, body), (200, b"null"))
+ status, _, _ = self.request(f"id={str(key).upper()}", port=self.server.alternate_port)
+ self.assertEqual(status, 205)
+ self.assert_initial_page(f"id={key.hex}")
+
+ def test_unsupported_methods_do_not_consume_the_programmed_response(self) -> None:
+ query = f"id={uuid.uuid4()}"
+ self.assertEqual(self.request(query + "&action=204", method="POST")[0], 204)
+ for method in ("HEAD", "OPTIONS", "PUT", "PATCH", "DELETE", "YO", "CUSTOM"):
+ with self.subTest(method=method):
+ status, _, body = self.request(query, method=method)
+ self.assertEqual((status, body), (400, b""))
+ self.assertEqual(self.request(query)[0], 204)
+ self.assert_initial_page(query)
+
+ def test_unknown_actions_are_consumed_and_duplicate_posts_do_not_overwrite(self) -> None:
+ query = f"id={uuid.uuid4()}"
+ for action in ("unknown", ""):
+ self.assertEqual(self.request(query + f"&action={action}", method="POST")[0], 204)
+ self.assertEqual(self.request(query)[0], 400)
+ self.assert_initial_page(query)
+ self.assertEqual(self.request(query + "&action=205&action=204", method="POST")[0], 204)
+ self.assertEqual(self.request(query + "&action=204", method="POST")[0], 500)
+ self.assertEqual(self.request(query + "&id=ignored")[0], 205)
+
+ def test_invalid_parameters_report_errors(self) -> None:
+ for query, method in (("", "GET"), ("id=", "GET"), ("id=not-a-uuid", "GET"),
+ (f"id={uuid.uuid4()}", "POST"), ("id=%FF&action=204", "POST")):
+ with self.subTest(query=query, method=method):
+ self.assertEqual(self.request(query, method=method)[0], 500)
+
+ def test_discovery_accepts_only_supported_resource_locations(self) -> None:
+ resource = "resources/204-205-download-on-second-visit.py"
+ cases = {
+ "relative.html": (resource, True),
+ "dot.html": ("./" + resource, True),
+ "absolute.html": (NAVIGATION_SECOND_VISIT_PATH, True),
+ "wrong-directory.html": ("../" + resource, False),
+ "basename.html": (resource.rsplit("/", 1)[1], False),
+ "suffix.html": (resource + ".extra", False),
+ }
+ for name, (reference, _) in cases.items():
+ (self.root / CASE_DIRECTORY / name).write_text(
+ '<script src="/resources/testharness.js"></script>'
+ '<script src="/resources/testharnessreport.js"></script>'
+ f'<script>fetch(`{reference}?id=${{id}}`);</script>'
+ )
+ discovered = enumerate_cases(self.root, dir_prefixes=(CASE_DIRECTORY,))
+ self.assertEqual(
+ sorted(case.case_path for case in discovered),
+ sorted(CASE_DIRECTORY + "/" + name for name, (_, allowed) in cases.items() if allowed),
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()