From e251847f540eb01625947a50fb010f726d5b44b9 Mon Sep 17 00:00:00 2001 From: Ryan Hunt Date: Fri, 20 Nov 2026 21:13:22 -0600 Subject: [PATCH 1/3] [js-api] WIP - add CI --- .github/workflows/ci-js-api.yml | 77 +++++ test/js-api/README.md | 38 +++ test/js-api/expectations.json | 454 +++++++++++++++++++++++++++++ test/js-api/run.py | 495 ++++++++++++++++++++++++++++++++ test/sync-js-api.py | 54 ---- 5 files changed, 1064 insertions(+), 54 deletions(-) create mode 100644 .github/workflows/ci-js-api.yml create mode 100644 test/js-api/expectations.json create mode 100755 test/js-api/run.py delete mode 100755 test/sync-js-api.py diff --git a/.github/workflows/ci-js-api.yml b/.github/workflows/ci-js-api.yml new file mode 100644 index 0000000000..2bef2752d7 --- /dev/null +++ b/.github/workflows/ci-js-api.yml @@ -0,0 +1,77 @@ +name: CI for Wasm JS API tests + +on: + push: + branches: [main] + paths: + - .github/workflows/ci-js-api.yml + - test/harness/testharness.js + - test/js-api/** + + pull_request: + branches: [main] + paths: + - .github/workflows/ci-js-api.yml + - test/harness/testharness.js + - test/js-api/** + + workflow_dispatch: + +permissions: + contents: read + +jobs: + js-api: + name: JS API (${{ matrix.browser }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + include: + - browser: firefox + os: ubuntu-24.04 + - browser: chrome + os: ubuntu-24.04 + - browser: safari + os: macos-15 + steps: + - name: Checkout repo + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: '3.14' + - name: Install Selenium + run: python -m pip install selenium==4.53.0 + - name: Enable Safari Remote Automation + if: matrix.browser == 'safari' + run: sudo /usr/bin/safaridriver --enable + - name: Run JS API tests + env: + BROWSER: ${{ matrix.browser }} + run: python test/js-api/run.py --browser "$BROWSER" --json wasm-js-api.json + - name: Upload browser report + if: ${{ !cancelled() && hashFiles('wasm-js-api.json') != '' }} + uses: actions/upload-artifact@v4 + with: + name: wasm-js-api-${{ matrix.browser }} + path: wasm-js-api.json + if-no-files-found: error + - name: Summarize browser results + if: ${{ !cancelled() && hashFiles('wasm-js-api.json') != '' }} + run: | + python - <<'PY' >> "$GITHUB_STEP_SUMMARY" + from collections import Counter + import json + from pathlib import Path + + report = json.loads(Path('wasm-js-api.json').read_text(encoding='utf-8')) + counts = Counter(case['outcome'] for case in report['results']) + print(f"### Wasm JS API in {report['browser']} {report['version']}\n") + print('| Pass | Fail | Expected failure | Unexpected pass | Skip |') + print('| ---: | ---: | ---: | ---: | ---: |') + print('| ' + ' | '.join(str(counts[outcome]) for outcome in ('PASS', 'FAIL', 'XFAIL', 'XPASS', 'SKIP')) + ' |') + PY diff --git a/test/js-api/README.md b/test/js-api/README.md index ca30ca42f5..840ce414f2 100644 --- a/test/js-api/README.md +++ b/test/js-api/README.md @@ -10,6 +10,44 @@ The tests use the [testharness.js] library and the [multi-global tests] setup for smooth integrations with the web-platform-tests project and the existing test infrastructure in implementations. +## Running in browsers + +From the repository root, install Selenium in a Python virtual environment and +run the suite against an installed browser. + +```sh +python3 -m venv /tmp/wasm-js-api-venv +/tmp/wasm-js-api-venv/bin/python -m pip install selenium +/tmp/wasm-js-api-venv/bin/python test/js-api/run.py --browser firefox|chrome|safari +``` + +For Safari, enable Remote Automation once with `safaridriver --enable`. + +### Browser expectations + +Selenium runs load [`expectations.json`](expectations.json). + +```json +{ + "memory/buffer.any.js": [ + { + "browser": "safari", + "context": "dedicatedworker", + "subtest": "Branding", + "expect": "fail", + "reason": "Link to the issue tracking this failure" + } + ], + "table/grow.any.js": [ + { + "browser": "firefox", + "expect": "skip", + "reason": "Link to the issue tracking why this test cannot run" + } + ] +} +``` + ## Metadata All tests must have the `.any.js` extension. diff --git a/test/js-api/expectations.json b/test/js-api/expectations.json new file mode 100644 index 0000000000..057c5727fc --- /dev/null +++ b/test/js-api/expectations.json @@ -0,0 +1,454 @@ +{ + "exception/constructor.tentative.any.js": [ + { + "browser": "firefox", + "subtest": "length", + "expect": "fail", + "reason": "WebAssembly.Exception.length is 1 instead of 2." + }, + { + "browser": "safari", + "subtest": "length", + "expect": "fail", + "reason": "WebAssembly.Exception.length is 1 instead of 2." + } + ], + "exception/getArg.tentative.any.js": [ + { + "browser": "safari", + "subtest": "Getting out-of-range argument", + "expect": "fail", + "reason": "Exception.getArg throws RangeError instead of TypeError for an out-of-range argument." + } + ], + "global/value-get-set.any.js": [ + { + "browser": "firefox", + "subtest": "Calling setter without argument", + "expect": "fail", + "reason": "The WebAssembly.Global value setter rejects a call with no argument." + }, + { + "browser": "safari", + "subtest": "Calling setter without argument", + "expect": "fail", + "reason": "The WebAssembly.Global value setter rejects a call with no argument." + } + ], + "instance/constructor-caching.any.js": [ + { + "browser": "safari", + "context": "window", + "subtest": "instance/constructor-caching.any.js (window)", + "expect": "fail", + "reason": "The cached and original WebAssembly.Global objects have different identities." + }, + { + "browser": "safari", + "context": "dedicatedworker", + "subtest": "constructor-caching", + "expect": "fail", + "reason": "The cached and original WebAssembly.Global objects have different identities." + } + ], + "interface.any.js": [ + { + "browser": "firefox", + "subtest": "WebAssembly.Table.set: length", + "expect": "fail", + "reason": "WebAssembly.Table.prototype.set.length is 2 instead of 1." + } + ], + "memory/constructor-memory64.any.js": [ + { + "browser": "safari", + "subtest": "Initial value exceeds maximum (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Zero initial (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Non-zero initial (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Memory with i64 address constructor", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Memory with string value for initial (i64)", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Memory with boolean value for initial (i64)", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + } + ], + "memory/constructor.any.js": [ + { + "browser": "safari", + "subtest": "Order of evaluation for descriptor", + "expect": "fail", + "reason": "Safari does not read the address property of the descriptor." + }, + { + "browser": "safari", + "subtest": "Zero initial", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Non-zero initial", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Stray argument", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Memory with address parameter omitted", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Memory with i32 address constructor", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Memory with string value for initial", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Memory with boolean value for initial", + "expect": "fail", + "reason": "Safari does not report the expected address type from Memory.type()." + }, + { + "browser": "safari", + "subtest": "Unknown memory address", + "expect": "fail", + "reason": "Safari accepts an unknown descriptor address instead of throwing TypeError." + } + ], + "memory/grow-memory64.any.js": [ + { + "browser": "safari", + "subtest": "Zero initial (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Non-zero initial (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Zero initial with respected maximum (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Zero initial with respected maximum grown twice (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Zero initial growing too much (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Out-of-range i64 argument: -1n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Out-of-range i64 argument: 18446744073709551616n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Out-of-range i64 argument: \"0x10000000000000000\"", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + } + ], + "memory/grow.any.js": [ + { + "browser": "firefox", + "subtest": "Growing shared memory does not detach old buffer", + "expect": "fail", + "reason": "The old buffer after shared memory growth is not frozen." + } + ], + "module/customSections.any.js": [ + { + "browser": "firefox", + "subtest": "Custom sections with U+FFFD", + "expect": "fail", + "reason": "A custom-section name lookup returns a match where the test expects none." + } + ], + "table/constructor-memory64.any.js": [ + { + "browser": "safari", + "subtest": "Initial value exceeds maximum (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Basic (zero, i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Basic (non-zero, i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Table with i64 address constructor", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Table with string value for initial (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Table with boolean value for initial (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Table with string value for maximum (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Table with boolean value for maximum (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + } + ], + "table/constructor.any.js": [ + { + "browser": "safari", + "subtest": "Order of evaluation for descriptor", + "expect": "fail", + "reason": "Safari does not read the address property of the descriptor." + }, + { + "browser": "safari", + "subtest": "Unknown table address", + "expect": "fail", + "reason": "Safari accepts an unknown descriptor address instead of throwing TypeError." + } + ], + "table/get-set.any.js": [ + { + "browser": "chrome", + "subtest": "Arguments for anyfunc table set", + "expect": "fail", + "reason": "Table.set rejects an explicit undefined value for an anyfunc table." + }, + { + "browser": "firefox", + "subtest": "Arguments for anyfunc table set", + "expect": "fail", + "reason": "Table.set rejects an explicit undefined value for an anyfunc table." + }, + { + "browser": "safari", + "subtest": "Basic (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Growing (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Setting out-of-bounds (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Getting out-of-range argument (i64): -1n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Setting out-of-range argument (i64): -1n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Getting out-of-range argument (i64): 18446744073709551616n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Setting out-of-range argument (i64): 18446744073709551616n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Getting out-of-range argument (i64): \"0x10000000000000000\"", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Setting out-of-range argument (i64): \"0x10000000000000000\"", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Arguments for anyfunc table set", + "expect": "fail", + "reason": "Table.set rejects an explicit undefined value for an anyfunc table." + } + ], + "table/grow-memory64.any.js": [ + { + "browser": "chrome", + "subtest": "Basic i64", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "chrome", + "subtest": "Reached maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "chrome", + "subtest": "Exceeded maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "firefox", + "subtest": "Basic i64", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "firefox", + "subtest": "Reached maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "firefox", + "subtest": "Exceeded maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "safari", + "subtest": "Basic i64", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Reached maximum (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Exceeded maximum (i64)", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Out-of-range i64 argument: -1n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Out-of-range i64 argument: 18446744073709551616n", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + }, + { + "browser": "safari", + "subtest": "Out-of-range i64 argument: \"0x10000000000000000\"", + "expect": "fail", + "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." + } + ], + "table/grow.any.js": [ + { + "browser": "chrome", + "subtest": "Grow with undefined argument", + "expect": "fail", + "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." + }, + { + "browser": "firefox", + "subtest": "Grow with undefined argument", + "expect": "fail", + "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." + }, + { + "browser": "safari", + "subtest": "Grow with undefined argument", + "expect": "fail", + "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." + } + ] +} diff --git a/test/js-api/run.py b/test/js-api/run.py new file mode 100755 index 0000000000..5cfd1e975c --- /dev/null +++ b/test/js-api/run.py @@ -0,0 +1,495 @@ +#!/usr/bin/env python3 +"""Run the Wasm JS API tests in a browser using Selenium.""" + +import argparse +import json +import re +from collections import Counter +from contextlib import nullcontext +from dataclasses import dataclass +from functools import cache +from html import escape +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from threading import Thread +from urllib.parse import quote, urljoin, urlsplit + +SUITE = Path(__file__).resolve().parent +MANIFEST = SUITE / "expectations.json" +PREFIX = "/wasm/jsapi/" +HARNESS = "/resources/testharness.js" +BROWSERS = ("chrome", "firefox", "safari") +BROWSER_GLOBALS = ("window", "dedicatedworker") +# Match the timeout values in testharness.js. +HARNESS_TIMEOUT_SECONDS = {"normal": 10, "long": 60} +WEBDRIVER_GRACE_SECONDS = 5 +# Manifest rules without a subtest name apply to the whole browser case. +WHOLE_CASE = None + +REPORTER = """\ +setup({output: false}); +globalThis.wasmTestResult = new Promise(resolve => { + let finished = false; + function report(result) { + if (finished) return; + finished = true; + document.getElementById("results").textContent = JSON.stringify(result, null, 2); + resolve(result); + } + + add_completion_callback((tests, harness) => { + const harnessStatuses = ["OK", "ERROR", "TIMEOUT", "PRECONDITION_FAILED"]; + const subtestStatuses = ["PASS", "FAIL", "TIMEOUT", "NOTRUN", "PRECONDITION_FAILED"]; + report({ + status: harnessStatuses[harness.status] ?? `UNKNOWN (${harness.status})`, + message: harness.message, + subtests: tests.map(test => ({ + name: test.name, + status: subtestStatuses[test.status] ?? `UNKNOWN (${test.status})`, + message: test.message, + })), + }); + }); + + // A missing classic script can leave the harness with only partial results. + addEventListener("error", event => { + if (event.target instanceof HTMLScriptElement) { + report({status: "ERROR", message: `Could not load ${event.target.src}`, subtests: []}); + } + }, true); +}); +""" + + +@dataclass(frozen=True) +class BrowserCase: + name: str + context: str + page_path: str + timeout_seconds: int + + +def test_metadata(path): + globals_ = set(BROWSER_GLOBALS) + helpers = [] + timeout = "normal" + with path.open(encoding="utf-8-sig") as source: + for line in source: + line = line.strip() + if line and not line.startswith("//"): + break + if not line.startswith("// META:"): + continue + match = re.fullmatch(r"// META:\s*(\w+)=(.+)", line) + if not match: + raise ValueError(f"{path.name}: invalid metadata: {line}") + key, value = match.groups() + if key == "global": + globals_ = {name.strip() for name in value.split(",")} + # Accept globals used by WPT even when this runner cannot launch them. + unknown = globals_ - {*BROWSER_GLOBALS, "jsshell", "shadowrealm"} + if unknown: + raise ValueError( + f"{path.name}: unsupported globals: {', '.join(sorted(unknown))}" + ) + elif key == "script": + helpers.append(value) + elif key == "timeout" and value == "long": + timeout = value + else: + raise ValueError(f"{path.name}: unsupported metadata: {line}") + return globals_, helpers, timeout + + +def discover_suite(): + sources = {path.relative_to(SUITE).as_posix(): path for path in SUITE.rglob("*.js")} + scripts = {PREFIX + quote(name): path for name, path in sources.items()} + scripts[HARNESS] = SUITE.parent / "harness" / "testharness.js" + tests = {name: path for name, path in sources.items() if name.endswith(".any.js")} + return scripts, tests + + +def generate_test_pages(scripts, tests, selected, contexts, metadata_for): + unknown = selected - tests.keys() + if unknown: + raise ValueError(f"Unknown tests: {', '.join(sorted(unknown))}") + pages = {} + cases = [] + for name in sorted(selected or tests): + url = PREFIX + quote(name) + stem = url.removesuffix(".js") + globals_, helpers, timeout_mode = metadata_for(tests[name]) + sources = [urljoin(url, helper) for helper in helpers] + for source in sources: + if source not in scripts: + raise ValueError(f"{name}: missing helper script {source}") + sources.append(url) + for context in contexts: + if context not in globals_: + continue + if context == "window": + page = stem + ".html" + body = "\n".join( + f'' for source in sources + ) + else: + page = stem + ".worker.html" + worker = stem + ".worker.js" + imports = ", ".join(map(json.dumps, [HARNESS, *sources])) + # The worker signals completion explicitly. Its parent reports the results. + pages[worker] = ( + "text/javascript", + f"importScripts({imports});\ndone();", + ) + body = f"" + pages[page] = ( + "text/html", + f""" + + +{escape(name)} ({context}) +
Running {escape(name)} ({context})…
+ + +{body} +""", + ) + cases.append( + BrowserCase( + name=name, + context=context, + page_path=page, + timeout_seconds=HARNESS_TIMEOUT_SECONDS[timeout_mode], + ) + ) + links = "\n".join( + f'
  • {escape(case.name)} ({case.context})
  • ' + for case in cases + ) + pages["/"] = ( + "text/html", + f""" + +Wasm JS API tests + +""", + ) + return pages, cases + + +def make_server(scripts, pages): + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + path = urlsplit(self.path).path + if path in pages: + content_type, content = pages[path] + content = content.encode("utf-8") + elif path in scripts: + content_type, content = "text/javascript", scripts[path].read_bytes() + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", content_type + "; charset=utf-8") + self.send_header("Content-Length", str(len(content))) + # Cross-origin isolation makes SharedArrayBuffer available to the tests. + self.send_header("Cross-Origin-Opener-Policy", "same-origin") + self.send_header("Cross-Origin-Embedder-Policy", "require-corp") + self.end_headers() + self.wfile.write(content) + + def log_message(self, format, *args): + pass + + return ThreadingHTTPServer(("127.0.0.1", 0), Handler) + + +def unique_json_keys(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate key: {key}") + result[key] = value + return result + + +def load_expectations(path, tests, browser, metadata_for): + by_test = json.loads( + path.read_text(encoding="utf-8"), object_pairs_hook=unique_json_keys + ) + if not isinstance(by_test, dict): + raise ValueError("Expected an object keyed by test path") + + rules = {} + required = {"browser", "expect", "reason"} + allowed = required | {"context", "subtest"} + for name, entries in by_test.items(): + if name not in tests: + raise ValueError(f"Unknown test: {name}") + if not isinstance(entries, list): + raise ValueError(f"{name}: expected a list of rules") + globals_, _, _ = metadata_for(tests[name]) + supported = [context for context in BROWSER_GLOBALS if context in globals_] + for index, entry in enumerate(entries, 1): + label = f"{name} rule {index}" + if ( + not isinstance(entry, dict) + or not required <= entry.keys() <= allowed + or not all( + isinstance(value, str) and value.strip() for value in entry.values() + ) + ): + raise ValueError( + f"{label}: provide browser, expect, reason and optional context or subtest" + ) + product, expect = entry["browser"], entry["expect"] + subtest = entry.get("subtest", WHOLE_CASE) + if product not in BROWSERS or expect not in ("fail", "skip"): + raise ValueError(f"{label}: invalid browser or expectation") + if expect == "skip" and subtest is not WHOLE_CASE: + raise ValueError(f"{label}: skip applies to a whole test case") + requested_context = entry.get("context") + contexts = [ + context + for context in supported + if requested_context is None or context == requested_context + ] + if not contexts: + raise ValueError(f"{label}: no supported browser context") + for context in contexts: + case_rules = rules.setdefault((product, name, context), {}) + if ( + subtest in case_rules + or WHOLE_CASE in case_rules + or (subtest is WHOLE_CASE and case_rules) + ): + raise ValueError( + f"{label}: overlapping rules for {product} [{context}]" + ) + case_rules[subtest] = (expect, entry["reason"]) + + return { + (name, context): case_rules + for (product, name, context), case_rules in rules.items() + if product == browser + } + + +def create_driver(browser): + try: + from selenium import webdriver + from selenium.common.exceptions import WebDriverException + except ModuleNotFoundError as error: + if error.name != "selenium": + raise + raise SystemExit( + "Install Selenium with python -m pip install selenium" + ) from error + + driver_class, options_class, headless = { + "chrome": (webdriver.Chrome, webdriver.ChromeOptions, "--headless"), + "firefox": (webdriver.Firefox, webdriver.FirefoxOptions, "-headless"), + "safari": (webdriver.Safari, webdriver.SafariOptions, None), + }[browser] + options = options_class() + if headless: + options.add_argument(headless) + + try: + return driver_class(options=options) + except WebDriverException as error: + raise SystemExit(f"Could not start {browser}: {error.msg}") from error + + +def read_result(driver, url, timeout_seconds): + from selenium.common.exceptions import WebDriverException + + try: + # Give the harness time to report its own timeout through WebDriver. + webdriver_timeout = timeout_seconds + WEBDRIVER_GRACE_SECONDS + driver.set_page_load_timeout(webdriver_timeout) + driver.set_script_timeout(webdriver_timeout) + driver.get(url) + result = driver.execute_async_script("""\ +const done = arguments[0]; +Promise.resolve(window.wasmTestResult ?? null).then(done); +""") + if result is None: + raise ValueError("Test page did not initialize the harness") + if result["status"] == "OK" and not result["subtests"]: + raise ValueError("No subtests ran") + return result + except (WebDriverException, ValueError) as error: + message = error.msg if isinstance(error, WebDriverException) else str(error) + return {"status": "ERROR", "message": message, "subtests": []} + + +def evaluate_result(result, rules): + """Apply failure expectations after the harness has completed successfully.""" + subtests = result["subtests"] + failures = [test for test in subtests if test["status"] != "PASS"] + diagnostics = [ + f"{test['status']} {test['name']}: {test['message']}" for test in failures + ] + if result["status"] != "OK": + return "FAIL", [f"{result['status']}: {result['message']}", *diagnostics] + # Only a subtest with status FAIL can satisfy a failure expectation. + if WHOLE_CASE in rules: + _, reason = rules[WHOLE_CASE] + if not failures: + return "XPASS", [f"Expected a failure: {reason}"] + if all(test["status"] == "FAIL" for test in failures): + return "XFAIL", [reason, *diagnostics] + return "FAIL", diagnostics + + by_name = {test["name"]: test for test in subtests} + missing = rules.keys() - by_name.keys() + unexpected = [ + test + for test in failures + if test["name"] not in rules or test["status"] != "FAIL" + ] + expected_failures_that_passed = [ + name for name in rules if name in by_name and by_name[name]["status"] == "PASS" + ] + diagnostics += [f"Expected subtest missing: {name}" for name in sorted(missing)] + diagnostics += [ + f"XPASS {name}: {rules[name][1]}" for name in expected_failures_that_passed + ] + # Missing expected subtests and unexpected failures take precedence over XPASS. + if missing or unexpected: + return "FAIL", diagnostics + if expected_failures_that_passed: + return "XPASS", diagnostics + if rules: + return "XFAIL", [ + f"{name}: {reason}" for name, (_, reason) in rules.items() + ] + diagnostics + return "PASS", [] + + +def run_browser(browser, base_url, cases, expectations, json_path): + results = [] + counts = Counter() + selected = [ + (case, expectations.get((case.name, case.context), {})) for case in cases + ] + has_runnable_cases = any( + rules.get(WHOLE_CASE, (None, None))[0] != "skip" for _, rules in selected + ) + with create_driver(browser) if has_runnable_cases else nullcontext() as driver: + version = ( + driver.capabilities.get("browserVersion", "unknown") if driver else None + ) + print( + f"{browser}: {len(cases)} selected cases" + + (f" (version {version})" if version else ""), + flush=True, + ) + for case, rules in selected: + expect, reason = rules.get(WHOLE_CASE, (None, None)) + if expect == "skip": + result = {"status": "SKIP", "message": reason, "subtests": []} + outcome, diagnostics = "SKIP", [reason] + else: + result = read_result( + driver, base_url + case.page_path, case.timeout_seconds + ) + outcome, diagnostics = evaluate_result(result, rules) + counts[outcome] += 1 + print( + f"{outcome} {case.name} [{case.context}] ({len(result['subtests'])} subtests)", + flush=True, + ) + for diagnostic in diagnostics: + print(f" {diagnostic}", flush=True) + results.append( + { + "test": case.name, + "context": case.context, + **result, + "outcome": outcome, + "diagnostics": diagnostics, + } + ) + + if json_path: + report = {"browser": browser, "version": version, "results": results} + json_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print( + ", ".join( + f"{counts[status]} {status}" + for status in ("PASS", "FAIL", "XFAIL", "XPASS", "SKIP") + ), + flush=True, + ) + return int(counts["FAIL"] > 0 or counts["XPASS"] > 0) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--browser", choices=BROWSERS, default="firefox") + parser.add_argument( + "--context", + choices=BROWSER_GLOBALS, + action="append", + help="Browser global to run, repeatable (default: both)", + ) + parser.add_argument("--json", type=Path, help="Write a JSON report to this file") + parser.add_argument( + "--manifest", + type=Path, + default=MANIFEST, + help="Expectations file for Selenium runs (default: test/js-api/expectations.json)", + ) + parser.add_argument( + "--serve", action="store_true", help="Serve test pages for manual use" + ) + parser.add_argument( + "tests", nargs="*", help="Test paths relative to test/js-api (default: all)" + ) + args = parser.parse_args() + + contexts = tuple( + context + for context in BROWSER_GLOBALS + if not args.context or context in args.context + ) + scripts, tests = discover_suite() + metadata_for = cache(test_metadata) + try: + pages, cases = generate_test_pages( + scripts, tests, set(args.tests), contexts, metadata_for + ) + except ValueError as error: + parser.error(str(error)) + if not cases: + parser.error("No browser cases matched the selection") + if not args.serve: + try: + # Validate the full manifest even when the run selects only a few cases. + expectations = load_expectations( + args.manifest, tests, args.browser, metadata_for + ) + except (OSError, ValueError) as error: + parser.error(f"{args.manifest}: {error}") + + with make_server(scripts, pages) as server: + base_url = f"http://127.0.0.1:{server.server_port}" + if args.serve: + print(base_url, flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + return 0 + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + return run_browser(args.browser, base_url, cases, expectations, args.json) + finally: + server.shutdown() + thread.join() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/test/sync-js-api.py b/test/sync-js-api.py deleted file mode 100755 index 454d69df6b..0000000000 --- a/test/sync-js-api.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python3 - -import glob -import os -import shutil -import subprocess - -LOCAL_FILES = [ - "LICENSE.md", - "README.md", - - # Currently doesn't pass the stability checker in wpt. - "limits.any.js", -] - - -def copy_from_local(local_dir, out): - for local_file in LOCAL_FILES: - shutil.copy(os.path.join(local_dir, local_file), out) - - -def copy_from_upstream(upstream, out): - upstream = os.path.abspath(upstream) - paths = glob.glob(os.path.join(upstream, "**", "*.js"), recursive=True) - for path in paths: - relpath = os.path.relpath(path, upstream) - - # Tests for proposals that have not merged here yet. - if ".tentative" in relpath: - continue - - # Requires `fetch()` and various wpt infrastructure. - if os.path.basename(relpath) == "idlharness.any.js": - continue - - dest = os.path.join(out, relpath) - os.makedirs(os.path.dirname(dest), exist_ok=True) - shutil.copy(path, dest) - - -def main(upstream): - local_dir = os.path.join("test", "js-api") - scratch = os.path.join("test", "js-api-temp") - os.mkdir(scratch) - copy_from_local(local_dir, scratch) - copy_from_upstream(os.path.join(upstream, "wasm", "jsapi"), scratch) - shutil.rmtree(local_dir) - os.rename(scratch, local_dir) - subprocess.check_call(["git", "add", local_dir]) - - -if __name__ == "__main__": - import sys - main(*sys.argv[1:]) From 11c1d499f489c3239f82cdafbe4acd80fbb19e9a Mon Sep 17 00:00:00 2001 From: Ryan Hunt Date: Mon, 23 Nov 2026 22:07:21 -0600 Subject: [PATCH 2/3] [js-api] Pinned browser versions and re-org --- .github/workflows/ci-js-api.yml | 211 +++++++++- test/js-api/README.md | 67 ++- test/js-api/expectations.json | 454 --------------------- test/js-api/scripts/browser-versions.json | 5 + test/js-api/scripts/expectations.json | 260 ++++++++++++ test/js-api/{ => scripts}/run.py | 93 +++-- test/js-api/scripts/update-expectations.py | 180 ++++++++ 7 files changed, 749 insertions(+), 521 deletions(-) delete mode 100644 test/js-api/expectations.json create mode 100644 test/js-api/scripts/browser-versions.json create mode 100644 test/js-api/scripts/expectations.json rename test/js-api/{ => scripts}/run.py (88%) create mode 100755 test/js-api/scripts/update-expectations.py diff --git a/.github/workflows/ci-js-api.yml b/.github/workflows/ci-js-api.yml index 2bef2752d7..7c924c8100 100644 --- a/.github/workflows/ci-js-api.yml +++ b/.github/workflows/ci-js-api.yml @@ -15,14 +15,56 @@ on: - test/harness/testharness.js - test/js-api/** + schedule: + - cron: '23 6 * * 1' + workflow_dispatch: + inputs: + refresh: + description: Test current releases and update the browser bump PR from the default branch + type: boolean + default: false + chrome-version: + description: Candidate Chrome version (blank uses the pin) + type: string + firefox-version: + description: Candidate Firefox version (blank uses the pin) + type: string + safari-version: + description: Candidate Safari version, or "installed" to accept the hosted version + type: string permissions: contents: read +defaults: + run: + shell: bash + jobs: + refresh-schedule: + name: Check browser refresh schedule + if: github.event_name == 'schedule' + runs-on: ubuntu-24.04 + timeout-minutes: 2 + permissions: {} + outputs: + due: ${{ steps.schedule.outputs.due }} + steps: + - name: Check four-week cadence + id: schedule + run: | + # Cron wakes the workflow weekly. Count UTC weeks from a fixed Monday. + anchor=$(date -u -d '2026-11-23' +%s) + now=$(date -u +%s) + if (( now >= anchor && (now - anchor) / 604800 % 4 == 0 )); then + echo 'due=true' >> "$GITHUB_OUTPUT" + fi + js-api: name: JS API (${{ matrix.browser }}) + needs: refresh-schedule + if: ${{ !cancelled() && (github.event_name != 'schedule' || needs.refresh-schedule.outputs.due == 'true') }} runs-on: ${{ matrix.os }} timeout-minutes: 15 strategy: @@ -31,10 +73,16 @@ jobs: include: - browser: firefox os: ubuntu-24.04 + version: ${{ inputs.firefox-version }} - browser: chrome os: ubuntu-24.04 + version: ${{ inputs.chrome-version }} - browser: safari os: macos-15 + version: ${{ inputs.safari-version }} + env: + BROWSER: ${{ matrix.browser }} + REFRESH: ${{ github.event_name == 'schedule' || inputs.refresh }} steps: - name: Checkout repo uses: actions/checkout@v4 @@ -46,13 +94,65 @@ jobs: python-version: '3.14' - name: Install Selenium run: python -m pip install selenium==4.53.0 + - name: Select browser version + id: browser + env: + OVERRIDE: ${{ matrix.version }} + run: | + pin=$(jq -er --arg browser "$BROWSER" '.[$browser]' test/js-api/scripts/browser-versions.json) + if [[ "$REFRESH" == true ]]; then + case "$BROWSER" in + chrome) + latest=$(curl -fsSL --retry 3 --max-time 30 https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_STABLE) + ;; + firefox) + latest=$(curl -fsSL --retry 3 --max-time 30 https://product-details.mozilla.org/1.0/firefox_versions.json | jq -er '.LATEST_FIREFOX_VERSION') + ;; + safari) + latest=installed + ;; + esac + if [[ "$latest" == installed && "$BROWSER" == safari ]]; then + version=installed + elif [[ "$latest" =~ ^[0-9]+(\.[0-9]+)+$ ]]; then + # A release feed can lag behind the version already tested. + version=$(printf '%s\n%s\n' "$pin" "$latest" | sort -V | tail -n 1) + else + echo "Could not resolve a stable $BROWSER version" >&2 + exit 1 + fi + elif [[ -n "$OVERRIDE" ]]; then + version=$OVERRIDE + elif [[ "$BROWSER" == safari ]]; then + # The hosted runner supplies Safari. Normal CI checks only its major version. + version=${pin%%.*} + else + version=$pin + fi + if [[ ! "$version" =~ ^[0-9]+(\.[0-9]+)*$ && ( "$BROWSER" != safari || "$version" != installed ) ]]; then + echo "Invalid $BROWSER version" >&2 + exit 1 + fi + printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT" - name: Enable Safari Remote Automation if: matrix.browser == 'safari' run: sudo /usr/bin/safaridriver --enable - name: Run JS API tests env: - BROWSER: ${{ matrix.browser }} - run: python test/js-api/run.py --browser "$BROWSER" --json wasm-js-api.json + BROWSER_VERSION: ${{ steps.browser.outputs.version }} + SE_SKIP_DRIVER_IN_PATH: 'true' + run: | + args=(--browser "$BROWSER" --json wasm-js-api.json) + if [[ "$BROWSER" != safari || "$BROWSER_VERSION" != installed ]]; then + args+=(--browser-version "$BROWSER_VERSION") + fi + status=0 + python test/js-api/scripts/run.py "${args[@]}" || status=$? + # Candidate test failures are expected. The PR job validates the report. + if [[ "$REFRESH" == true && "$status" == 1 && -s wasm-js-api.json ]]; then + exit 0 + fi + exit "$status" - name: Upload browser report if: ${{ !cancelled() && hashFiles('wasm-js-api.json') != '' }} uses: actions/upload-artifact@v4 @@ -75,3 +175,110 @@ jobs: print('| ---: | ---: | ---: | ---: | ---: |') print('| ' + ' | '.join(str(counts[outcome]) for outcome in ('PASS', 'FAIL', 'XFAIL', 'XPASS', 'SKIP')) + ' |') PY + + propose-browser-update: + name: Propose browser update + if: ${{ (github.event_name == 'schedule' || inputs.refresh) && github.ref_name == github.event.repository.default_branch }} + needs: js-api + runs-on: ubuntu-24.04 + timeout-minutes: 5 + concurrency: js-api-browser-update + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout tested commit + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Download browser reports + uses: actions/download-artifact@v4 + with: + pattern: wasm-js-api-* + path: ${{ runner.temp }}/js-api-reports + - name: Update pins and expectations + env: + REPORTS: ${{ runner.temp }}/js-api-reports + BASE_BRANCH: ${{ github.event.repository.default_branch }} + run: | + if [[ "$(git ls-remote origin "refs/heads/$BASE_BRANCH" | cut -f1)" != "$GITHUB_SHA" ]]; then + echo "The default branch moved during testing. Run the refresh again." >&2 + exit 1 + fi + proposal=$(mktemp -d) + pins=test/js-api/scripts/browser-versions.json + manifest=test/js-api/scripts/expectations.json + cp "$pins" "$proposal/pins.json" + cp "$manifest" "$proposal/manifest.json" + for browser in chrome firefox safari; do + report="$REPORTS/wasm-js-api-$browser/wasm-js-api.json" + pin=$(jq -er --arg browser "$browser" '.[$browser]' "$pins") + version=$(jq -er --arg browser "$browser" \ + 'select(.browser == $browser) | .version | select(test("^[0-9]+([.][0-9]+)+$"))' "$report") + python3 test/js-api/scripts/update-expectations.py --require-complete \ + --manifest "$proposal/manifest.json" "$report" > "$proposal/manifest.next.json" + if [[ "$version" == "$pin" ]]; then + continue + fi + if [[ "$(printf '%s\n%s\n' "$pin" "$version" | sort -V | tail -n 1)" != "$version" ]]; then + echo "$browser $version is older than the tested pin $pin" >&2 + exit 1 + fi + jq --arg browser "$browser" --arg version "$version" '.[$browser] = $version' \ + "$proposal/pins.json" > "$proposal/pins.next.json" + mv "$proposal/pins.next.json" "$proposal/pins.json" + mv "$proposal/manifest.next.json" "$proposal/manifest.json" + printf -- '- %s %s → %s\n' "$browser" "$pin" "$version" >> "$GITHUB_STEP_SUMMARY" + done + cp "$proposal/pins.json" "$pins" + cp "$proposal/manifest.json" "$manifest" + - name: Open or update browser bump PR + env: + GH_TOKEN: ${{ github.token }} + BASE_BRANCH: ${{ github.event.repository.default_branch }} + run: | + branch=automation/js-api-browser-versions + ref="refs/heads/$branch" + previous=$(git ls-remote origin "$ref" | cut -f1) + lease="--force-with-lease=$ref:$previous" + git add -- test/js-api/scripts/browser-versions.json test/js-api/scripts/expectations.json + if git diff --cached --quiet; then + if [[ -n "$previous" ]]; then + gh auth setup-git + git push "$lease" origin ":$ref" + fi + echo "No browser updates to propose." + exit 0 + fi + + pr=$(gh api --method GET "repos/$GITHUB_REPOSITORY/pulls" \ + -f state=open -f base="$BASE_BRANCH" \ + -f head="${GITHUB_REPOSITORY%%/*}:$branch" --jq '.[0].number // empty') + if [[ -n "$pr" && -n "$previous" ]]; then + previous_tree=$(gh api "repos/$GITHUB_REPOSITORY/git/commits/$previous" --jq .tree.sha) + if [[ "$(git write-tree)" == "$previous_tree" ]]; then + echo "PR #$pr already contains this update." + exit 0 + fi + fi + + title='[js-api] Bump CI browser versions' + body_file=$(mktemp) + cat > "$body_file" < scripts/expectations.json` +to update expectations based on a test run. diff --git a/test/js-api/expectations.json b/test/js-api/expectations.json deleted file mode 100644 index 057c5727fc..0000000000 --- a/test/js-api/expectations.json +++ /dev/null @@ -1,454 +0,0 @@ -{ - "exception/constructor.tentative.any.js": [ - { - "browser": "firefox", - "subtest": "length", - "expect": "fail", - "reason": "WebAssembly.Exception.length is 1 instead of 2." - }, - { - "browser": "safari", - "subtest": "length", - "expect": "fail", - "reason": "WebAssembly.Exception.length is 1 instead of 2." - } - ], - "exception/getArg.tentative.any.js": [ - { - "browser": "safari", - "subtest": "Getting out-of-range argument", - "expect": "fail", - "reason": "Exception.getArg throws RangeError instead of TypeError for an out-of-range argument." - } - ], - "global/value-get-set.any.js": [ - { - "browser": "firefox", - "subtest": "Calling setter without argument", - "expect": "fail", - "reason": "The WebAssembly.Global value setter rejects a call with no argument." - }, - { - "browser": "safari", - "subtest": "Calling setter without argument", - "expect": "fail", - "reason": "The WebAssembly.Global value setter rejects a call with no argument." - } - ], - "instance/constructor-caching.any.js": [ - { - "browser": "safari", - "context": "window", - "subtest": "instance/constructor-caching.any.js (window)", - "expect": "fail", - "reason": "The cached and original WebAssembly.Global objects have different identities." - }, - { - "browser": "safari", - "context": "dedicatedworker", - "subtest": "constructor-caching", - "expect": "fail", - "reason": "The cached and original WebAssembly.Global objects have different identities." - } - ], - "interface.any.js": [ - { - "browser": "firefox", - "subtest": "WebAssembly.Table.set: length", - "expect": "fail", - "reason": "WebAssembly.Table.prototype.set.length is 2 instead of 1." - } - ], - "memory/constructor-memory64.any.js": [ - { - "browser": "safari", - "subtest": "Initial value exceeds maximum (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Zero initial (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Non-zero initial (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Memory with i64 address constructor", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Memory with string value for initial (i64)", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Memory with boolean value for initial (i64)", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - } - ], - "memory/constructor.any.js": [ - { - "browser": "safari", - "subtest": "Order of evaluation for descriptor", - "expect": "fail", - "reason": "Safari does not read the address property of the descriptor." - }, - { - "browser": "safari", - "subtest": "Zero initial", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Non-zero initial", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Stray argument", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Memory with address parameter omitted", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Memory with i32 address constructor", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Memory with string value for initial", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Memory with boolean value for initial", - "expect": "fail", - "reason": "Safari does not report the expected address type from Memory.type()." - }, - { - "browser": "safari", - "subtest": "Unknown memory address", - "expect": "fail", - "reason": "Safari accepts an unknown descriptor address instead of throwing TypeError." - } - ], - "memory/grow-memory64.any.js": [ - { - "browser": "safari", - "subtest": "Zero initial (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Non-zero initial (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Zero initial with respected maximum (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Zero initial with respected maximum grown twice (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Zero initial growing too much (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Out-of-range i64 argument: -1n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Out-of-range i64 argument: 18446744073709551616n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Out-of-range i64 argument: \"0x10000000000000000\"", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - } - ], - "memory/grow.any.js": [ - { - "browser": "firefox", - "subtest": "Growing shared memory does not detach old buffer", - "expect": "fail", - "reason": "The old buffer after shared memory growth is not frozen." - } - ], - "module/customSections.any.js": [ - { - "browser": "firefox", - "subtest": "Custom sections with U+FFFD", - "expect": "fail", - "reason": "A custom-section name lookup returns a match where the test expects none." - } - ], - "table/constructor-memory64.any.js": [ - { - "browser": "safari", - "subtest": "Initial value exceeds maximum (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Basic (zero, i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Basic (non-zero, i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Table with i64 address constructor", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Table with string value for initial (i64)", - "expect": "fail", - "reason": "Safari reports table length as a number for an i64 table." - }, - { - "browser": "safari", - "subtest": "Table with boolean value for initial (i64)", - "expect": "fail", - "reason": "Safari reports table length as a number for an i64 table." - }, - { - "browser": "safari", - "subtest": "Table with string value for maximum (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Table with boolean value for maximum (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - } - ], - "table/constructor.any.js": [ - { - "browser": "safari", - "subtest": "Order of evaluation for descriptor", - "expect": "fail", - "reason": "Safari does not read the address property of the descriptor." - }, - { - "browser": "safari", - "subtest": "Unknown table address", - "expect": "fail", - "reason": "Safari accepts an unknown descriptor address instead of throwing TypeError." - } - ], - "table/get-set.any.js": [ - { - "browser": "chrome", - "subtest": "Arguments for anyfunc table set", - "expect": "fail", - "reason": "Table.set rejects an explicit undefined value for an anyfunc table." - }, - { - "browser": "firefox", - "subtest": "Arguments for anyfunc table set", - "expect": "fail", - "reason": "Table.set rejects an explicit undefined value for an anyfunc table." - }, - { - "browser": "safari", - "subtest": "Basic (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Growing (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Setting out-of-bounds (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Getting out-of-range argument (i64): -1n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Setting out-of-range argument (i64): -1n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Getting out-of-range argument (i64): 18446744073709551616n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Setting out-of-range argument (i64): 18446744073709551616n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Getting out-of-range argument (i64): \"0x10000000000000000\"", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Setting out-of-range argument (i64): \"0x10000000000000000\"", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Arguments for anyfunc table set", - "expect": "fail", - "reason": "Table.set rejects an explicit undefined value for an anyfunc table." - } - ], - "table/grow-memory64.any.js": [ - { - "browser": "chrome", - "subtest": "Basic i64", - "expect": "fail", - "reason": "The test calls nulls(), which its declared helpers do not define." - }, - { - "browser": "chrome", - "subtest": "Reached maximum (i64)", - "expect": "fail", - "reason": "The test calls nulls(), which its declared helpers do not define." - }, - { - "browser": "chrome", - "subtest": "Exceeded maximum (i64)", - "expect": "fail", - "reason": "The test calls nulls(), which its declared helpers do not define." - }, - { - "browser": "firefox", - "subtest": "Basic i64", - "expect": "fail", - "reason": "The test calls nulls(), which its declared helpers do not define." - }, - { - "browser": "firefox", - "subtest": "Reached maximum (i64)", - "expect": "fail", - "reason": "The test calls nulls(), which its declared helpers do not define." - }, - { - "browser": "firefox", - "subtest": "Exceeded maximum (i64)", - "expect": "fail", - "reason": "The test calls nulls(), which its declared helpers do not define." - }, - { - "browser": "safari", - "subtest": "Basic i64", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Reached maximum (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Exceeded maximum (i64)", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Out-of-range i64 argument: -1n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Out-of-range i64 argument: 18446744073709551616n", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - }, - { - "browser": "safari", - "subtest": "Out-of-range i64 argument: \"0x10000000000000000\"", - "expect": "fail", - "reason": "Safari rejects the BigInt argument in this i64 memory or table operation." - } - ], - "table/grow.any.js": [ - { - "browser": "chrome", - "subtest": "Grow with undefined argument", - "expect": "fail", - "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." - }, - { - "browser": "firefox", - "subtest": "Grow with undefined argument", - "expect": "fail", - "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." - }, - { - "browser": "safari", - "subtest": "Grow with undefined argument", - "expect": "fail", - "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." - } - ] -} diff --git a/test/js-api/scripts/browser-versions.json b/test/js-api/scripts/browser-versions.json new file mode 100644 index 0000000000..30417d3937 --- /dev/null +++ b/test/js-api/scripts/browser-versions.json @@ -0,0 +1,5 @@ +{ + "chrome": "157.0.8103.78", + "firefox": "160.0", + "safari": "27.2" +} diff --git a/test/js-api/scripts/expectations.json b/test/js-api/scripts/expectations.json new file mode 100644 index 0000000000..f10dd75f88 --- /dev/null +++ b/test/js-api/scripts/expectations.json @@ -0,0 +1,260 @@ +{ + "exception/constructor.tentative.any.js": [ + { + "browser": "firefox", + "subtest": "length", + "expect": "fail", + "reason": "WebAssembly.Exception.length is 1 instead of 2." + }, + { + "browser": "safari", + "subtest": "length", + "expect": "fail", + "reason": "WebAssembly.Exception.length is 1 instead of 2." + } + ], + "exception/getArg.tentative.any.js": [ + { + "browser": "safari", + "subtest": "Getting out-of-range argument", + "expect": "fail", + "reason": "Exception.getArg throws RangeError instead of TypeError for an out-of-range argument." + } + ], + "global/value-get-set.any.js": [ + { + "browser": "firefox", + "subtest": "Calling setter without argument", + "expect": "fail", + "reason": "The WebAssembly.Global value setter rejects a call with no argument." + }, + { + "browser": "safari", + "subtest": "Calling setter without argument", + "expect": "fail", + "reason": "The WebAssembly.Global value setter rejects a call with no argument." + } + ], + "instance/constructor-caching.any.js": [ + { + "browser": "safari", + "context": "window", + "subtest": "instance/constructor-caching.any.js (window)", + "expect": "fail", + "reason": "The cached and original WebAssembly.Global objects have different identities." + }, + { + "browser": "safari", + "context": "dedicatedworker", + "subtest": "constructor-caching", + "expect": "fail", + "reason": "The cached and original WebAssembly.Global objects have different identities." + } + ], + "interface.any.js": [ + { + "browser": "firefox", + "subtest": "WebAssembly.Table.set: length", + "expect": "fail", + "reason": "WebAssembly.Table.prototype.set.length is 2 instead of 1." + } + ], + "js-string/basic.any.js": [ + { + "browser": "safari", + "subtest": "Incorrect types", + "expect": "fail", + "reason": "Safari validates a module that imports a JS string builtin with an incorrect type." + } + ], + "memory/constructor.any.js": [ + { + "browser": "safari", + "subtest": "Unknown memory address", + "expect": "fail", + "reason": "Safari throws Error instead of TypeError for an unknown memory address type." + } + ], + "memory/grow.any.js": [ + { + "browser": "firefox", + "subtest": "Growing shared memory does not detach old buffer", + "expect": "fail", + "reason": "The old buffer after shared memory growth is not frozen." + } + ], + "module/customSections.any.js": [ + { + "browser": "firefox", + "subtest": "Custom sections with U+FFFD", + "expect": "fail", + "reason": "A custom-section name lookup returns a match where the test expects none." + } + ], + "table/constructor-memory64.any.js": [ + { + "browser": "safari", + "subtest": "Basic (zero, i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Basic (non-zero, i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Table with i64 address constructor", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Table with string value for initial (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Table with boolean value for initial (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Table with string value for maximum (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Table with boolean value for maximum (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + } + ], + "table/constructor.any.js": [ + { + "browser": "safari", + "subtest": "Order of evaluation for descriptor", + "expect": "fail", + "reason": "Safari reads the table descriptor's address property before its element property." + } + ], + "table/get-set.any.js": [ + { + "browser": "chrome", + "subtest": "Arguments for anyfunc table set", + "expect": "fail", + "reason": "Table.set rejects an explicit undefined value for an anyfunc table." + }, + { + "browser": "firefox", + "subtest": "Arguments for anyfunc table set", + "expect": "fail", + "reason": "Table.set rejects an explicit undefined value for an anyfunc table." + }, + { + "browser": "safari", + "subtest": "Basic (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Growing (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Setting out-of-bounds (i64)", + "expect": "fail", + "reason": "Safari reports table length as a number for an i64 table." + }, + { + "browser": "safari", + "subtest": "Arguments for anyfunc table set", + "expect": "fail", + "reason": "Table.set rejects an explicit undefined value for an anyfunc table." + } + ], + "table/grow-memory64.any.js": [ + { + "browser": "chrome", + "subtest": "Basic i64", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "chrome", + "subtest": "Reached maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "chrome", + "subtest": "Exceeded maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "firefox", + "subtest": "Basic i64", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "firefox", + "subtest": "Reached maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "firefox", + "subtest": "Exceeded maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "safari", + "subtest": "Basic i64", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "safari", + "subtest": "Reached maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + }, + { + "browser": "safari", + "subtest": "Exceeded maximum (i64)", + "expect": "fail", + "reason": "The test calls nulls(), which its declared helpers do not define." + } + ], + "table/grow.any.js": [ + { + "browser": "chrome", + "subtest": "Grow with undefined argument", + "expect": "fail", + "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." + }, + { + "browser": "firefox", + "subtest": "Grow with undefined argument", + "expect": "fail", + "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." + }, + { + "browser": "safari", + "subtest": "Grow with undefined argument", + "expect": "fail", + "reason": "Table.grow rejects an explicit undefined initializer for an anyfunc table." + } + ] +} diff --git a/test/js-api/run.py b/test/js-api/scripts/run.py similarity index 88% rename from test/js-api/run.py rename to test/js-api/scripts/run.py index 5cfd1e975c..3637a3eb2a 100755 --- a/test/js-api/run.py +++ b/test/js-api/scripts/run.py @@ -14,8 +14,9 @@ from threading import Thread from urllib.parse import quote, urljoin, urlsplit -SUITE = Path(__file__).resolve().parent -MANIFEST = SUITE / "expectations.json" +SCRIPTS = Path(__file__).resolve().parent +SUITE = SCRIPTS.parent +MANIFEST = SCRIPTS / "expectations.json" PREFIX = "/wasm/jsapi/" HARNESS = "/resources/testharness.js" BROWSERS = ("chrome", "firefox", "safari") @@ -102,7 +103,11 @@ def test_metadata(path): def discover_suite(): - sources = {path.relative_to(SUITE).as_posix(): path for path in SUITE.rglob("*.js")} + sources = { + path.relative_to(SUITE).as_posix(): path + for path in SUITE.rglob("*.js") + if not path.is_relative_to(SCRIPTS) + } scripts = {PREFIX + quote(name): path for name, path in sources.items()} scripts[HARNESS] = SUITE.parent / "harness" / "testharness.js" tests = {name: path for name, path in sources.items() if name.endswith(".any.js")} @@ -213,10 +218,13 @@ def unique_json_keys(pairs): return result -def load_expectations(path, tests, browser, metadata_for): - by_test = json.loads( +def read_json(path): + return json.loads( path.read_text(encoding="utf-8"), object_pairs_hook=unique_json_keys ) + + +def validate_expectations(by_test, tests, browser, metadata_for): if not isinstance(by_test, dict): raise ValueError("Expected an object keyed by test path") @@ -275,7 +283,7 @@ def load_expectations(path, tests, browser, metadata_for): } -def create_driver(browser): +def create_driver(browser, browser_version): try: from selenium import webdriver from selenium.common.exceptions import WebDriverException @@ -294,6 +302,8 @@ def create_driver(browser): options = options_class() if headless: options.add_argument(headless) + if browser_version and browser != "safari": + options.browser_version = browser_version try: return driver_class(options=options) @@ -368,7 +378,7 @@ def evaluate_result(result, rules): return "PASS", [] -def run_browser(browser, base_url, cases, expectations, json_path): +def run_browser(browser, browser_version, base_url, cases, expectations): results = [] counts = Counter() selected = [ @@ -377,10 +387,23 @@ def run_browser(browser, base_url, cases, expectations, json_path): has_runnable_cases = any( rules.get(WHOLE_CASE, (None, None))[0] != "skip" for _, rules in selected ) - with create_driver(browser) if has_runnable_cases else nullcontext() as driver: + with ( + create_driver(browser, browser_version) + if has_runnable_cases + else nullcontext() as driver + ): version = ( - driver.capabilities.get("browserVersion", "unknown") if driver else None + (driver.capabilities.get("browserVersion") or "unknown") if driver else None ) + if ( + driver + and browser_version + and version != browser_version + and not ( + "." not in browser_version and version.startswith(browser_version + ".") + ) + ): + raise SystemExit(f"Expected {browser} {browser_version}, started {version}") print( f"{browser}: {len(cases)} selected cases" + (f" (version {version})" if version else ""), @@ -413,9 +436,6 @@ def run_browser(browser, base_url, cases, expectations, json_path): } ) - if json_path: - report = {"browser": browser, "version": version, "results": results} - json_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print( ", ".join( f"{counts[status]} {status}" @@ -423,12 +443,21 @@ def run_browser(browser, base_url, cases, expectations, json_path): ), flush=True, ) - return int(counts["FAIL"] > 0 or counts["XPASS"] > 0) + report = {"browser": browser, "version": version, "results": results} + return report, int(counts["FAIL"] > 0 or counts["XPASS"] > 0) def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--browser", choices=BROWSERS, default="firefox") + parser.add_argument( + "--browser", + choices=BROWSERS, + default="firefox", + help="Browser to run (default: firefox)", + ) + parser.add_argument( + "--browser-version", help="Require a browser version or major version" + ) parser.add_argument( "--context", choices=BROWSER_GLOBALS, @@ -440,7 +469,7 @@ def main(): "--manifest", type=Path, default=MANIFEST, - help="Expectations file for Selenium runs (default: test/js-api/expectations.json)", + help="Expectations file (default: test/js-api/scripts/expectations.json)", ) parser.add_argument( "--serve", action="store_true", help="Serve test pages for manual use" @@ -449,14 +478,28 @@ def main(): "tests", nargs="*", help="Test paths relative to test/js-api (default: all)" ) args = parser.parse_args() + if args.browser_version and not re.fullmatch( + r"\d+(?:\.\d+)*", args.browser_version + ): + parser.error("--browser-version must be a version number") + scripts, tests = discover_suite() + metadata_for = cache(test_metadata) + + if not args.serve: + try: + # Validate the full manifest even when the run selects only a few cases. + manifest = read_json(args.manifest) + expectations = validate_expectations( + manifest, tests, args.browser, metadata_for + ) + except (OSError, ValueError) as error: + parser.error(f"{args.manifest}: {error}") contexts = tuple( context for context in BROWSER_GLOBALS if not args.context or context in args.context ) - scripts, tests = discover_suite() - metadata_for = cache(test_metadata) try: pages, cases = generate_test_pages( scripts, tests, set(args.tests), contexts, metadata_for @@ -465,15 +508,6 @@ def main(): parser.error(str(error)) if not cases: parser.error("No browser cases matched the selection") - if not args.serve: - try: - # Validate the full manifest even when the run selects only a few cases. - expectations = load_expectations( - args.manifest, tests, args.browser, metadata_for - ) - except (OSError, ValueError) as error: - parser.error(f"{args.manifest}: {error}") - with make_server(scripts, pages) as server: base_url = f"http://127.0.0.1:{server.server_port}" if args.serve: @@ -485,10 +519,15 @@ def main(): thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: - return run_browser(args.browser, base_url, cases, expectations, args.json) + report, status = run_browser( + args.browser, args.browser_version, base_url, cases, expectations + ) finally: server.shutdown() thread.join() + if args.json: + args.json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + return status if __name__ == "__main__": diff --git a/test/js-api/scripts/update-expectations.py b/test/js-api/scripts/update-expectations.py new file mode 100755 index 0000000000..d354239a3e --- /dev/null +++ b/test/js-api/scripts/update-expectations.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Generate proposed Wasm JS API expectations from a browser JSON report.""" + +import argparse +import json +from functools import cache +from pathlib import Path + +from run import ( + BROWSER_GLOBALS, + BROWSERS, + MANIFEST, + WHOLE_CASE, + discover_suite, + evaluate_result, + read_json, + test_metadata, + validate_expectations, +) + + +def update_expectations(manifest, rules, report, tests, metadata_for): + """Refresh failure rules for the browser cases covered by a result report.""" + browser, version = report["browser"], report.get("version") + updated = rules.copy() + seen = set() + changed = set() + for case in report["results"]: + name, context = case["test"], case["context"] + key = (name, context) + if ( + name not in tests + or context not in BROWSER_GLOBALS + or context not in metadata_for(tests[name])[0] + or key in seen + ): + raise ValueError(f"Unknown or duplicate browser case: {name} [{context}]") + seen.add(key) + subtests = case["subtests"] + previous = rules.get(key, {}) + # A skip or an incomplete run gives no reliable evidence about this case. + if ( + case["status"] != "OK" + or not subtests + or any(test["status"] not in ("PASS", "FAIL") for test in subtests) + or previous.get(WHOLE_CASE, (None, None))[0] == "skip" + ): + continue + failures = { + test["name"]: test.get("message") + for test in subtests + if test["status"] == "FAIL" + } + whole_case = previous.get(WHOLE_CASE) + if whole_case and failures: + current = previous + else: + current = {} + for subtest, message in failures.items(): + if subtest in previous: + current[subtest] = previous[subtest] + else: + reason = f"Observed in {browser.capitalize()}" + if version: + reason += f" {version}" + if message: + reason += f": {' '.join(message.split())}" + current[subtest] = ("fail", reason) + if current != previous: + updated[key] = current + changed.add(name) + + result = manifest.copy() + for name in sorted(changed): + supported = [ + context + for context in BROWSER_GLOBALS + if context in metadata_for(tests[name])[0] + ] + rule_contexts = {} + for context in supported: + for subtest, (expect, reason) in updated.get((name, context), {}).items(): + rule_contexts.setdefault((subtest, expect, reason), []).append(context) + + entries = [ + entry for entry in manifest.get(name, []) if entry["browser"] != browser + ] + for (subtest, expect, reason), contexts in rule_contexts.items(): + # A rule with no context applies to every supported browser global. + for context in (None,) if contexts == supported else contexts: + entry = {"browser": browser} + if context is not None: + entry["context"] = context + if subtest is not WHOLE_CASE: + entry["subtest"] = subtest + entries.append({**entry, "expect": expect, "reason": reason}) + if entries: + result[name] = entries + else: + result.pop(name) + return dict(sorted(result.items())) if changed else result + + +def check_complete_report(report, rules, tests, metadata_for): + expected_cases = { + (name, context) + for name, path in tests.items() + for context in BROWSER_GLOBALS + if context in metadata_for(path)[0] + } + reported_cases = {(case["test"], case["context"]) for case in report["results"]} + missing = expected_cases - reported_cases + if missing: + examples = ", ".join( + f"{name} [{context}]" for name, context in sorted(missing)[:3] + ) + raise ValueError( + f"Report is missing {len(missing)} browser cases, including {examples}" + ) + + for case in report["results"]: + name, context = case["test"], case["context"] + case_rules = rules.get((name, context), {}) + if ( + case_rules.get(WHOLE_CASE, (None, None))[0] == "skip" + and case["status"] == "SKIP" + ): + continue + outcome, _ = evaluate_result(case, case_rules) + if not case["subtests"] or outcome not in ("PASS", "XFAIL"): + raise ValueError( + f"Cannot update from an incomplete or unresolved case: {name} [{context}]" + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "report", type=Path, help="Browser JSON report from run.py or CI" + ) + parser.add_argument( + "--manifest", + type=Path, + default=MANIFEST, + help="Base expectations file (default: test/js-api/scripts/expectations.json)", + ) + parser.add_argument( + "--require-complete", + action="store_true", + help="Reject reports with missing or unresolved cases (used by CI)", + ) + args = parser.parse_args() + try: + report = read_json(args.report) + browser = report["browser"] + if browser not in BROWSERS or not isinstance(report["results"], list): + raise ValueError("Expected a browser report with a results list") + except (OSError, ValueError, KeyError, TypeError) as error: + parser.error(f"{args.report}: {error}") + + _, tests = discover_suite() + metadata_for = cache(test_metadata) + try: + manifest = read_json(args.manifest) + rules = validate_expectations(manifest, tests, browser, metadata_for) + except (OSError, ValueError) as error: + parser.error(f"{args.manifest}: {error}") + + try: + updated = update_expectations(manifest, rules, report, tests, metadata_for) + updated_rules = validate_expectations(updated, tests, browser, metadata_for) + if args.require_complete: + check_complete_report(report, updated_rules, tests, metadata_for) + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + parser.error(f"{args.report}: {error}") + print(json.dumps(updated, indent=2)) + + +if __name__ == "__main__": + main() From f55248f020e21f3e1c97bad0a00042daef3ab52c Mon Sep 17 00:00:00 2001 From: Ryan Hunt Date: Mon, 23 Nov 2026 22:31:02 -0600 Subject: [PATCH 3/3] [js-api] More reorganizing --- .github/workflows/ci-js-api.yml | 127 ++--------- test/js-api/README.md | 14 +- test/js-api/scripts/ci.py | 131 +++++++++++ test/js-api/scripts/lib/__init__.py | 0 test/js-api/scripts/lib/expectations.py | 230 +++++++++++++++++++ test/js-api/scripts/lib/tests.py | 90 ++++++++ test/js-api/scripts/run.py | 253 ++++----------------- test/js-api/scripts/update-expectations.py | 169 ++------------ 8 files changed, 548 insertions(+), 466 deletions(-) create mode 100644 test/js-api/scripts/ci.py create mode 100644 test/js-api/scripts/lib/__init__.py create mode 100644 test/js-api/scripts/lib/expectations.py create mode 100644 test/js-api/scripts/lib/tests.py diff --git a/.github/workflows/ci-js-api.yml b/.github/workflows/ci-js-api.yml index 7c924c8100..6c13bdfb88 100644 --- a/.github/workflows/ci-js-api.yml +++ b/.github/workflows/ci-js-api.yml @@ -1,4 +1,4 @@ -name: CI for Wasm JS API tests +name: CI for JS API tests on: push: @@ -16,7 +16,7 @@ on: - test/js-api/** schedule: - - cron: '23 6 * * 1' + - cron: '23 6 1 * *' workflow_dispatch: inputs: @@ -42,29 +42,8 @@ defaults: shell: bash jobs: - refresh-schedule: - name: Check browser refresh schedule - if: github.event_name == 'schedule' - runs-on: ubuntu-24.04 - timeout-minutes: 2 - permissions: {} - outputs: - due: ${{ steps.schedule.outputs.due }} - steps: - - name: Check four-week cadence - id: schedule - run: | - # Cron wakes the workflow weekly. Count UTC weeks from a fixed Monday. - anchor=$(date -u -d '2026-11-23' +%s) - now=$(date -u +%s) - if (( now >= anchor && (now - anchor) / 604800 % 4 == 0 )); then - echo 'due=true' >> "$GITHUB_OUTPUT" - fi - js-api: name: JS API (${{ matrix.browser }}) - needs: refresh-schedule - if: ${{ !cancelled() && (github.event_name != 'schedule' || needs.refresh-schedule.outputs.due == 'true') }} runs-on: ${{ matrix.os }} timeout-minutes: 15 strategy: @@ -83,6 +62,7 @@ jobs: env: BROWSER: ${{ matrix.browser }} REFRESH: ${{ github.event_name == 'schedule' || inputs.refresh }} + PROPOSE: ${{ (github.event_name == 'schedule' || inputs.refresh) && github.ref_name == github.event.repository.default_branch }} steps: - name: Checkout repo uses: actions/checkout@v4 @@ -99,41 +79,12 @@ jobs: env: OVERRIDE: ${{ matrix.version }} run: | - pin=$(jq -er --arg browser "$BROWSER" '.[$browser]' test/js-api/scripts/browser-versions.json) + args=(select-version "$BROWSER" --override "$OVERRIDE") if [[ "$REFRESH" == true ]]; then - case "$BROWSER" in - chrome) - latest=$(curl -fsSL --retry 3 --max-time 30 https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_STABLE) - ;; - firefox) - latest=$(curl -fsSL --retry 3 --max-time 30 https://product-details.mozilla.org/1.0/firefox_versions.json | jq -er '.LATEST_FIREFOX_VERSION') - ;; - safari) - latest=installed - ;; - esac - if [[ "$latest" == installed && "$BROWSER" == safari ]]; then - version=installed - elif [[ "$latest" =~ ^[0-9]+(\.[0-9]+)+$ ]]; then - # A release feed can lag behind the version already tested. - version=$(printf '%s\n%s\n' "$pin" "$latest" | sort -V | tail -n 1) - else - echo "Could not resolve a stable $BROWSER version" >&2 - exit 1 - fi - elif [[ -n "$OVERRIDE" ]]; then - version=$OVERRIDE - elif [[ "$BROWSER" == safari ]]; then - # The hosted runner supplies Safari. Normal CI checks only its major version. - version=${pin%%.*} - else - version=$pin - fi - if [[ ! "$version" =~ ^[0-9]+(\.[0-9]+)*$ && ( "$BROWSER" != safari || "$version" != installed ) ]]; then - echo "Invalid $BROWSER version" >&2 - exit 1 + args+=(--refresh) fi - printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT" + version=$(python test/js-api/scripts/ci.py "${args[@]}") + echo "version=$version" >> "$GITHUB_OUTPUT" - name: Enable Safari Remote Automation if: matrix.browser == 'safari' run: sudo /usr/bin/safaridriver --enable @@ -142,14 +93,14 @@ jobs: BROWSER_VERSION: ${{ steps.browser.outputs.version }} SE_SKIP_DRIVER_IN_PATH: 'true' run: | - args=(--browser "$BROWSER" --json wasm-js-api.json) - if [[ "$BROWSER" != safari || "$BROWSER_VERSION" != installed ]]; then + args=(--browser "$BROWSER" --json wasm-js-api.json --summary "$GITHUB_STEP_SUMMARY") + if [[ -n "$BROWSER_VERSION" ]]; then args+=(--browser-version "$BROWSER_VERSION") fi status=0 python test/js-api/scripts/run.py "${args[@]}" || status=$? - # Candidate test failures are expected. The PR job validates the report. - if [[ "$REFRESH" == true && "$status" == 1 && -s wasm-js-api.json ]]; then + # Candidate test failures are expected. The proposal job validates the report. + if [[ "$PROPOSE" == true && "$status" == 1 && -s wasm-js-api.json ]]; then exit 0 fi exit "$status" @@ -160,21 +111,6 @@ jobs: name: wasm-js-api-${{ matrix.browser }} path: wasm-js-api.json if-no-files-found: error - - name: Summarize browser results - if: ${{ !cancelled() && hashFiles('wasm-js-api.json') != '' }} - run: | - python - <<'PY' >> "$GITHUB_STEP_SUMMARY" - from collections import Counter - import json - from pathlib import Path - - report = json.loads(Path('wasm-js-api.json').read_text(encoding='utf-8')) - counts = Counter(case['outcome'] for case in report['results']) - print(f"### Wasm JS API in {report['browser']} {report['version']}\n") - print('| Pass | Fail | Expected failure | Unexpected pass | Skip |') - print('| ---: | ---: | ---: | ---: | ---: |') - print('| ' + ' | '.join(str(counts[outcome]) for outcome in ('PASS', 'FAIL', 'XFAIL', 'XPASS', 'SKIP')) + ' |') - PY propose-browser-update: name: Propose browser update @@ -184,6 +120,7 @@ jobs: timeout-minutes: 5 concurrency: js-api-browser-update permissions: + actions: write contents: write pull-requests: write steps: @@ -196,46 +133,24 @@ jobs: with: pattern: wasm-js-api-* path: ${{ runner.temp }}/js-api-reports - - name: Update pins and expectations + - name: Check the default branch is unchanged env: - REPORTS: ${{ runner.temp }}/js-api-reports BASE_BRANCH: ${{ github.event.repository.default_branch }} run: | if [[ "$(git ls-remote origin "refs/heads/$BASE_BRANCH" | cut -f1)" != "$GITHUB_SHA" ]]; then echo "The default branch moved during testing. Run the refresh again." >&2 exit 1 fi - proposal=$(mktemp -d) - pins=test/js-api/scripts/browser-versions.json - manifest=test/js-api/scripts/expectations.json - cp "$pins" "$proposal/pins.json" - cp "$manifest" "$proposal/manifest.json" - for browser in chrome firefox safari; do - report="$REPORTS/wasm-js-api-$browser/wasm-js-api.json" - pin=$(jq -er --arg browser "$browser" '.[$browser]' "$pins") - version=$(jq -er --arg browser "$browser" \ - 'select(.browser == $browser) | .version | select(test("^[0-9]+([.][0-9]+)+$"))' "$report") - python3 test/js-api/scripts/update-expectations.py --require-complete \ - --manifest "$proposal/manifest.json" "$report" > "$proposal/manifest.next.json" - if [[ "$version" == "$pin" ]]; then - continue - fi - if [[ "$(printf '%s\n%s\n' "$pin" "$version" | sort -V | tail -n 1)" != "$version" ]]; then - echo "$browser $version is older than the tested pin $pin" >&2 - exit 1 - fi - jq --arg browser "$browser" --arg version "$version" '.[$browser] = $version' \ - "$proposal/pins.json" > "$proposal/pins.next.json" - mv "$proposal/pins.next.json" "$proposal/pins.json" - mv "$proposal/manifest.next.json" "$proposal/manifest.json" - printf -- '- %s %s → %s\n' "$browser" "$pin" "$version" >> "$GITHUB_STEP_SUMMARY" - done - cp "$proposal/pins.json" "$pins" - cp "$proposal/manifest.json" "$manifest" + - name: Update pins and expectations + id: update + run: python3 test/js-api/scripts/ci.py propose "$RUNNER_TEMP/js-api-reports" | tee -a "$GITHUB_STEP_SUMMARY" + # A rejected browser fails the job, but the other browsers are still proposed. - name: Open or update browser bump PR + if: ${{ !cancelled() && steps.update.outcome != 'skipped' }} env: GH_TOKEN: ${{ github.token }} BASE_BRANCH: ${{ github.event.repository.default_branch }} + UPDATE_OUTCOME: ${{ steps.update.outcome }} run: | branch=automation/js-api-browser-versions ref="refs/heads/$branch" @@ -243,7 +158,7 @@ jobs: lease="--force-with-lease=$ref:$previous" git add -- test/js-api/scripts/browser-versions.json test/js-api/scripts/expectations.json if git diff --cached --quiet; then - if [[ -n "$previous" ]]; then + if [[ -n "$previous" && "$UPDATE_OUTCOME" == success ]]; then gh auth setup-git git push "$lease" origin ":$ref" fi @@ -275,6 +190,8 @@ jobs: gh auth setup-git # Rebuild the bot branch from the tested default-branch commit. git push "$lease" origin "HEAD:$ref" + # Pushes made with GITHUB_TOKEN do not trigger pull_request runs, so start CI on the PR head. + gh workflow run ci-js-api.yml --repo "$GITHUB_REPOSITORY" --ref "$branch" if [[ -n "$pr" ]]; then gh api --method PATCH "repos/$GITHUB_REPOSITORY/pulls/$pr" \ -F body=@"$body_file" --jq .html_url diff --git a/test/js-api/README.md b/test/js-api/README.md index d8603dc74b..0e5a8f0bc9 100644 --- a/test/js-api/README.md +++ b/test/js-api/README.md @@ -90,11 +90,17 @@ versions. Selenium Manager selects or downloads those versions. For Safari, the file records the full version last tested on the GitHub-hosted image. The [CI workflow](../../.github/workflows/ci-js-api.yml) checks for browser -updates every four weeks. After complete runs, it opens a PR with newer versions -and their expectations. +updates monthly. After complete runs, it opens a PR with newer versions +and their expectations. This requires the repository setting "Allow GitHub +Actions to create and approve pull requests". ### Browser expectations The test runner uses [scripts/expectations.json](scripts/expectations.json) to -track expected results of tests. Run `scripts/update-expectations.py test-results.json > scripts/expectations.json` -to update expectations based on a test run. +track expected results of tests. To update expectations from a test run, save a +JSON report and apply it to the expectations file: + +```sh +/tmp/wasm-js-api-venv/bin/python test/js-api/scripts/run.py --browser firefox --json firefox.json +python3 test/js-api/scripts/update-expectations.py --in-place firefox.json +``` diff --git a/test/js-api/scripts/ci.py b/test/js-api/scripts/ci.py new file mode 100644 index 0000000000..91a0d9bff7 --- /dev/null +++ b/test/js-api/scripts/ci.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Browser version selection and update proposals for the JS API CI workflow.""" + +import argparse +import json +import sys +import time +from pathlib import Path +from urllib.request import urlopen + +from lib.expectations import apply_report +from lib.tests import ( + BROWSERS, + EXPECTATIONS, + PINS, + VERSION, + discover_tests, + read_json, + version_key, + write_json, +) + +LATEST_RELEASE_URLS = { + "chrome": "https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_STABLE", + "firefox": "https://product-details.mozilla.org/1.0/firefox_versions.json", +} + + +def fetch(url, attempts=3): + for attempt in range(1, attempts + 1): + try: + with urlopen(url, timeout=30) as response: + return response.read().decode("utf-8") + except OSError: + if attempt == attempts: + raise + time.sleep(5 * attempt) + + +def latest_release(browser): + body = fetch(LATEST_RELEASE_URLS[browser]) + if browser == "firefox": + return json.loads(body)["LATEST_FIREFOX_VERSION"] + return body.strip() + + +def select_version(browser, override, refresh): + """Return the version to require, or an empty string to accept any.""" + pin = read_json(PINS)[browser] + if override: + version = override + elif browser == "safari": + # The hosted runner supplies Safari. Normal CI checks only its major version. + version = "installed" if refresh else pin.split(".")[0] + elif refresh: + latest = latest_release(browser) + if not VERSION.fullmatch(latest): + raise ValueError(f"Could not resolve a stable {browser} version: {latest}") + # A release feed can lag behind the version already tested. + version = max(pin, latest, key=version_key) + else: + version = pin + + if browser == "safari" and version == "installed": + return "" + if not VERSION.fullmatch(version): + raise ValueError(f"Invalid {browser} version: {version}") + return version + + +def propose(reports): + """Update pins and expectations from CI reports. Returns the rejected browsers.""" + pins = read_json(PINS) + expectations = read_json(EXPECTATIONS) + _, tests = discover_tests() + rejected = [] + for browser in BROWSERS: + pin = pins[browser] + try: + report = read_json(reports / f"wasm-js-api-{browser}" / "wasm-js-api.json") + version = report.get("version") + if report.get("browser") != browser or not ( + isinstance(version, str) and VERSION.fullmatch(version) + ): + raise ValueError("report has no valid browser version") + if version == pin: + continue + if version_key(version) < version_key(pin): + raise ValueError(f"{version} is older than the tested pin {pin}") + expectations = apply_report(expectations, report, tests, require_complete=True) + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + print(f"::error::{browser}: {error}", file=sys.stderr) + rejected.append(browser) + continue + pins[browser] = version + print(f"- {browser} {pin} → {version}") + write_json(PINS, pins) + write_json(EXPECTATIONS, expectations) + return rejected + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + + select = commands.add_parser( + "select-version", help="Print the browser version a CI run should require" + ) + select.add_argument("browser", choices=BROWSERS) + select.add_argument("--override", help="Candidate version to test instead") + select.add_argument( + "--refresh", action="store_true", help="Test the latest stable release" + ) + + update = commands.add_parser( + "propose", help="Update pins and expectations from downloaded CI reports" + ) + update.add_argument("reports", type=Path, help="Directory of report artifacts") + + args = parser.parse_args() + if args.command == "select-version": + try: + print(select_version(args.browser, args.override, args.refresh)) + except (OSError, ValueError, KeyError) as error: + parser.error(str(error)) + return 0 + return 1 if propose(args.reports) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/js-api/scripts/lib/__init__.py b/test/js-api/scripts/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/js-api/scripts/lib/expectations.py b/test/js-api/scripts/lib/expectations.py new file mode 100644 index 0000000000..23dd6d10ae --- /dev/null +++ b/test/js-api/scripts/lib/expectations.py @@ -0,0 +1,230 @@ +"""Validate, evaluate and update the rules in expectations.json.""" + +from .tests import BROWSERS, supported_globals + +# Rules without a subtest name apply to the whole browser case. +WHOLE_CASE = None + + +def validate_expectations(expectations, tests, browser): + """Validate all expectations and return one browser's rules by case.""" + if not isinstance(expectations, dict): + raise ValueError("Expected an object keyed by test path") + + rules = {} + required = {"browser", "expect", "reason"} + allowed = required | {"context", "subtest"} + for name, entries in expectations.items(): + if name not in tests: + raise ValueError(f"Unknown test: {name}") + if not isinstance(entries, list): + raise ValueError(f"{name}: expected a list of rules") + supported = supported_globals(tests[name]) + for index, entry in enumerate(entries, 1): + label = f"{name} rule {index}" + if ( + not isinstance(entry, dict) + or not required <= entry.keys() <= allowed + or not all( + isinstance(value, str) and value.strip() for value in entry.values() + ) + ): + raise ValueError( + f"{label}: provide browser, expect, reason and optional context or subtest" + ) + product, expect = entry["browser"], entry["expect"] + subtest = entry.get("subtest", WHOLE_CASE) + if product not in BROWSERS or expect not in ("fail", "skip"): + raise ValueError(f"{label}: invalid browser or expectation") + if expect == "skip" and subtest is not WHOLE_CASE: + raise ValueError(f"{label}: skip applies to a whole test case") + requested_context = entry.get("context") + contexts = [ + context + for context in supported + if requested_context is None or context == requested_context + ] + if not contexts: + raise ValueError(f"{label}: no supported browser context") + for context in contexts: + case_rules = rules.setdefault((product, name, context), {}) + if ( + subtest in case_rules + or WHOLE_CASE in case_rules + or (subtest is WHOLE_CASE and case_rules) + ): + raise ValueError( + f"{label}: overlapping rules for {product} [{context}]" + ) + case_rules[subtest] = (expect, entry["reason"]) + + return { + (name, context): case_rules + for (product, name, context), case_rules in rules.items() + if product == browser + } + + +def evaluate_result(result, rules): + """Apply failure expectations after the harness has completed successfully.""" + subtests = result["subtests"] + failures = [test for test in subtests if test["status"] != "PASS"] + diagnostics = [ + f"{test['status']} {test['name']}: {test['message']}" for test in failures + ] + if result["status"] != "OK": + return "FAIL", [f"{result['status']}: {result['message']}", *diagnostics] + # Only a subtest with status FAIL can satisfy a failure expectation. + if WHOLE_CASE in rules: + _, reason = rules[WHOLE_CASE] + if not failures: + return "XPASS", [f"Expected a failure: {reason}"] + if all(test["status"] == "FAIL" for test in failures): + return "XFAIL", [reason, *diagnostics] + return "FAIL", diagnostics + + by_name = {test["name"]: test for test in subtests} + missing = rules.keys() - by_name.keys() + unexpected = [ + test + for test in failures + if test["name"] not in rules or test["status"] != "FAIL" + ] + expected_failures_that_passed = [ + name for name in rules if name in by_name and by_name[name]["status"] == "PASS" + ] + diagnostics += [f"Expected subtest missing: {name}" for name in sorted(missing)] + diagnostics += [ + f"XPASS {name}: {rules[name][1]}" for name in expected_failures_that_passed + ] + # Missing expected subtests and unexpected failures take precedence over XPASS. + if missing or unexpected: + return "FAIL", diagnostics + if expected_failures_that_passed: + return "XPASS", diagnostics + if rules: + return "XFAIL", [ + f"{name}: {reason}" for name, (_, reason) in rules.items() + ] + diagnostics + return "PASS", [] + + +def update_expectations(expectations, rules, report, tests): + """Refresh failure rules for the browser cases covered by a result report.""" + browser, version = report["browser"], report.get("version") + updated = rules.copy() + seen = set() + changed = set() + for case in report["results"]: + name, context = case["test"], case["context"] + key = (name, context) + if ( + name not in tests + or context not in supported_globals(tests[name]) + or key in seen + ): + raise ValueError(f"Unknown or duplicate browser case: {name} [{context}]") + seen.add(key) + subtests = case["subtests"] + previous = rules.get(key, {}) + # A skip or an incomplete run gives no reliable evidence about this case. + if ( + case["status"] != "OK" + or not subtests + or any(test["status"] not in ("PASS", "FAIL") for test in subtests) + or previous.get(WHOLE_CASE, (None, None))[0] == "skip" + ): + continue + failures = { + test["name"]: test.get("message") + for test in subtests + if test["status"] == "FAIL" + } + whole_case = previous.get(WHOLE_CASE) + if whole_case and failures: + current = previous + else: + current = {} + for subtest, message in failures.items(): + if subtest in previous: + current[subtest] = previous[subtest] + else: + reason = f"Observed in {browser.capitalize()}" + if version: + reason += f" {version}" + if message: + reason += f": {' '.join(message.split())}" + current[subtest] = ("fail", reason) + if current != previous: + updated[key] = current + changed.add(name) + + result = expectations.copy() + for name in sorted(changed): + supported = supported_globals(tests[name]) + rule_contexts = {} + for context in supported: + for subtest, (expect, reason) in updated.get((name, context), {}).items(): + rule_contexts.setdefault((subtest, expect, reason), []).append(context) + + entries = [ + entry for entry in expectations.get(name, []) if entry["browser"] != browser + ] + for (subtest, expect, reason), contexts in rule_contexts.items(): + # A rule with no context applies to every supported browser global. + for context in (None,) if contexts == supported else contexts: + entry = {"browser": browser} + if context is not None: + entry["context"] = context + if subtest is not WHOLE_CASE: + entry["subtest"] = subtest + entries.append({**entry, "expect": expect, "reason": reason}) + if entries: + result[name] = entries + else: + result.pop(name) + return dict(sorted(result.items())) if changed else result + + +def check_complete_report(report, rules, tests): + expected_cases = { + (name, context) + for name, path in tests.items() + for context in supported_globals(path) + } + reported_cases = {(case["test"], case["context"]) for case in report["results"]} + missing = expected_cases - reported_cases + if missing: + examples = ", ".join( + f"{name} [{context}]" for name, context in sorted(missing)[:3] + ) + raise ValueError( + f"Report is missing {len(missing)} browser cases, including {examples}" + ) + + for case in report["results"]: + name, context = case["test"], case["context"] + case_rules = rules.get((name, context), {}) + if ( + case_rules.get(WHOLE_CASE, (None, None))[0] == "skip" + and case["status"] == "SKIP" + ): + continue + outcome, _ = evaluate_result(case, case_rules) + if not case["subtests"] or outcome not in ("PASS", "XFAIL"): + raise ValueError( + f"Cannot update from an incomplete or unresolved case: {name} [{context}]" + ) + + +def apply_report(expectations, report, tests, require_complete=False): + """Return the expectations updated with a browser report's results.""" + browser = report["browser"] + if browser not in BROWSERS or not isinstance(report["results"], list): + raise ValueError("Expected a browser report with a results list") + rules = validate_expectations(expectations, tests, browser) + updated = update_expectations(expectations, rules, report, tests) + updated_rules = validate_expectations(updated, tests, browser) + if require_complete: + check_complete_report(report, updated_rules, tests) + return updated diff --git a/test/js-api/scripts/lib/tests.py b/test/js-api/scripts/lib/tests.py new file mode 100644 index 0000000000..5f92705f53 --- /dev/null +++ b/test/js-api/scripts/lib/tests.py @@ -0,0 +1,90 @@ +"""Test discovery, META parsing and shared helpers for the JS API scripts.""" + +import json +import re +from functools import cache +from pathlib import Path +from urllib.parse import quote + +SCRIPTS = Path(__file__).resolve().parent.parent +TEST_DIR = SCRIPTS.parent +EXPECTATIONS = SCRIPTS / "expectations.json" +PINS = SCRIPTS / "browser-versions.json" +PREFIX = "/wasm/jsapi/" +HARNESS = "/resources/testharness.js" +BROWSERS = ("chrome", "firefox", "safari") +BROWSER_GLOBALS = ("window", "dedicatedworker") +VERSION = re.compile(r"\d+(?:\.\d+)*") + + +def version_key(version): + return tuple(map(int, version.split("."))) + + +@cache +def test_metadata(path): + globals_ = set(BROWSER_GLOBALS) + helpers = [] + timeout = "normal" + with path.open(encoding="utf-8-sig") as source: + for line in source: + line = line.strip() + if line and not line.startswith("//"): + break + if not line.startswith("// META:"): + continue + match = re.fullmatch(r"// META:\s*(\w+)=(.+)", line) + if not match: + raise ValueError(f"{path.name}: invalid metadata: {line}") + key, value = match.groups() + if key == "global": + globals_ = {name.strip() for name in value.split(",")} + # Accept globals used by WPT even when this runner cannot launch them. + unknown = globals_ - {*BROWSER_GLOBALS, "jsshell", "shadowrealm"} + if unknown: + raise ValueError( + f"{path.name}: unsupported globals: {', '.join(sorted(unknown))}" + ) + elif key == "script": + helpers.append(value) + elif key == "timeout" and value == "long": + timeout = value + else: + raise ValueError(f"{path.name}: unsupported metadata: {line}") + return globals_, helpers, timeout + + +def supported_globals(path): + globals_, _, _ = test_metadata(path) + return [context for context in BROWSER_GLOBALS if context in globals_] + + +def discover_tests(): + sources = { + path.relative_to(TEST_DIR).as_posix(): path + for path in TEST_DIR.rglob("*.js") + if not path.is_relative_to(SCRIPTS) + } + scripts = {PREFIX + quote(name): path for name, path in sources.items()} + scripts[HARNESS] = TEST_DIR.parent / "harness" / "testharness.js" + tests = {name: path for name, path in sources.items() if name.endswith(".any.js")} + return scripts, tests + + +def unique_json_keys(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate key: {key}") + result[key] = value + return result + + +def read_json(path): + return json.loads( + path.read_text(encoding="utf-8"), object_pairs_hook=unique_json_keys + ) + + +def write_json(path, data): + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") diff --git a/test/js-api/scripts/run.py b/test/js-api/scripts/run.py index 3637a3eb2a..ebdf116912 100755 --- a/test/js-api/scripts/run.py +++ b/test/js-api/scripts/run.py @@ -3,29 +3,33 @@ import argparse import json -import re from collections import Counter from contextlib import nullcontext from dataclasses import dataclass -from functools import cache from html import escape from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from threading import Thread from urllib.parse import quote, urljoin, urlsplit -SCRIPTS = Path(__file__).resolve().parent -SUITE = SCRIPTS.parent -MANIFEST = SCRIPTS / "expectations.json" -PREFIX = "/wasm/jsapi/" -HARNESS = "/resources/testharness.js" -BROWSERS = ("chrome", "firefox", "safari") -BROWSER_GLOBALS = ("window", "dedicatedworker") +from lib.expectations import WHOLE_CASE, evaluate_result, validate_expectations +from lib.tests import ( + BROWSER_GLOBALS, + BROWSERS, + HARNESS, + EXPECTATIONS, + PREFIX, + VERSION, + discover_tests, + read_json, + test_metadata, + write_json, +) + # Match the timeout values in testharness.js. HARNESS_TIMEOUT_SECONDS = {"normal": 10, "long": 60} WEBDRIVER_GRACE_SECONDS = 5 -# Manifest rules without a subtest name apply to the whole browser case. -WHOLE_CASE = None +OUTCOMES = ("PASS", "FAIL", "XFAIL", "XPASS", "SKIP") REPORTER = """\ setup({output: false}); @@ -70,51 +74,7 @@ class BrowserCase: timeout_seconds: int -def test_metadata(path): - globals_ = set(BROWSER_GLOBALS) - helpers = [] - timeout = "normal" - with path.open(encoding="utf-8-sig") as source: - for line in source: - line = line.strip() - if line and not line.startswith("//"): - break - if not line.startswith("// META:"): - continue - match = re.fullmatch(r"// META:\s*(\w+)=(.+)", line) - if not match: - raise ValueError(f"{path.name}: invalid metadata: {line}") - key, value = match.groups() - if key == "global": - globals_ = {name.strip() for name in value.split(",")} - # Accept globals used by WPT even when this runner cannot launch them. - unknown = globals_ - {*BROWSER_GLOBALS, "jsshell", "shadowrealm"} - if unknown: - raise ValueError( - f"{path.name}: unsupported globals: {', '.join(sorted(unknown))}" - ) - elif key == "script": - helpers.append(value) - elif key == "timeout" and value == "long": - timeout = value - else: - raise ValueError(f"{path.name}: unsupported metadata: {line}") - return globals_, helpers, timeout - - -def discover_suite(): - sources = { - path.relative_to(SUITE).as_posix(): path - for path in SUITE.rglob("*.js") - if not path.is_relative_to(SCRIPTS) - } - scripts = {PREFIX + quote(name): path for name, path in sources.items()} - scripts[HARNESS] = SUITE.parent / "harness" / "testharness.js" - tests = {name: path for name, path in sources.items() if name.endswith(".any.js")} - return scripts, tests - - -def generate_test_pages(scripts, tests, selected, contexts, metadata_for): +def generate_test_pages(scripts, tests, selected, contexts): unknown = selected - tests.keys() if unknown: raise ValueError(f"Unknown tests: {', '.join(sorted(unknown))}") @@ -123,7 +83,7 @@ def generate_test_pages(scripts, tests, selected, contexts, metadata_for): for name in sorted(selected or tests): url = PREFIX + quote(name) stem = url.removesuffix(".js") - globals_, helpers, timeout_mode = metadata_for(tests[name]) + globals_, helpers, timeout_mode = test_metadata(tests[name]) sources = [urljoin(url, helper) for helper in helpers] for source in sources: if source not in scripts: @@ -209,80 +169,6 @@ def log_message(self, format, *args): return ThreadingHTTPServer(("127.0.0.1", 0), Handler) -def unique_json_keys(pairs): - result = {} - for key, value in pairs: - if key in result: - raise ValueError(f"Duplicate key: {key}") - result[key] = value - return result - - -def read_json(path): - return json.loads( - path.read_text(encoding="utf-8"), object_pairs_hook=unique_json_keys - ) - - -def validate_expectations(by_test, tests, browser, metadata_for): - if not isinstance(by_test, dict): - raise ValueError("Expected an object keyed by test path") - - rules = {} - required = {"browser", "expect", "reason"} - allowed = required | {"context", "subtest"} - for name, entries in by_test.items(): - if name not in tests: - raise ValueError(f"Unknown test: {name}") - if not isinstance(entries, list): - raise ValueError(f"{name}: expected a list of rules") - globals_, _, _ = metadata_for(tests[name]) - supported = [context for context in BROWSER_GLOBALS if context in globals_] - for index, entry in enumerate(entries, 1): - label = f"{name} rule {index}" - if ( - not isinstance(entry, dict) - or not required <= entry.keys() <= allowed - or not all( - isinstance(value, str) and value.strip() for value in entry.values() - ) - ): - raise ValueError( - f"{label}: provide browser, expect, reason and optional context or subtest" - ) - product, expect = entry["browser"], entry["expect"] - subtest = entry.get("subtest", WHOLE_CASE) - if product not in BROWSERS or expect not in ("fail", "skip"): - raise ValueError(f"{label}: invalid browser or expectation") - if expect == "skip" and subtest is not WHOLE_CASE: - raise ValueError(f"{label}: skip applies to a whole test case") - requested_context = entry.get("context") - contexts = [ - context - for context in supported - if requested_context is None or context == requested_context - ] - if not contexts: - raise ValueError(f"{label}: no supported browser context") - for context in contexts: - case_rules = rules.setdefault((product, name, context), {}) - if ( - subtest in case_rules - or WHOLE_CASE in case_rules - or (subtest is WHOLE_CASE and case_rules) - ): - raise ValueError( - f"{label}: overlapping rules for {product} [{context}]" - ) - case_rules[subtest] = (expect, entry["reason"]) - - return { - (name, context): case_rules - for (product, name, context), case_rules in rules.items() - if product == browser - } - - def create_driver(browser, browser_version): try: from selenium import webdriver @@ -334,58 +220,14 @@ def read_result(driver, url, timeout_seconds): return {"status": "ERROR", "message": message, "subtests": []} -def evaluate_result(result, rules): - """Apply failure expectations after the harness has completed successfully.""" - subtests = result["subtests"] - failures = [test for test in subtests if test["status"] != "PASS"] - diagnostics = [ - f"{test['status']} {test['name']}: {test['message']}" for test in failures - ] - if result["status"] != "OK": - return "FAIL", [f"{result['status']}: {result['message']}", *diagnostics] - # Only a subtest with status FAIL can satisfy a failure expectation. - if WHOLE_CASE in rules: - _, reason = rules[WHOLE_CASE] - if not failures: - return "XPASS", [f"Expected a failure: {reason}"] - if all(test["status"] == "FAIL" for test in failures): - return "XFAIL", [reason, *diagnostics] - return "FAIL", diagnostics - - by_name = {test["name"]: test for test in subtests} - missing = rules.keys() - by_name.keys() - unexpected = [ - test - for test in failures - if test["name"] not in rules or test["status"] != "FAIL" - ] - expected_failures_that_passed = [ - name for name in rules if name in by_name and by_name[name]["status"] == "PASS" - ] - diagnostics += [f"Expected subtest missing: {name}" for name in sorted(missing)] - diagnostics += [ - f"XPASS {name}: {rules[name][1]}" for name in expected_failures_that_passed - ] - # Missing expected subtests and unexpected failures take precedence over XPASS. - if missing or unexpected: - return "FAIL", diagnostics - if expected_failures_that_passed: - return "XPASS", diagnostics - if rules: - return "XFAIL", [ - f"{name}: {reason}" for name, (_, reason) in rules.items() - ] + diagnostics - return "PASS", [] - - -def run_browser(browser, browser_version, base_url, cases, expectations): +def run_browser(browser, browser_version, base_url, cases, rules): results = [] counts = Counter() selected = [ - (case, expectations.get((case.name, case.context), {})) for case in cases + (case, rules.get((case.name, case.context), {})) for case in cases ] has_runnable_cases = any( - rules.get(WHOLE_CASE, (None, None))[0] != "skip" for _, rules in selected + case_rules.get(WHOLE_CASE, (None, None))[0] != "skip" for _, case_rules in selected ) with ( create_driver(browser, browser_version) @@ -409,8 +251,8 @@ def run_browser(browser, browser_version, base_url, cases, expectations): + (f" (version {version})" if version else ""), flush=True, ) - for case, rules in selected: - expect, reason = rules.get(WHOLE_CASE, (None, None)) + for case, case_rules in selected: + expect, reason = case_rules.get(WHOLE_CASE, (None, None)) if expect == "skip": result = {"status": "SKIP", "message": reason, "subtests": []} outcome, diagnostics = "SKIP", [reason] @@ -418,7 +260,7 @@ def run_browser(browser, browser_version, base_url, cases, expectations): result = read_result( driver, base_url + case.page_path, case.timeout_seconds ) - outcome, diagnostics = evaluate_result(result, rules) + outcome, diagnostics = evaluate_result(result, case_rules) counts[outcome] += 1 print( f"{outcome} {case.name} [{case.context}] ({len(result['subtests'])} subtests)", @@ -436,17 +278,21 @@ def run_browser(browser, browser_version, base_url, cases, expectations): } ) - print( - ", ".join( - f"{counts[status]} {status}" - for status in ("PASS", "FAIL", "XFAIL", "XPASS", "SKIP") - ), - flush=True, - ) + print(", ".join(f"{counts[outcome]} {outcome}" for outcome in OUTCOMES), flush=True) report = {"browser": browser, "version": version, "results": results} return report, int(counts["FAIL"] > 0 or counts["XPASS"] > 0) +def write_summary(path, report): + counts = Counter(case["outcome"] for case in report["results"]) + title = " ".join(filter(None, ("Wasm JS API in", report["browser"], report["version"]))) + with path.open("a", encoding="utf-8") as summary: + summary.write(f"### {title}\n\n") + summary.write("| Pass | Fail | Expected failure | Unexpected pass | Skip |\n") + summary.write("| ---: | ---: | ---: | ---: | ---: |\n") + summary.write("| " + " | ".join(str(counts[outcome]) for outcome in OUTCOMES) + " |\n") + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( @@ -466,9 +312,12 @@ def main(): ) parser.add_argument("--json", type=Path, help="Write a JSON report to this file") parser.add_argument( - "--manifest", + "--summary", type=Path, help="Append a Markdown results table to this file" + ) + parser.add_argument( + "--expectations", type=Path, - default=MANIFEST, + default=EXPECTATIONS, help="Expectations file (default: test/js-api/scripts/expectations.json)", ) parser.add_argument( @@ -478,22 +327,16 @@ def main(): "tests", nargs="*", help="Test paths relative to test/js-api (default: all)" ) args = parser.parse_args() - if args.browser_version and not re.fullmatch( - r"\d+(?:\.\d+)*", args.browser_version - ): + if args.browser_version and not VERSION.fullmatch(args.browser_version): parser.error("--browser-version must be a version number") - scripts, tests = discover_suite() - metadata_for = cache(test_metadata) + scripts, tests = discover_tests() if not args.serve: try: - # Validate the full manifest even when the run selects only a few cases. - manifest = read_json(args.manifest) - expectations = validate_expectations( - manifest, tests, args.browser, metadata_for - ) + # Validate all expectations even when the run selects only a few cases. + rules = validate_expectations(read_json(args.expectations), tests, args.browser) except (OSError, ValueError) as error: - parser.error(f"{args.manifest}: {error}") + parser.error(f"{args.expectations}: {error}") contexts = tuple( context @@ -502,7 +345,7 @@ def main(): ) try: pages, cases = generate_test_pages( - scripts, tests, set(args.tests), contexts, metadata_for + scripts, tests, set(args.tests), contexts ) except ValueError as error: parser.error(str(error)) @@ -520,13 +363,15 @@ def main(): thread.start() try: report, status = run_browser( - args.browser, args.browser_version, base_url, cases, expectations + args.browser, args.browser_version, base_url, cases, rules ) finally: server.shutdown() thread.join() if args.json: - args.json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + write_json(args.json, report) + if args.summary: + write_summary(args.summary, report) return status diff --git a/test/js-api/scripts/update-expectations.py b/test/js-api/scripts/update-expectations.py index d354239a3e..6619e24372 100755 --- a/test/js-api/scripts/update-expectations.py +++ b/test/js-api/scripts/update-expectations.py @@ -3,134 +3,10 @@ import argparse import json -from functools import cache from pathlib import Path -from run import ( - BROWSER_GLOBALS, - BROWSERS, - MANIFEST, - WHOLE_CASE, - discover_suite, - evaluate_result, - read_json, - test_metadata, - validate_expectations, -) - - -def update_expectations(manifest, rules, report, tests, metadata_for): - """Refresh failure rules for the browser cases covered by a result report.""" - browser, version = report["browser"], report.get("version") - updated = rules.copy() - seen = set() - changed = set() - for case in report["results"]: - name, context = case["test"], case["context"] - key = (name, context) - if ( - name not in tests - or context not in BROWSER_GLOBALS - or context not in metadata_for(tests[name])[0] - or key in seen - ): - raise ValueError(f"Unknown or duplicate browser case: {name} [{context}]") - seen.add(key) - subtests = case["subtests"] - previous = rules.get(key, {}) - # A skip or an incomplete run gives no reliable evidence about this case. - if ( - case["status"] != "OK" - or not subtests - or any(test["status"] not in ("PASS", "FAIL") for test in subtests) - or previous.get(WHOLE_CASE, (None, None))[0] == "skip" - ): - continue - failures = { - test["name"]: test.get("message") - for test in subtests - if test["status"] == "FAIL" - } - whole_case = previous.get(WHOLE_CASE) - if whole_case and failures: - current = previous - else: - current = {} - for subtest, message in failures.items(): - if subtest in previous: - current[subtest] = previous[subtest] - else: - reason = f"Observed in {browser.capitalize()}" - if version: - reason += f" {version}" - if message: - reason += f": {' '.join(message.split())}" - current[subtest] = ("fail", reason) - if current != previous: - updated[key] = current - changed.add(name) - - result = manifest.copy() - for name in sorted(changed): - supported = [ - context - for context in BROWSER_GLOBALS - if context in metadata_for(tests[name])[0] - ] - rule_contexts = {} - for context in supported: - for subtest, (expect, reason) in updated.get((name, context), {}).items(): - rule_contexts.setdefault((subtest, expect, reason), []).append(context) - - entries = [ - entry for entry in manifest.get(name, []) if entry["browser"] != browser - ] - for (subtest, expect, reason), contexts in rule_contexts.items(): - # A rule with no context applies to every supported browser global. - for context in (None,) if contexts == supported else contexts: - entry = {"browser": browser} - if context is not None: - entry["context"] = context - if subtest is not WHOLE_CASE: - entry["subtest"] = subtest - entries.append({**entry, "expect": expect, "reason": reason}) - if entries: - result[name] = entries - else: - result.pop(name) - return dict(sorted(result.items())) if changed else result - - -def check_complete_report(report, rules, tests, metadata_for): - expected_cases = { - (name, context) - for name, path in tests.items() - for context in BROWSER_GLOBALS - if context in metadata_for(path)[0] - } - reported_cases = {(case["test"], case["context"]) for case in report["results"]} - missing = expected_cases - reported_cases - if missing: - examples = ", ".join( - f"{name} [{context}]" for name, context in sorted(missing)[:3] - ) - raise ValueError( - f"Report is missing {len(missing)} browser cases, including {examples}" - ) - - for case in report["results"]: - name, context = case["test"], case["context"] - case_rules = rules.get((name, context), {}) - if ( - case_rules.get(WHOLE_CASE, (None, None))[0] == "skip" - and case["status"] == "SKIP" - ): - continue - outcome, _ = evaluate_result(case, case_rules) - if not case["subtests"] or outcome not in ("PASS", "XFAIL"): - raise ValueError( - f"Cannot update from an incomplete or unresolved case: {name} [{context}]" - ) +from lib.expectations import apply_report +from lib.tests import EXPECTATIONS, discover_tests, read_json, write_json def main(): @@ -139,41 +15,28 @@ def main(): "report", type=Path, help="Browser JSON report from run.py or CI" ) parser.add_argument( - "--manifest", + "--expectations", type=Path, - default=MANIFEST, - help="Base expectations file (default: test/js-api/scripts/expectations.json)", + default=EXPECTATIONS, + help="Expectations file to update (default: test/js-api/scripts/expectations.json)", ) parser.add_argument( - "--require-complete", + "--in-place", action="store_true", - help="Reject reports with missing or unresolved cases (used by CI)", + help="Write the result back to the expectations file instead of stdout", ) args = parser.parse_args() + _, tests = discover_tests() try: - report = read_json(args.report) - browser = report["browser"] - if browser not in BROWSERS or not isinstance(report["results"], list): - raise ValueError("Expected a browser report with a results list") - except (OSError, ValueError, KeyError, TypeError) as error: - parser.error(f"{args.report}: {error}") - - _, tests = discover_suite() - metadata_for = cache(test_metadata) - try: - manifest = read_json(args.manifest) - rules = validate_expectations(manifest, tests, browser, metadata_for) - except (OSError, ValueError) as error: - parser.error(f"{args.manifest}: {error}") - - try: - updated = update_expectations(manifest, rules, report, tests, metadata_for) - updated_rules = validate_expectations(updated, tests, browser, metadata_for) - if args.require_complete: - check_complete_report(report, updated_rules, tests, metadata_for) + updated = apply_report( + read_json(args.expectations), read_json(args.report), tests + ) except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: - parser.error(f"{args.report}: {error}") - print(json.dumps(updated, indent=2)) + parser.error(str(error)) + if args.in_place: + write_json(args.expectations, updated) + else: + print(json.dumps(updated, indent=2)) if __name__ == "__main__":