diff --git a/.github/workflows/ci-js-api.yml b/.github/workflows/ci-js-api.yml new file mode 100644 index 0000000000..6c13bdfb88 --- /dev/null +++ b/.github/workflows/ci-js-api.yml @@ -0,0 +1,201 @@ +name: CI for 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/** + + 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: + 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 + 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 }} + PROPOSE: ${{ (github.event_name == 'schedule' || inputs.refresh) && github.ref_name == github.event.repository.default_branch }} + 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: Select browser version + id: browser + env: + OVERRIDE: ${{ matrix.version }} + run: | + args=(select-version "$BROWSER" --override "$OVERRIDE") + if [[ "$REFRESH" == true ]]; then + args+=(--refresh) + fi + 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 + - name: Run JS API tests + env: + BROWSER_VERSION: ${{ steps.browser.outputs.version }} + SE_SKIP_DRIVER_IN_PATH: 'true' + run: | + 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 proposal job validates the report. + if [[ "$PROPOSE" == 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 + with: + name: wasm-js-api-${{ matrix.browser }} + path: wasm-js-api.json + if-no-files-found: error + + 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: + actions: write + 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: Check the default branch is unchanged + env: + 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 + - 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" + 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" && "$UPDATE_OUTCOME" == success ]]; 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" < { + 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 generate_test_pages(scripts, tests, selected, contexts): + 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 = test_metadata(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 create_driver(browser, browser_version): + 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) + if browser_version and browser != "safari": + options.browser_version = browser_version + + 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 run_browser(browser, browser_version, base_url, cases, rules): + results = [] + counts = Counter() + selected = [ + (case, rules.get((case.name, case.context), {})) for case in cases + ] + has_runnable_cases = any( + case_rules.get(WHOLE_CASE, (None, None))[0] != "skip" for _, case_rules in selected + ) + with ( + create_driver(browser, browser_version) + if has_runnable_cases + else nullcontext() as driver + ): + version = ( + (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 ""), + flush=True, + ) + 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] + else: + result = read_result( + driver, base_url + case.page_path, case.timeout_seconds + ) + outcome, diagnostics = evaluate_result(result, case_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, + } + ) + + 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( + "--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, + 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( + "--summary", type=Path, help="Append a Markdown results table to this file" + ) + parser.add_argument( + "--expectations", + type=Path, + default=EXPECTATIONS, + help="Expectations file (default: test/js-api/scripts/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() + if args.browser_version and not VERSION.fullmatch(args.browser_version): + parser.error("--browser-version must be a version number") + scripts, tests = discover_tests() + + if not args.serve: + try: + # 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.expectations}: {error}") + + contexts = tuple( + context + for context in BROWSER_GLOBALS + if not args.context or context in args.context + ) + try: + pages, cases = generate_test_pages( + scripts, tests, set(args.tests), contexts + ) + except ValueError as error: + parser.error(str(error)) + if not cases: + parser.error("No browser cases matched the selection") + 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: + report, status = run_browser( + args.browser, args.browser_version, base_url, cases, rules + ) + finally: + server.shutdown() + thread.join() + if args.json: + write_json(args.json, report) + if args.summary: + write_summary(args.summary, report) + return status + + +if __name__ == "__main__": + raise SystemExit(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..6619e24372 --- /dev/null +++ b/test/js-api/scripts/update-expectations.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Generate proposed Wasm JS API expectations from a browser JSON report.""" + +import argparse +import json +from pathlib import Path + +from lib.expectations import apply_report +from lib.tests import EXPECTATIONS, discover_tests, read_json, write_json + + +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( + "--expectations", + type=Path, + default=EXPECTATIONS, + help="Expectations file to update (default: test/js-api/scripts/expectations.json)", + ) + parser.add_argument( + "--in-place", + action="store_true", + help="Write the result back to the expectations file instead of stdout", + ) + args = parser.parse_args() + _, tests = discover_tests() + try: + updated = apply_report( + read_json(args.expectations), read_json(args.report), tests + ) + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + parser.error(str(error)) + if args.in_place: + write_json(args.expectations, updated) + else: + print(json.dumps(updated, indent=2)) + + +if __name__ == "__main__": + 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:])