Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
456bb81c10 | ||
|
|
8ca47cba13 | ||
|
|
e2e1c49db6 | ||
|
|
041010070c | ||
|
|
9ea819445f | ||
|
|
2ec1a9026b | ||
|
|
f0d25a86ff | ||
|
|
ca0c6e33f8 | ||
|
|
46cf6a579a | ||
|
|
0a031d2688 | ||
|
|
a9e56c0b21 | ||
|
|
04b7a79b66 | ||
|
|
2c5cd5ea79 | ||
|
|
877027f9f4 | ||
|
|
0e48424da8 | ||
|
|
43e1b355a3 | ||
|
|
ebfd0fa573 | ||
|
|
b699439355 | ||
|
|
7031c911c7 | ||
|
|
464e0b132b |
No files matched your search
@@ -28,27 +28,28 @@
|
||||
# version with content nobody compared, which is the exact failure mode the
|
||||
# `==` specifier was adopted to expose.
|
||||
#
|
||||
# So this workflow asks the index and reports a verdict: the job is green only
|
||||
# when the pinned core is on the index, and RED in every other case. There is no
|
||||
# "skip" outcome and no output a caller can read to skip itself (rule ci-13:
|
||||
# nothing counts as passed that did not pass). Outcomes:
|
||||
# So this workflow asks the index and reports a verdict, and the callers make
|
||||
# their real jobs depend on it. Three outcomes, all of them visible:
|
||||
#
|
||||
# the project is not on the index at all
|
||||
# -> red. During the publish window (the core is uploaded first, this
|
||||
# package after it) no install here can succeed, so the run says so and
|
||||
# fails; re-run it once the core's publish has finished. The callers
|
||||
# `need` this job, so they do not run, and the `gate` of tests.yml
|
||||
# refuses a skipped job.
|
||||
# -> the publish window. This job passes, emits a ::warning:: annotation
|
||||
# on the run page, writes the reason into the run summary, and returns
|
||||
# available=false. Every caller job is then SKIPPED - grey in the
|
||||
# checks list, not green - and the summary says in words that no tests
|
||||
# ran. Nobody can mistake it for a passing build.
|
||||
#
|
||||
# the project is on the index and carries the pinned version
|
||||
# -> green. Every caller job runs exactly as it did before this file
|
||||
# existed. Nothing is weakened, ever.
|
||||
# -> available=true. Every caller job runs exactly as it did before this
|
||||
# file existed. Nothing is weakened, ever.
|
||||
#
|
||||
# the project is on the index but NOT at the pinned version
|
||||
# -> red: the pin names a version that was never uploaded.
|
||||
# -> this is not the window. The core has been published, so the pin
|
||||
# names a version that was never uploaded. Hard failure, red.
|
||||
#
|
||||
# Anything ambiguous (index unreachable, malformed answer, no `==` pin in
|
||||
# pyproject.toml, two of them) is also a hard failure.
|
||||
# pyproject.toml, two of them) is also a hard failure. A gate that answers
|
||||
# "skip" when it does not know would silently disable this repo's whole CI the
|
||||
# first time PyPI has a bad minute.
|
||||
#
|
||||
# This does NOT stop being useful once the core is published: it is the check
|
||||
# that catches a pin pointing at a version that does not exist, about 20s
|
||||
@@ -59,6 +60,12 @@ name: core-on-index
|
||||
on:
|
||||
workflow_call:
|
||||
outputs:
|
||||
available:
|
||||
description: >-
|
||||
"true" when the invisible-core version pinned in pyproject.toml can
|
||||
be resolved from the package index. Any other value means the caller
|
||||
must not attempt an install.
|
||||
value: ${{ jobs.probe.outputs.available }}
|
||||
pin:
|
||||
description: The invisible-core version this repo pins.
|
||||
value: ${{ jobs.probe.outputs.pin }}
|
||||
@@ -72,6 +79,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
available: ${{ steps.probe.outputs.available }}
|
||||
pin: ${{ steps.probe.outputs.pin }}
|
||||
steps:
|
||||
# SHA-pinned like e2e.yml: this job decides whether the rest of the repo's
|
||||
@@ -159,20 +167,29 @@ jobs:
|
||||
f"verdict, so this job fails instead of guessing. Re-run it.")
|
||||
|
||||
if unpublished:
|
||||
die(f"FAIL core-on-index: the pinned {DIST} {pin} is not on the index. "
|
||||
f"Fix: wait for its publish to finish, or pin a published core. "
|
||||
f"Rule: ci-13 nothing counts as passed that did not pass")
|
||||
msg = (f"{DIST} has never been published to the index. This is the "
|
||||
f"expected publish window: the core is uploaded first, this "
|
||||
f"repo's package after it.")
|
||||
print(f"::warning title={DIST} is not on the index yet::{msg} "
|
||||
f"NOTHING WAS INSTALLED AND NO TEST RAN in this workflow run.")
|
||||
write("GITHUB_STEP_SUMMARY",
|
||||
f"### NO TESTS RAN\n\n{msg}\n\n"
|
||||
f"Every job in this workflow was **skipped**, not passed. "
|
||||
f"`pyproject.toml` pins `{DIST}=={pin}`; until that version is on "
|
||||
f"the index no `pip install` in this repository can resolve, so "
|
||||
f"there is nothing to run. Publish `{DIST}=={pin}`, then re-run "
|
||||
f"this workflow - the jobs come back on their own, with no edit "
|
||||
f"to any file here.\n")
|
||||
write("GITHUB_OUTPUT", "available=false")
|
||||
sys.exit(0)
|
||||
|
||||
versions = data.get("versions")
|
||||
if not versions:
|
||||
die(f"{url} answered but listed no versions. The index API changed shape "
|
||||
f"or served something unexpected; refusing to guess.")
|
||||
f"or served something unexpected; refusing to turn that into a skip.")
|
||||
if pin not in versions:
|
||||
shown = sorted(versions)[-10:] # diagnostics only, so a plain sort
|
||||
die(f"FAIL core-on-index: the pinned {DIST} {pin} is not on the index. "
|
||||
f"Fix: wait for its publish to finish, or pin a published core. "
|
||||
f"Rule: ci-13 nothing counts as passed that did not pass. "
|
||||
f"Detail: pyproject.toml pins {DIST}=={pin}, but the index publishes "
|
||||
die(f"pyproject.toml pins {DIST}=={pin}, but the index publishes "
|
||||
f"{len(versions)} version(s) ({', '.join(shown)}) and not {pin}. "
|
||||
f"{DIST} exists, so this is NOT the "
|
||||
f"publish window - the pin names a version that was never uploaded. "
|
||||
@@ -180,9 +197,11 @@ jobs:
|
||||
f"the core first.")
|
||||
|
||||
print(f"{DIST}=={pin} is on the index - the workflow runs normally.")
|
||||
write("GITHUB_OUTPUT", "available=true")
|
||||
PY
|
||||
|
||||
- name: Say so in the run summary
|
||||
if: steps.probe.outputs.available == 'true'
|
||||
run: |
|
||||
echo "invisible-core==${{ steps.probe.outputs.pin }} is on the index; jobs run normally." \
|
||||
>> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -22,6 +22,15 @@
|
||||
# Windows runner separates the two without asking anyone to stay off it
|
||||
# for six hours.
|
||||
#
|
||||
# A second use, chosen by the input `ab_network_webrtc_seed` (empty = the loop
|
||||
# above, as always): the network oracle's WebRTC walk of that seed, alone,
|
||||
# `runs` times for each engine of its A/A (the published engine twice). It
|
||||
# exists to tell two readings apart when the A/A of that walk differs from
|
||||
# itself in the number of TURN Allocate datagrams (scripts/ci_ab_network.py:
|
||||
# AB_NETWORK_HUNT): each repetition keeps every datagram with its time and its
|
||||
# STUN transaction id and the page's own ICE times (network/hunt/<engine>-<i>.json,
|
||||
# summary in network/hunt/summary.json). It decides nothing: the step exits 0.
|
||||
#
|
||||
# Doesn't start on its own: `workflow_dispatch` only. It's not a gate, it's
|
||||
# an investigation tool, and it must not be added to the required contexts.
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@@ -34,6 +43,10 @@ on:
|
||||
description: "How many runs at most (at 12% it takes ~18 for a 90% chance)"
|
||||
required: false
|
||||
default: "18"
|
||||
ab_network_webrtc_seed:
|
||||
description: "A seed (e.g. 4) to repeat ONLY the network oracle's WebRTC walk of, `runs` times for each engine of its A/A, instead of the e2e loop. Empty: the e2e loop."
|
||||
required: false
|
||||
default: ""
|
||||
os:
|
||||
description: "Where to hunt. windows-latest answers a DIFFERENT question: are the interaction retries seen on the dev machine the product or contention?"
|
||||
required: false
|
||||
@@ -121,10 +134,29 @@ jobs:
|
||||
sudo apt-get $APT update
|
||||
sudo cp /tmp/linux-deps/*.deb /var/cache/apt/archives/
|
||||
sudo apt-get $APT install -y --no-download --no-install-recommends $(cat /tmp/linux-deps/roots.txt)
|
||||
- name: The security state (a fixed directory of the repository)
|
||||
if: inputs.ab_network_webrtc_seed != ''
|
||||
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
if: inputs.ab_network_webrtc_seed != ''
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
|
||||
# The hunt of the network oracle's WebRTC walk: instead of the loop below, never with it. `runs` is the number of repetitions per engine.
|
||||
- name: The network oracle's WebRTC walk of one seed, repeated (decides nothing)
|
||||
if: inputs.ab_network_webrtc_seed != ''
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
AB_NETWORK_HUNT: webrtc:${{ inputs.ab_network_webrtc_seed }}:${{ inputs.runs }}
|
||||
run: |
|
||||
set -u
|
||||
if [ "$RUNNER_OS" = "Linux" ]; then PRE="xvfb-run -a"; else PRE=""; fi
|
||||
mkdir -p network
|
||||
$PRE python -u scripts/ci_ab_network.py ab --a-a --out network --published-binary "$FF"
|
||||
|
||||
- name: Loop until it catches one
|
||||
if: inputs.ab_network_webrtc_seed == ''
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
INVPW_TEST_WATCHDOG_FILE: evidence/e2e-watchdog.log
|
||||
@@ -179,3 +211,12 @@ jobs:
|
||||
evidence/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
- name: Upload the hunt of the network oracle's WebRTC walk
|
||||
if: always() && inputs.ab_network_webrtc_seed != ''
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: e2e-hunt-network-webrtc-${{ inputs.os }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: network/hunt
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
+144
-135
@@ -1,9 +1,6 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# e2e.yml - run the FULL browser-driving e2e suite (the 127 @pytest.mark.e2e)
|
||||
# on GitHub, in the merge queue run of every change to main and on every push to main.
|
||||
# A pull request runs the fast set (tests.yml); this workflow is too heavy for every push to a
|
||||
# pull request, so it runs when the change enters the merge queue (`merge_group`), and that run
|
||||
# decides: its ONE verdict is the job `e2e verdict`.
|
||||
# on GitHub, on every push/PR to main.
|
||||
#
|
||||
# Why this can run on CI when the drive-gate had to stay light: the drive-gate
|
||||
# launched Firefox in true HEADLESS mode, which is content-process unstable on
|
||||
@@ -25,9 +22,16 @@ on:
|
||||
- '**.md'
|
||||
- 'docs/**'
|
||||
- 'LICENSE'
|
||||
# The merge queue run. GitHub applies no `paths` or `paths-ignore` to it, so a docs-only change runs the whole set here too.
|
||||
merge_group:
|
||||
types: [checks_requested]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
# The same filter as `push` above, which had it and this one did not. A
|
||||
# docs-only PR (#54, deleting the Pages site) therefore spun up the full
|
||||
# browser bench, hung, and burned the whole 40-minute timeout on a change no
|
||||
# test can observe. The filter belongs on BOTH triggers or it is not a filter.
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'docs/**'
|
||||
- 'LICENSE'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
only:
|
||||
@@ -42,20 +46,22 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Nothing cancels this workflow: a merge queue run is keyed by its own ref
|
||||
# (one per queue entry, `gh-readonly-queue/...`) and never cancelled in
|
||||
# progress, and the run of a push is unique to the run (`github.run_id`).
|
||||
# A newer push to a pull request cancels the older in-flight run of THIS
|
||||
# workflow on that pull request as a whole, cleanly, instead of leaving its
|
||||
# queued jobs to be cancelled one by one - which left the run marked failed even
|
||||
# though nothing had actually failed. Keyed by workflow + pull request number,
|
||||
# so tests and e2e never cancel each other.
|
||||
#
|
||||
# NEVER on main. The release gate (scripts/e2e_is_green.py) asks for the e2e
|
||||
# check-run of the commit being tagged, and a cancelled one refuses the release:
|
||||
# with the group keyed by ref, the next push to main cancelled the run of the
|
||||
# commit before it. Outside the merge queue the group is unique to the run
|
||||
# commit before it. Outside a pull request the group is unique to the run
|
||||
# (`github.run_id`), so every commit of main keeps its own finished run, and a
|
||||
# pending run is not replaced by a newer one either (a group with a fixed name
|
||||
# drops the older pending run, cancel or not).
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'merge_group' && github.ref || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
@@ -66,46 +72,12 @@ env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# THE FIRST JOB: does this change have anything for the workflow to test? GitHub applies no `paths` filter to a merge queue run, so a docs-only change would
|
||||
# run everything here. In a queue run scripts/ci_changes.py lists the files of the entry (base_sha..head_sha) and applies the path rules of the `push` trigger
|
||||
# above; on any other event it says run=true. `run=false` is an explicit "nothing to test", not a skip: every other job needs this one and runs only on
|
||||
# run == 'true', and `e2e verdict` (scripts/ci_gate.py, CHANGES_RUN) expects them all skipped then, and red otherwise. The script is read from main, never
|
||||
# from the branch it judges (a branch must not decide that it needs no test); while it is not on main yet the copy of this branch is used, and the log says so.
|
||||
changes:
|
||||
name: changes
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
run: ${{ steps.changes.outputs.run }}
|
||||
files: ${{ steps.changes.outputs.files }}
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- name: does the change touch anything this workflow tests
|
||||
id: changes
|
||||
shell: bash
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
HEAD_SHA: ${{ github.event.merge_group.head_sha }}
|
||||
run: |
|
||||
git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main
|
||||
if git cat-file -e origin/main:scripts/ci_changes.py 2>/dev/null; then
|
||||
git show origin/main:scripts/ci_changes.py > "$RUNNER_TEMP/ci_changes.py"
|
||||
else
|
||||
echo "ci_changes.py is not on origin/main yet: falling back to the copy of this branch"
|
||||
cp scripts/ci_changes.py "$RUNNER_TEMP/ci_changes.py"
|
||||
fi
|
||||
python3 "$RUNNER_TEMP/ci_changes.py" e2e "$EVENT_NAME" "$BASE_SHA" "$HEAD_SHA" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
# The install below resolves `invisible-core==N.M.0` from the package index,
|
||||
# and the core is published BEFORE this package. This gate answers whether it
|
||||
# is on the index yet; during that window this job FAILS (rule ci-13: a core
|
||||
# that is not on the index is red, never a skip) and the e2e jobs, which
|
||||
# need it, do not run; once the core is up it runs unchanged. See .github/workflows/core-on-index.yml.
|
||||
# is on the index yet; during that window the e2e job is SKIPPED with the
|
||||
# reason in the run summary rather than faked green, and once the core is up
|
||||
# it runs unchanged. See .github/workflows/core-on-index.yml.
|
||||
core-on-index:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.run == 'true'
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
|
||||
# THE UBUNTU PACKAGES OF THE LINUX JOBS, from Ubuntu's archive once per runner image and list (linux-deps.yml), never by a job: a run lost a green leg to its time
|
||||
@@ -114,8 +86,8 @@ jobs:
|
||||
# Playwright's install-deps names for Firefox. The jobs install its roots by name from that repository, with --no-download.
|
||||
linux-deps-e2e:
|
||||
name: linux-deps-e2e
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
uses: ./.github/workflows/linux-deps.yml
|
||||
with:
|
||||
name: e2e
|
||||
@@ -131,8 +103,8 @@ jobs:
|
||||
# branch protection read.
|
||||
e2e-linux:
|
||||
name: e2e (linux, part ${{ matrix.part }})
|
||||
needs: [changes, core-on-index, linux-deps-e2e]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: [core-on-index, linux-deps-e2e]
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
@@ -144,14 +116,14 @@ jobs:
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
# The A/A of the three A/B oracles (page, network, host) runs on the first seeds of the candidate set in the merge queue run, and on ALL of them when the change
|
||||
# touches a file of that oracle (scripts/ci_ab_pr_seeds.py holds the lists). The checkout is shallow, so the script fetches the base commit of the queue entry and lists the files that
|
||||
# differ from it (`git diff --name-only <base> HEAD`: HEAD is the merge group commit, so this is the change of the entry); the tests read the variables it prints.
|
||||
# The A/A of the three A/B oracles (page, network, host) runs on the first seeds of the candidate set on a pull request, and on ALL of them when the pull request
|
||||
# changes a file of that oracle (scripts/ci_ab_pr_seeds.py holds the lists). The checkout is shallow, so the script fetches the base commit and lists the files that
|
||||
# differ from it (`git diff --name-only <base> HEAD`: HEAD is the merge commit, so this is the pull request's own change); the tests read the variables it prints.
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -396,12 +368,13 @@ jobs:
|
||||
# it is green only when every part is green. `needs.e2e-linux.result` is the result of the matrix as a whole (`success` only when every part succeeded;
|
||||
# one failed, cancelled or skipped part makes it something else), and anything but `success` is red here: a cancelled part measured nothing, a skipped
|
||||
# one ran nothing. `always()` so that a red or cancelled part still reaches this job and turns it red instead of skipping it, which reads as not red.
|
||||
# The gate of the core on the index stays the same as for the parts: while the pinned core is not on the index core-on-index is red and the parts are skipped, so this job (always()) sees their result `skipped` and fails (rule ci-13).
|
||||
# The gate of the core on the index stays the same as for the parts: while the pinned core is not on the index the parts are skipped with the reason in
|
||||
# the summary (core-on-index.yml), and so is this job, as the Linux job was before the split.
|
||||
# tests/test_ci_runs_once_per_commit.py (5.) holds this job.
|
||||
e2e:
|
||||
name: e2e (linux, xvfb)
|
||||
needs: [changes, core-on-index, e2e-linux]
|
||||
if: always() && needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: [core-on-index, e2e-linux]
|
||||
if: always() && needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
@@ -418,11 +391,12 @@ jobs:
|
||||
# ``Control+A`` selects all in a field, on the PUBLISHED engine and the core this package pins, on Windows, where the keyboard of a real
|
||||
# user is: the shortcut letter used to reach the browser as Control+Shift+A (invisible-core 63.66.0 fixes it). The e2e is red on the
|
||||
# keyboard that held Shift for the capital A (tests/test_control_a_selects_all_in_a_field_e2e.py: 5 ways to press it x an <input> and a
|
||||
# <textarea>, in-process and served to the stock Playwright client). Same gate as the Linux job: it needs core-on-index, which fails until the core is on the index, and it runs unchanged after; `workflow_dispatch` with `only: windows-control-a` runs it alone.
|
||||
# <textarea>, in-process and served to the stock Playwright client). Same gate as the Linux job: it is SKIPPED, with the reason in the
|
||||
# summary, until the core is on the index, and it runs unchanged after; `workflow_dispatch` with `only: windows-control-a` runs it alone.
|
||||
e2e-windows-control-a:
|
||||
name: e2e (windows, Control+A)
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true'
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
|
||||
@@ -437,6 +411,17 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
# The runner's screen (1024x768 by default) is smaller than the browser window the e2e open (1936x1048 for a 1920x1080 identity), so the
|
||||
# OS cursor cannot be parked outside it (tests/_os_cursor.py) and a native move for it reaches the page. 1920x1080 is the largest mode the
|
||||
# runner's video device accepts (run 45730213378 of oss-invisible/playwright): it leaves the strip below the window free. Declared here, read back.
|
||||
- name: The runner's screen is 1920x1080, larger than the browser window is tall (read back)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Set-DisplayResolution -Width 1920 -Height 1080 -Force
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$b = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
||||
"the runner's screen: $($b.Width)x$($b.Height) at $($b.X),$($b.Y)"
|
||||
if ($b.Width -lt 1920 -or $b.Height -lt 1080) { Write-Error "the runner's screen is $($b.Width)x$($b.Height), not 1920x1080: the OS cursor could not be parked outside the browser window"; exit 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install wrapper + test deps (the stock client is in the dev extra)
|
||||
@@ -464,8 +449,8 @@ jobs:
|
||||
# partition whole and tests/test_every_suite_runs_on_linux_and_windows.py holds both systems together.
|
||||
e2e-windows:
|
||||
name: e2e (windows, part ${{ matrix.part }})
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 40
|
||||
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
|
||||
@@ -483,16 +468,27 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
# The runner's screen (1024x768 by default) is smaller than the browser window the e2e open (1936x1048 for a 1920x1080 identity), so the
|
||||
# OS cursor cannot be parked outside it (tests/_os_cursor.py) and a native move for it reaches the page. 1920x1080 is the largest mode the
|
||||
# runner's video device accepts (run 45730213378 of oss-invisible/playwright): it leaves the strip below the window free. Declared here, read back.
|
||||
- name: The runner's screen is 1920x1080, larger than the browser window is tall (read back)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Set-DisplayResolution -Width 1920 -Height 1080 -Force
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$b = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
||||
"the runner's screen: $($b.Width)x$($b.Height) at $($b.X),$($b.Y)"
|
||||
if ($b.Width -lt 1920 -or $b.Height -lt 1080) { Write-Error "the runner's screen is $($b.Width)x$($b.Height), not 1920x1080: the OS cursor could not be parked outside the browser window"; exit 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
# The A/A of the three A/B oracles (page, network, host) runs on the first seeds of the candidate set in the merge queue run, and on ALL of them when the change
|
||||
# touches a file of that oracle (scripts/ci_ab_pr_seeds.py holds the lists). The checkout is shallow, so the script fetches the base commit of the queue entry and lists the files that
|
||||
# differ from it (`git diff --name-only <base> HEAD`: HEAD is the merge group commit, so this is the change of the entry); the tests read the variables it prints.
|
||||
# The A/A of the three A/B oracles (page, network, host) runs on the first seeds of the candidate set on a pull request, and on ALL of them when the pull request
|
||||
# changes a file of that oracle (scripts/ci_ab_pr_seeds.py holds the lists). The checkout is shallow, so the script fetches the base commit and lists the files that
|
||||
# differ from it (`git diff --name-only <base> HEAD`: HEAD is the merge commit, so this is the pull request's own change); the tests read the variables it prints.
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -564,8 +560,8 @@ jobs:
|
||||
# above, `own_job` in the Windows parts). The same setup as the shared jobs: the security state, the engine, the GeoIP database made by the repository.
|
||||
e2e-network:
|
||||
name: e2e (network, linux)
|
||||
needs: [changes, core-on-index, linux-deps-e2e]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: [core-on-index, linux-deps-e2e]
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
# the network oracle's own guard (2197 s, two engine runs: the measured runs 45121964904 and 45153612447 plus 25%) and the job's own steps, with room for a slow runner
|
||||
timeout-minutes: 50
|
||||
@@ -575,10 +571,10 @@ jobs:
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -655,8 +651,8 @@ jobs:
|
||||
|
||||
e2e-network-windows:
|
||||
name: e2e (network, windows)
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
# the network oracle's own guard (2197 s, two engine runs: the measured runs 45121964904 and 45153612447 plus 25%) and the job's own steps, with room for a slow runner
|
||||
timeout-minutes: 50
|
||||
@@ -666,13 +662,24 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
# The runner's screen (1024x768 by default) is smaller than the browser window the e2e open (1936x1048 for a 1920x1080 identity), so the
|
||||
# OS cursor cannot be parked outside it (tests/_os_cursor.py) and a native move for it reaches the page. 1920x1080 is the largest mode the
|
||||
# runner's video device accepts (run 45730213378 of oss-invisible/playwright): it leaves the strip below the window free. Declared here, read back.
|
||||
- name: The runner's screen is 1920x1080, larger than the browser window is tall (read back)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Set-DisplayResolution -Width 1920 -Height 1080 -Force
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$b = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
||||
"the runner's screen: $($b.Width)x$($b.Height) at $($b.X),$($b.Y)"
|
||||
if ($b.Width -lt 1920 -or $b.Height -lt 1080) { Write-Error "the runner's screen is $($b.Width)x$($b.Height), not 1920x1080: the OS cursor could not be parked outside the browser window"; exit 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -728,8 +735,8 @@ jobs:
|
||||
# 35 for the test.
|
||||
e2e-host:
|
||||
name: e2e (host, linux)
|
||||
needs: [changes, core-on-index, linux-deps-e2e]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: [core-on-index, linux-deps-e2e]
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 65
|
||||
steps:
|
||||
@@ -738,10 +745,10 @@ jobs:
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -838,8 +845,8 @@ jobs:
|
||||
|
||||
e2e-host-windows:
|
||||
name: e2e (host, windows)
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 45
|
||||
defaults:
|
||||
@@ -848,13 +855,24 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
# The runner's screen (1024x768 by default) is smaller than the browser window the e2e open (1936x1048 for a 1920x1080 identity), so the
|
||||
# OS cursor cannot be parked outside it (tests/_os_cursor.py) and a native move for it reaches the page. 1920x1080 is the largest mode the
|
||||
# runner's video device accepts (run 45730213378 of oss-invisible/playwright): it leaves the strip below the window free. Declared here, read back.
|
||||
- name: The runner's screen is 1920x1080, larger than the browser window is tall (read back)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Set-DisplayResolution -Width 1920 -Height 1080 -Force
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$b = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
||||
"the runner's screen: $($b.Width)x$($b.Height) at $($b.X),$($b.Y)"
|
||||
if ($b.Width -lt 1920 -or $b.Height -lt 1080) { Write-Error "the runner's screen is $($b.Width)x$($b.Height), not 1920x1080: the OS cursor could not be parked outside the browser window"; exit 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -977,8 +995,8 @@ jobs:
|
||||
# `own_job` in the Windows parts). 45 minutes for the job, as the host oracle's: the setup of the job plus the guard of the test with the margin of Windows. The same setup as the shared jobs.
|
||||
e2e-page:
|
||||
name: e2e (page oracle, linux)
|
||||
needs: [changes, core-on-index, linux-deps-e2e]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: [core-on-index, linux-deps-e2e]
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
@@ -987,10 +1005,10 @@ jobs:
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -1067,8 +1085,8 @@ jobs:
|
||||
|
||||
e2e-page-windows:
|
||||
name: e2e (page oracle, windows)
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true' && inputs.only != 'windows-control-a'
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 45
|
||||
defaults:
|
||||
@@ -1077,13 +1095,24 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
# The runner's screen (1024x768 by default) is smaller than the browser window the e2e open (1936x1048 for a 1920x1080 identity), so the
|
||||
# OS cursor cannot be parked outside it (tests/_os_cursor.py) and a native move for it reaches the page. 1920x1080 is the largest mode the
|
||||
# runner's video device accepts (run 45730213378 of oss-invisible/playwright): it leaves the strip below the window free. Declared here, read back.
|
||||
- name: The runner's screen is 1920x1080, larger than the browser window is tall (read back)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Set-DisplayResolution -Width 1920 -Height 1080 -Force
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$b = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
||||
"the runner's screen: $($b.Width)x$($b.Height) at $($b.X),$($b.Y)"
|
||||
if ($b.Width -lt 1920 -or $b.Height -lt 1080) { Write-Error "the runner's screen is $($b.Width)x$($b.Height), not 1920x1080: the OS cursor could not be parked outside the browser window"; exit 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)
|
||||
if: github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
@@ -1146,8 +1175,8 @@ jobs:
|
||||
# Seed 0 is in shard 1, and its second launch on a reused profile is part of that shard's A/A.
|
||||
e2e-page-final-touched:
|
||||
name: e2e (page oracle, is it touched)
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true' && github.event_name == 'merge_group' && inputs.only != 'windows-control-a'
|
||||
needs: core-on-index
|
||||
if: github.event_name == 'pull_request' && needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
@@ -1157,17 +1186,17 @@ jobs:
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Does the change touch a file of the page oracle
|
||||
- name: Does the pull request change a file of the page oracle
|
||||
id: touched
|
||||
shell: bash
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: python scripts/ci_ab_oracle.py touched "$BASE_SHA" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
e2e-page-final:
|
||||
name: e2e (page oracle, final seeds ${{ matrix.shard }}/4, linux)
|
||||
needs: [changes, core-on-index, e2e-page-final-touched, linux-deps-e2e]
|
||||
if: needs.changes.outputs.run == 'true' && needs.e2e-page-final-touched.outputs.touched == 'true'
|
||||
needs: [core-on-index, e2e-page-final-touched, linux-deps-e2e]
|
||||
if: needs.core-on-index.outputs.available == 'true' && needs.e2e-page-final-touched.outputs.touched == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
@@ -1256,8 +1285,8 @@ jobs:
|
||||
|
||||
e2e-page-final-windows:
|
||||
name: e2e (page oracle, final seeds ${{ matrix.shard }}/4, windows)
|
||||
needs: [changes, core-on-index, e2e-page-final-touched]
|
||||
if: needs.changes.outputs.run == 'true' && needs.e2e-page-final-touched.outputs.touched == 'true'
|
||||
needs: [core-on-index, e2e-page-final-touched]
|
||||
if: needs.core-on-index.outputs.available == 'true' && needs.e2e-page-final-touched.outputs.touched == 'true'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
@@ -1270,6 +1299,17 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
# The runner's screen (1024x768 by default) is smaller than the browser window the e2e open (1936x1048 for a 1920x1080 identity), so the
|
||||
# OS cursor cannot be parked outside it (tests/_os_cursor.py) and a native move for it reaches the page. 1920x1080 is the largest mode the
|
||||
# runner's video device accepts (run 45730213378 of oss-invisible/playwright): it leaves the strip below the window free. Declared here, read back.
|
||||
- name: The runner's screen is 1920x1080, larger than the browser window is tall (read back)
|
||||
shell: pwsh
|
||||
run: |
|
||||
Set-DisplayResolution -Width 1920 -Height 1080 -Force
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$b = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
||||
"the runner's screen: $($b.Width)x$($b.Height) at $($b.X),$($b.Y)"
|
||||
if ($b.Width -lt 1920 -or $b.Height -lt 1080) { Write-Error "the runner's screen is $($b.Width)x$($b.Height), not 1920x1080: the OS cursor could not be parked outside the browser window"; exit 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
@@ -1320,34 +1360,3 @@ jobs:
|
||||
${{ runner.temp }}/page-final-e2e.xml
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
# THE VERDICT of the workflow, the only one that decides (rule ci-13, nothing counts as passed that did not pass). It waits for EVERY job of this file, and
|
||||
# `if: always()` makes sure a failed, cancelled or skipped one still reaches it. Each must end in `success`; only the jobs scripts/ci_gate.py names as
|
||||
# conditional by design may be `skipped` (the final-seed shards when the page oracle is not touched, and what `only: windows-control-a` leaves out).
|
||||
# The judge is read from main, never from the branch it judges; while the file is not on main yet (the change that adds it) the copy of this branch is
|
||||
# used, and the log says so. `e2e (linux, xvfb)` above stays the Linux check the release reads (scripts/e2e_is_green.py).
|
||||
verdict:
|
||||
name: e2e verdict
|
||||
needs: [changes, core-on-index, linux-deps-e2e, e2e-linux, e2e, e2e-windows-control-a, e2e-windows, e2e-network, e2e-network-windows, e2e-host, e2e-host-windows, e2e-page, e2e-page-windows, e2e-page-final-touched, e2e-page-final, e2e-page-final-windows]
|
||||
if: always()
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- name: refuse unless every needed job succeeded
|
||||
env:
|
||||
NEEDS: ${{ toJSON(needs) }}
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
WORKFLOW: e2e
|
||||
CHANGES_RUN: ${{ needs.changes.outputs.run }}
|
||||
INPUT_ONLY: ${{ inputs.only }}
|
||||
run: |
|
||||
git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main
|
||||
if git cat-file -e origin/main:scripts/ci_gate.py 2>/dev/null; then
|
||||
git show origin/main:scripts/ci_gate.py > "$RUNNER_TEMP/ci_gate.py"
|
||||
else
|
||||
echo "ci_gate.py is not on origin/main yet: falling back to the copy of this branch"
|
||||
cp scripts/ci_gate.py "$RUNNER_TEMP/ci_gate.py"
|
||||
fi
|
||||
python3 "$RUNNER_TEMP/ci_gate.py"
|
||||
@@ -11,10 +11,9 @@
|
||||
# WHICH ENGINE. The published one (`python -m invisible_playwright fetch`), as e2e.yml. The candidate of the engine repository runs the same entry on its own
|
||||
# binary (scripts/run_fakeweb.py --binary), and judges the four e2e tests of this fake web as the suite `wrapper.e2e.fakeweb` of ci/required-suites.json.
|
||||
#
|
||||
# WHEN. The merge queue run of every change to main (`merge_group`: GitHub applies no `paths` filter to it, so every queue entry runs it, and that run decides), and a
|
||||
# push to main that touches the fake web or this file; again by hand with `workflow_dispatch`. A pull request does not run it: a pull request runs the fast set
|
||||
# (tests.yml). Four legs, a profile on a system each (Linux under Xvfb, Windows); no leg is repeated or forgiven, and the ONE verdict of the workflow is the
|
||||
# job `fakeweb verdict`: red unless every job of the workflow is green (a skipped leg, for a core that is not on the index yet, is not green: nothing was measured).
|
||||
# WHEN. A pull request or a push to main that touches the fake web or this file (the journey and the hard pages are not a round for every change); again by hand
|
||||
# with `workflow_dispatch`. Four legs, a profile on a system each (Linux under Xvfb, Windows); no leg is repeated or forgiven, and the ONE verdict of the workflow is the
|
||||
# job `fakeweb verdict`: red unless all four legs are green (a skipped leg, for a core that is not on the index yet, is not green: nothing was measured).
|
||||
|
||||
name: fakeweb
|
||||
|
||||
@@ -28,66 +27,37 @@ on:
|
||||
- 'scripts/fakeweb_p4_report.py'
|
||||
- 'scripts/playwright_pin.txt'
|
||||
- '.github/workflows/fakeweb.yml'
|
||||
merge_group:
|
||||
types: [checks_requested]
|
||||
pull_request:
|
||||
paths:
|
||||
- 'tests/fakeweb/**'
|
||||
- 'tests/test_fakeweb_*.py'
|
||||
- 'scripts/run_fakeweb.py'
|
||||
- 'scripts/fakeweb_p4_report.py'
|
||||
- 'scripts/playwright_pin.txt'
|
||||
- '.github/workflows/fakeweb.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Nothing cancels this workflow (the same group as e2e.yml): a merge queue run is keyed by its own ref (one per queue entry) and never cancelled in progress,
|
||||
# and the run of a push is unique to the run.
|
||||
# A newer push to a pull request cancels the older run of THIS workflow on that pull request, and nothing else cancels (the same group as e2e.yml).
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'merge_group' && github.ref || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# The engine download goes through the release API with the token of the job (anonymous requests are the ones GitHub drops first).
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# THE FIRST JOB: does this change have anything for the workflow to test? GitHub applies no `paths` filter to a merge queue run, so a docs-only change would
|
||||
# run everything here. In a queue run scripts/ci_changes.py lists the files of the entry (base_sha..head_sha) and applies the path rules of the `push` trigger
|
||||
# above; on any other event it says run=true. `run=false` is an explicit "nothing to test", not a skip: every other job needs this one and runs only on
|
||||
# run == 'true', and `fakeweb verdict` (scripts/ci_gate.py, CHANGES_RUN) expects them all skipped then, and red otherwise. The script is read from main, never
|
||||
# from the branch it judges (a branch must not decide that it needs no test); while it is not on main yet the copy of this branch is used, and the log says so.
|
||||
changes:
|
||||
name: changes
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
run: ${{ steps.changes.outputs.run }}
|
||||
files: ${{ steps.changes.outputs.files }}
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- name: does the change touch anything this workflow tests
|
||||
id: changes
|
||||
shell: bash
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
BASE_SHA: ${{ github.event.merge_group.base_sha }}
|
||||
HEAD_SHA: ${{ github.event.merge_group.head_sha }}
|
||||
run: |
|
||||
git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main
|
||||
if git cat-file -e origin/main:scripts/ci_changes.py 2>/dev/null; then
|
||||
git show origin/main:scripts/ci_changes.py > "$RUNNER_TEMP/ci_changes.py"
|
||||
else
|
||||
echo "ci_changes.py is not on origin/main yet: falling back to the copy of this branch"
|
||||
cp scripts/ci_changes.py "$RUNNER_TEMP/ci_changes.py"
|
||||
fi
|
||||
python3 "$RUNNER_TEMP/ci_changes.py" fakeweb "$EVENT_NAME" "$BASE_SHA" "$HEAD_SHA" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
core-on-index:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.run == 'true'
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
|
||||
# The Ubuntu packages of the Linux legs, from Ubuntu's archive once per runner image and list (linux-deps.yml), never by a leg.
|
||||
linux-deps-fakeweb:
|
||||
name: linux-deps-fakeweb
|
||||
needs: [changes, core-on-index]
|
||||
if: needs.changes.outputs.run == 'true'
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
uses: ./.github/workflows/linux-deps.yml
|
||||
with:
|
||||
name: fakeweb
|
||||
@@ -96,8 +66,8 @@ jobs:
|
||||
|
||||
walk:
|
||||
name: fakeweb ${{ matrix.profile }} (${{ matrix.os }})
|
||||
needs: [changes, core-on-index, linux-deps-fakeweb]
|
||||
if: needs.changes.outputs.run == 'true'
|
||||
needs: [core-on-index, linux-deps-fakeweb]
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
@@ -205,29 +175,19 @@ jobs:
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# THE VERDICT of the workflow, the only one that decides (rule ci-13): it waits for EVERY job of this file, `if: always()` so that a failed, cancelled or skipped
|
||||
# one still reaches it, and each must end in `success` (a leg that did not run measured nothing). scripts/ci_gate.py judges it, read from main and never from
|
||||
# the branch it judges; while the file is not on main yet (the change that adds it) the copy of this branch is used, and the log says so.
|
||||
# THE VERDICT of the workflow, the only one: green only when all four legs ran and passed.
|
||||
verdict:
|
||||
name: fakeweb verdict
|
||||
needs: [changes, core-on-index, linux-deps-fakeweb, walk]
|
||||
needs: [core-on-index, walk]
|
||||
if: always()
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- name: refuse unless every needed job succeeded
|
||||
env:
|
||||
NEEDS: ${{ toJSON(needs) }}
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
WORKFLOW: fakeweb
|
||||
CHANGES_RUN: ${{ needs.changes.outputs.run }}
|
||||
- name: red unless every leg is green
|
||||
run: |
|
||||
git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main
|
||||
if git cat-file -e origin/main:scripts/ci_gate.py 2>/dev/null; then
|
||||
git show origin/main:scripts/ci_gate.py > "$RUNNER_TEMP/ci_gate.py"
|
||||
else
|
||||
echo "ci_gate.py is not on origin/main yet: falling back to the copy of this branch"
|
||||
cp scripts/ci_gate.py "$RUNNER_TEMP/ci_gate.py"
|
||||
echo "core-on-index: ${{ needs.core-on-index.result }}"
|
||||
echo "walk (p2 and p4, linux and windows): ${{ needs.walk.result }}"
|
||||
if [ "${{ needs.walk.result }}" != "success" ]; then
|
||||
echo "RED: the four legs did not all pass (a leg that did not run measured nothing)"
|
||||
exit 1
|
||||
fi
|
||||
python3 "$RUNNER_TEMP/ci_gate.py"
|
||||
echo "green: ours equals stock on the fake web, on both systems"
|
||||
@@ -39,15 +39,16 @@ env:
|
||||
jobs:
|
||||
# `pip install .` below resolves `invisible-core==N.M.0` from the package
|
||||
# index, and the core is published BEFORE this package. This gate answers
|
||||
# whether it is there yet; during that window this job FAILS (rule ci-13: a
|
||||
# core that is not on the index is red, never a skip) and the smoke matrix,
|
||||
# which needs it, does not run; once the core is up it runs unchanged. See .github/workflows/core-on-index.yml.
|
||||
# whether it is there yet; during that window the smoke matrix is SKIPPED
|
||||
# with the reason in the run summary rather than faked green, and once the
|
||||
# core is up it runs unchanged. See .github/workflows/core-on-index.yml.
|
||||
core-on-index:
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
|
||||
smoke:
|
||||
name: launch (${{ matrix.os }}, py${{ matrix.python }})
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
+69
-48
@@ -5,9 +5,6 @@ on:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
# The merge queue run: a pull request is judged by this fast set; e2e.yml and fakeweb.yml run in the queue run and that run decides.
|
||||
merge_group:
|
||||
types: [checks_requested]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -20,10 +17,9 @@ permissions:
|
||||
# each other; only an older run of THIS workflow on the same branch is replaced.
|
||||
# A newer push to a pull request cancels the run it supersedes. Never on main:
|
||||
# outside a pull request the group is unique to the run (`github.run_id`), so
|
||||
# every commit of main keeps its own finished run (see e2e.yml for why). A merge queue run is keyed by its own ref (one per queue entry) and is never
|
||||
# cancelled: `cancel-in-progress` is true on a pull request only.
|
||||
# every commit of main keeps its own finished run (see e2e.yml for why).
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'merge_group' && github.ref || github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
@@ -156,11 +152,11 @@ jobs:
|
||||
# package index. The core is published BEFORE this package, so between the
|
||||
# first push of this repo and that upload there is a window in which no
|
||||
# install here can succeed. This gate answers "is it on the index?" and the
|
||||
# unit job depends on the answer: during the window this job FAILS with the
|
||||
# reason (rule ci-13: a core that is not on the index is red, never a skip),
|
||||
# and `gate` is red with it; once the core is published it runs exactly as
|
||||
# before. Full reasoning, including why `|| true`, `--no-deps` and a git
|
||||
# fallback were all rejected, is in .github/workflows/core-on-index.yml.
|
||||
# unit job depends on the answer: during the window that job is SKIPPED (grey
|
||||
# in the checks list, with the reason written into the run summary), never
|
||||
# faked green; once the core is published it runs exactly as before. Full
|
||||
# reasoning, including why `|| true`, `--no-deps` and a git fallback were all
|
||||
# rejected, is in .github/workflows/core-on-index.yml.
|
||||
core-on-index:
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
|
||||
@@ -173,6 +169,7 @@ jobs:
|
||||
unit:
|
||||
name: pytest (${{ matrix.os }}, py${{ matrix.python }})
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -350,12 +347,13 @@ jobs:
|
||||
# exactly how it got here. This job depends on the whole matrix and its
|
||||
# name never changes.
|
||||
#
|
||||
# SKIPPED IS RED (rule ci-13: nothing counts as passed that did not pass).
|
||||
# A job that was skipped ran nothing. `unit` used to be skipped when
|
||||
# `core-on-index` said the pin was not on the index yet, and this gate
|
||||
# treated that skip as a pass: a pull request merged with no test run. Now
|
||||
# `core-on-index` fails in that case, and the gate refuses every needed job
|
||||
# whose result is not `success`.
|
||||
# SKIPPED IS NOT FAILED, and that is the part specific to this repo. `unit`
|
||||
# is skipped on purpose when `core-on-index` says the pin is not yet on the
|
||||
# index: during that window no install can succeed, and the workflow chose
|
||||
# to SKIP instead of faking green. A gate that required `success` would
|
||||
# turn that choice into a red and push toward dropping the protection on
|
||||
# release day of all days. So it refuses on `failure` and `cancelled`,
|
||||
# never on `skipped`.
|
||||
# The guides are the surface a stranger copies first, and until 2026-09-08
|
||||
# nothing read them: one page published `page.accessibility.snapshot()`, which
|
||||
# this fork does not have, so anybody who ran that block got an AttributeError.
|
||||
@@ -363,11 +361,13 @@ jobs:
|
||||
# by a reader who then leaves.
|
||||
#
|
||||
# It needs the package importable, because it asks the REAL classes what they
|
||||
# have rather than carrying a list that would drift from them - so it needs
|
||||
# core-on-index exactly as `unit` does.
|
||||
# have rather than carrying a list that would drift from them - so it takes
|
||||
# core-on-index's answer exactly as `unit` does, and is SKIPPED during the
|
||||
# window rather than faked green.
|
||||
docs-api:
|
||||
name: the guides name an API that exists
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
|
||||
@@ -396,37 +396,59 @@ jobs:
|
||||
# the decorative protection this project has already met once, on the branch
|
||||
# rules that required job names no job produced any more.
|
||||
#
|
||||
# Every needed job must end in `success`; `skipped`, `cancelled` and
|
||||
# `failure` are red, one FAIL line each (scripts/ci_gate.py). The single job
|
||||
# that is conditional by design is `version`: it runs on pull requests and in
|
||||
# the merge queue run, so a push to main skips it on purpose, and the script
|
||||
# expects `skipped` there and `success` on a pull request and in the queue.
|
||||
# Nothing else is forgiven. The
|
||||
# script is read from origin/main, not from the branch being judged. Its table and the `needs:` below are held together by
|
||||
# tests/test_the_gate_is_red_when_a_needed_job_is_skipped.py.
|
||||
# `skipped` is not a failure and must not be treated as one: `version` runs on
|
||||
# pull requests only and is skipped on every push to main, and `unit` and
|
||||
# `docs-api` are skipped during the window when the pinned core is not on the
|
||||
# index yet. The case arms name failure and cancelled, so a skip passes on
|
||||
# purpose. That is also why each arm carries its own sentence: a gate that
|
||||
# exits 1 without saying which of five inputs went red is a gate somebody has
|
||||
# to open five tabs to read.
|
||||
gate:
|
||||
needs: [core-on-index, unit, docs-api, english, claims, version, way-in, install-job, noreply-identity]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
|
||||
- name: refuse unless every needed job succeeded
|
||||
env:
|
||||
NEEDS: ${{ toJSON(needs) }}
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
WORKFLOW: tests
|
||||
# The judge is read from main, never from the branch it judges. Only
|
||||
# while the file is not on main yet (the change that adds it) the
|
||||
# copy of this branch is used, and the log says so.
|
||||
- name: refuse unless nothing failed
|
||||
run: |
|
||||
git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main
|
||||
if git cat-file -e origin/main:scripts/ci_gate.py 2>/dev/null; then
|
||||
git show origin/main:scripts/ci_gate.py > "$RUNNER_TEMP/ci_gate.py"
|
||||
else
|
||||
echo "ci_gate.py is not on origin/main yet: falling back to the copy of this branch"
|
||||
cp scripts/ci_gate.py "$RUNNER_TEMP/ci_gate.py"
|
||||
echo "core-on-index: ${{ needs.core-on-index.result }}"
|
||||
echo "unit: ${{ needs.unit.result }}"
|
||||
echo "docs-api: ${{ needs.docs-api.result }}"
|
||||
echo "english: ${{ needs.english.result }}"
|
||||
echo "claims: ${{ needs.claims.result }}"
|
||||
echo "way-in: ${{ needs.way-in.result }}"
|
||||
echo "version: ${{ needs.version.result }}"
|
||||
echo "install-job: ${{ needs.install-job.result }}"
|
||||
echo "noreply-identity: ${{ needs.noreply-identity.result }}"
|
||||
case "${{ needs.unit.result }}" in
|
||||
failure|cancelled) echo "the suite did not pass"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.core-on-index.result }}" in
|
||||
failure|cancelled) echo "the index check did not run"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.docs-api.result }}" in
|
||||
failure|cancelled) echo "the guides name something that does not exist"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.english.result }}" in
|
||||
failure|cancelled) echo "the repository is not English"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.claims.result }}" in
|
||||
failure|cancelled) echo "the README promises what no measurement supports"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.way-in.result }}" in
|
||||
failure|cancelled) echo "an install instruction is not uv"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.version.result }}" in
|
||||
failure|cancelled) echo "the version this change proposes is already taken"; exit 1 ;;
|
||||
esac
|
||||
case "${{ needs.install-job.result }}" in
|
||||
failure|cancelled) echo "the user-install job would not run on a release, or leaks"; exit 1 ;;
|
||||
esac
|
||||
# Unlike the checks above this one must be `success`: it runs on every
|
||||
# event this workflow has, so a skip would mean the check never ran.
|
||||
if [ "${{ needs.noreply-identity.result }}" != "success" ]; then
|
||||
echo "a commit or tag of this change has an email that is not a GitHub noreply address"; exit 1
|
||||
fi
|
||||
python3 "$RUNNER_TEMP/ci_gate.py"
|
||||
echo "ok"
|
||||
|
||||
# Measured 2026-09-04: 0.10.0 was on the index while main sat on 0.10.0 with
|
||||
# FIFTEEN commits of different content on top of the tag - 39 files, 841
|
||||
@@ -436,14 +458,13 @@ jobs:
|
||||
# indistinguishable from somebody forgetting to bump. The fix could not have
|
||||
# reached anybody, and nothing would have said so.
|
||||
#
|
||||
# Where a change is proposed (a pull request, and the merge queue run, which
|
||||
# compares the version the entry proposes with the published one): on main
|
||||
# straight after a release the version IS the published one until somebody
|
||||
# bumps, and a gate that is red at rest is one people learn to skip. Bumping publishes nothing - publishing happens on a
|
||||
# Pull requests only: on main straight after a release the version IS the
|
||||
# published one until somebody bumps, and a gate that is red at rest is one
|
||||
# people learn to skip. Bumping publishes nothing - publishing happens on a
|
||||
# tag push - so main on an unreleased version is the normal state between
|
||||
# releases and the rule costs one line.
|
||||
version:
|
||||
if: github.event_name == 'pull_request' || github.event_name == 'merge_group'
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 (v4.4.0)
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
{"id": "wrapper.e2e.fakeweb", "giro": "G2", "os": ["linux", "windows"], "min_tests": 7, "exact": true, "tests": ["tests/test_fakeweb_p2_e2e.py", "tests/test_fakeweb_p4_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The fake web, offline: our browser on the hard pages (profile P2: a reused routed page reaches networkidle every time, also under a load of three other browsers; the other site is another process) and on the 17-step journey of a person (profile P4: every step as stock, and every page left only once its noise is done), each judged against what stock Firefox does, as tests/fakeweb/pages.json declares it. 7 = 3 + 4 (the last two: a `load` that takes 20 s is a step that succeeds, and a `load` that never comes ends in an error that names the wait and the page). Stock itself is held to that declaration, and compared with ours step by step, by scripts/run_fakeweb.py in .github/workflows/fakeweb.yml. Needs the candidate binary (STEALTHFOX_E2E_BINARY).", "stock_firefox": true, "extra_steps": ["fakeweb_profiles"]},
|
||||
{"id": "wrapper.e2e.fontconfig", "giro": "G2", "os": ["linux"], "min_tests": 2, "exact": true, "tests": ["tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "Fontconfig exists only on Linux: the parent of the engine shows <GRE>/fonts to it (FcConfigAppFontAddDir) to rebuild a font from a path and a face index. On Windows DirectWrite opens the file from its path, with no folder to scan and no cache to read, so this test has no Windows counterpart.", "note": "2 = (1) the stand-in that runs the engine under strace stays in the engine's place, as the core launches it (the leader of a process group of its own): a fake engine with a child, no browser; the process the launcher holds lives as long as the fake engine, and the group killed holds strace and the child (the stand-in that exec'd setsid forked and exited 0 at once: candidate 44161687675); (2) the warm launch of the parent reads the bundle from fontconfig's cache and does not scan it again (from firefox-66, engine_at_least). Two launches under strace with the same XDG_CACHE_HOME of the test, the first cold and the second warm: the cold parent opens every font file of <GRE>/fonts (the folder as the disk lists it) before any page and fontconfig writes its cache; the warm parent does not open every one of them, and it opens a *.cache-* file of fontconfig (a few files are opened to be used, so the verdict asks about the whole folder, as a scan does). Scan and drawing are told apart by position: only what the parent opens before the first page counts (the opens that draw are written as after_startup). Evidence in RUNNER_TEMP/invpw-evidence/fontconfig-cache: the interval and the number of opens of the bundle, the names of the files of the bundle each launch opened before the first page, the size of the cache file, the VmRSS of the parent after about:blank and after a page with every family, and a third launch with gfx.bundled-fonts.activate=0 (the behaviour before), which is evidence only. Needs strace on the runner: without it both are red, not skipped. No threshold."},
|
||||
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 30, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference, and the box cut out of a screenshot (its pixels, a box outside the picture refused, written as a PNG and read back, two boxes told apart by a pixel that is named, the pixels that are not grey)."},
|
||||
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 3879, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_docs_only_change_runs_nothing_heavy_in_the_queue.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_file_chooser_is_never_dropped_in_silence.py", "tests/test_a_frame_tap_needs_a_context_with_touch.py", "tests/test_a_handle_action_walks_like_a_selector_action.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_screenshot_sends_its_scale_to_the_engine.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_streamed_upload_is_staged_in_the_session.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_ab_host.py", "tests/test_ab_host_aa_stable.py", "tests/test_ab_network.py", "tests/test_ab_oracle.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_element_handle_serves_every_method_of_the_client.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_host_gate_ab.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_linux_legs_read_no_mirror.py", "tests/test_ci_poison_host.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_action_is_pinned_by_commit_sha.py", "tests/test_every_argument_reaches_the_page_as_playwright_sends_it.py", "tests/test_every_held_request_of_the_journey_starts_after_the_load.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_every_wire_method_is_served_or_refused.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fakeweb_stock_unsettled.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_glean_ready.py", "tests/test_goto_follows_the_base_url.py", "Line truncated
|
||||
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 3880, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_docs_only_change_runs_nothing_heavy_in_the_queue.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_file_chooser_is_never_dropped_in_silence.py", "tests/test_a_frame_tap_needs_a_context_with_touch.py", "tests/test_a_handle_action_walks_like_a_selector_action.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_screenshot_sends_its_scale_to_the_engine.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_streamed_upload_is_staged_in_the_session.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_ab_host.py", "tests/test_ab_host_aa_stable.py", "tests/test_ab_network.py", "tests/test_ab_oracle.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_element_handle_serves_every_method_of_the_client.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_host_gate_ab.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_linux_legs_read_no_mirror.py", "tests/test_ci_poison_host.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_action_is_pinned_by_commit_sha.py", "tests/test_every_argument_reaches_the_page_as_playwright_sends_it.py", "tests/test_every_held_request_of_the_journey_starts_after_the_load.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_every_wire_method_is_served_or_refused.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fakeweb_stock_unsettled.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_glean_ready.py", "tests/test_goto_follows_the_base_url.pyLine truncated
|
||||
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 3851, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_file_chooser_is_never_dropped_in_silence.py", "tests/test_a_frame_tap_needs_a_context_with_touch.py", "tests/test_a_handle_action_walks_like_a_selector_action.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_screenshot_sends_its_scale_to_the_engine.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_streamed_upload_is_staged_in_the_session.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_test_that_is_not_e2e_never_leaves_the_machine.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_ab_host.py", "tests/test_ab_host_aa_stable.py", "tests/test_ab_network.py", "tests/test_ab_network_turn_credential.py", "tests/test_ab_network_turn_deallocation.py", "tests/test_ab_network_webrtc_evidence.py", "tests/test_ab_oracle.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_element_handle_serves_every_method_of_the_client.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_host_gate_ab.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_linux_legs_read_no_mirror.py", "tests/test_ci_poison_host.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_action_is_pinned_by_commit_sha.py", "tests/test_every_argument_reaches_the_page_as_playwright_sends_it.py", "tests/test_every_held_request_of_the_journey_starts_after_the_load.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_every_wire_method_is_served_or_refused.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fakeweb_stock_unsettled.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tLine truncated
|
||||
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 3855, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_file_chooser_is_never_dropped_in_silence.py", "tests/test_a_frame_tap_needs_a_context_with_touch.py", "tests/test_a_handle_action_walks_like_a_selector_action.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_screenshot_sends_its_scale_to_the_engine.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_streamed_upload_is_staged_in_the_session.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_test_that_is_not_e2e_never_leaves_the_machine.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_ab_host.py", "tests/test_ab_host_aa_stable.py", "tests/test_ab_network.py", "tests/test_ab_network_turn_credential.py", "tests/test_ab_network_turn_deallocation.py", "tests/test_ab_network_webrtc_evidence.py", "tests/test_ab_oracle.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_element_handle_serves_every_method_of_the_client.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_host_gate_ab.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_linux_legs_read_no_mirror.py", "tests/test_ci_poison_host.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_action_is_pinned_by_commit_sha.py", "tests/test_every_argument_reaches_the_page_as_playwright_sends_it.py", "tests/test_every_held_request_of_the_journey_starts_after_the_load.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_every_wire_method_is_served_or_refused.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fakeweb_stock_unsettled.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py"Line truncated
|
||||
{"id": "wrapper.e2e.securitystate", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_security_state_engine_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The security state the core declares, against the engine: the engine launched directly in its generate mode makes what it is given (the contract's result, security_state/ with the bytes of the full filter and of the delta, the core's own validation of it); a normal launch declares no pref of the mode and re-imports nothing; a certificate that Mozilla's CRLite test data say is revoked in a delta is refused at the first navigation (SEC_ERROR_REVOKED_CERTIFICATE) while a valid one loads, and the revoked one loads when the ready directory has no data; a ready directory with no or an empty security_state/ starts. Certificates made on the run (a fresh root trusted in cert9.db by the engine's own xpcshell, Mozilla's default test key as the key of CN=int), servers on loopback, no network. Red on firefox-67 (no generate mode).", "core_dumps": "invpw-cores"},
|
||||
{"id": "wrapper.e2e.suite.linux.1", "giro": "G2", "os": ["linux"], "min_tests": 415, "exact": true, "tests": ["tests/test_a_closed_browser_leaves_the_others_alone_e2e.py", "tests/test_a_context_that_ends_leaves_no_process_e2e.py", "tests/test_a_cors_preflight_is_not_a_request_of_the_page_e2e.py", "tests/test_a_declared_webgl_extension_survives_its_use_e2e.py", "tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "tests/test_a_held_ice_port_blinds_the_loopback_checks_e2e.py", "tests/test_a_launch_without_a_session_gets_one_e2e.py", "tests/test_a_left_documents_body_is_evicted_e2e.py", "tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py", "tests/test_a_screenshot_honours_its_scale_e2e.py", "tests/test_a_served_browser_answers_a_plain_client_e2e.py", "tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "tests/test_accept_language_on_the_wire_e2e.py", "tests/test_browser_output_is_drained.py", "tests/test_click_rhythm.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_control_a_selects_all_in_a_field_e2e.py", "tests/test_cross_origin_iframe.py", "tests/test_declared_host_network_e2e.py", "tests/test_detectors_e2e.py", "tests/test_e2e.py", "tests/test_element_handle_actions.py", "tests/test_element_screenshot_e2e.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_file_chooser.py", "tests/test_fingerprint_surface.py", "tests/test_fission_frames_history_and_processes_e2e.py", "tests/test_fission_frames_workers_storage_and_special_frames_e2e.py", "tests/test_frames_outlive_the_back_forward_cache_e2e.py", "tests/test_goto_networkidle_after_spa_e2e.py", "tests/test_goto_script_redirect_e2e.py", "tests/test_hidden_display_linux.py", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context", "tests/test_ignore_https_errors_e2e.py", "tests/test_injected_node_surface.py", "tests/test_juggler_connection.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_navigation_across_processes_e2e.py", "tests/test_navigation_response.py", "tests/test_networkidle_reaches_the_client_e2e.py", "tests/test_oop_frame_element.py", "tests/test_oop_frame_geometry.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pointer_position.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_realness_behind_a_declared_exit_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_route_header_order_e2e.py", "tests/test_same_document_goto_e2e.py", "tests/test_screencast.py", "tests/test_screencast_stop_e2e.py", "tests/test_screenshot_looks_where_you_are.py", "tests/test_security_state_engine_e2e.py", "tests/test_service_worker.py", "tests/test_service_worker_controller_e2e.py", "tests/test_set_offline_e2e.py", "tests/test_shadow_trusted_input.py", "tests/test_strict_and_force.py", "tests/test_the_callers_code_is_not_counted_e2e.py", "tests/test_the_device_enumeration_takes_the_declared_time_e2e.py", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_a_launch_scans_no_process_of_the_machine", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_after_close_no_process_of_the_session_is_left", "tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_trial_does_not_act.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_ua_widget_not_selectable.py", "tests/test_voices_e2e.py", "tests/test_wait_for_function.py", "tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py", "tests/test_webgl_noise_active.py", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_not_blocked_behind_tcp_only_socks", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_Line truncated
|
||||
{"id": "wrapper.e2e.suite.linux.2", "giro": "G2", "os": ["linux"], "min_tests": 414, "exact": true, "tests": ["tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py", "tests/test_a_context_init_script_runs_once_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_goto_to_a_response_with_no_document_ends_e2e.py", "tests/test_a_keepalive_request_reaches_the_client_e2e.py", "tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py", "tests/test_a_page_cannot_probe_the_juggler_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py", "tests/test_a_request_says_what_it_is_e2e.py", "tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_isolated_page_and_the_next_e2e.py", "tests/test_bypass_csp_e2e.py", "tests/test_caller_world_handles_e2e.py", "tests/test_canvas_reads_as_drawn.py", "tests/test_canvas_render_stealth.py", "tests/test_context_locale_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_download_is_intercepted_e2e.py", "tests/test_drag_motion.py", "tests/test_expose_binding_e2e.py", "tests/test_fakeweb_p4_e2e.py", "tests/test_fingerprint_consistency.py", "tests/test_fission_frames_dialogs_downloads_popups_e2e.py", "tests/test_fission_frames_route_and_bindings_e2e.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fission_iframe_crash_e2e.py", "tests/test_fission_strategy1_bench.py", "tests/test_goto_to_the_same_url_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_input_is_born_before_the_page_sees_it_e2e.py", "tests/test_juggler_actions.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py::test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None", "tests/test_juggler_injected.py::test_actionability_DISTINGUISHES_instead_of_always_saying_yes", "tests/test_juggler_injected.py::test_reads_that_make_no_sense_are_REJECTED", "tests/test_juggler_injected.py::test_states_DISCRIMINATE_instead_of_always_saying_true", "tests/test_juggler_injected.py::test_the_DOM_READING_group", "tests/test_juggler_injected.py::test_the_selector_engines_respond", "tests/test_juggler_injected.py::test_the_text_reads", "tests/test_juggler_lifecycle_e2e.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_long_session_e2e.py", "tests/test_mouse.py", "tests/test_mouse_events_keep_their_values_e2e.py", "tests/test_new_page_defaults.py", "tests/test_popup_destinations_e2e.py", "tests/test_popup_pages.py", "tests/test_proxy_http_auth_e2e.py", "tests/test_proxy_reaches_the_browser.py", "tests/test_proxy_socks_auth_e2e.py", "tests/test_requestless_navigation.py", "tests/test_route_abort_code.py", "tests/test_route_e2e.py", "tests/test_route_post_data_e2e.py", "tests/test_route_sends_a_navigation_elsewhere_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_same_document_navigation.py", "tests/test_screenshot_of_text_returns_linux_e2e.py", "tests/test_scroll_into_view.py", "tests/test_scroll_only_if_needed_e2e.py", "tests/test_service_workers_blocked.py", "tests/test_set_input_files_payloads.py", "tests/test_software_compositing_is_declared_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_the_callers_code_runs_once_e2e.py", "tests/test_the_close_returns_when_the_browser_has_exited_e2e.py", "tests/test_the_favicon_stays_out_of_sight_e2e.py", "tests/test_the_font_list_is_the_bundle_e2e.py", "tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py", "tests/test_the_scheme_is_the_personas_e2e.py", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_typing_a_character_without_a_key_e2e.py", "tests/test_wait_for_timeout.py", "tests/test_web_fonts_of_closed_contexts_e2e.py"], "marker": "e2e", "needs_root": false, "windows_twin": "wrapper.e2e.suite.windows.2", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 2 rows of linux are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 564 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapLine truncated
|
||||
|
||||
+502
-34
@@ -49,6 +49,11 @@ under ``exits``, outside the leaves that are compared, and a parent that did not
|
||||
the side, the seed, the launch and the code. What a launch that died left is kept beside the transcript (``transcript-68.json`` -> ``transcript-68.crash/``): the core through gdb with
|
||||
the build ids, the ``.extra`` and the minidump names, ``said.txt`` for what the collectors did not find. This oracle runs no strace (a trace would change the outcome it observes).
|
||||
|
||||
THE WEBRTC EVIDENCE AND THE HUNT. The WebRTC walk keeps, under ``transcript["evidence"]["seeds"][<seed>]["webrtc"]`` (never compared: the comparison reads ``seeds`` and nothing else), every datagram the gateway
|
||||
routed in it (when, target, message, STUN transaction id), the moments of its stages and of the page's call, and the page's own ``performance.now()`` at each step of the gather. With
|
||||
``AB_NETWORK_HUNT=webrtc:<seed>:<n>`` the command ``ab`` runs ONLY that walk of that seed, ``n`` times for each engine of the A/A, and writes ``<out>/hunt/<engine>-<i>.json`` and ``<out>/hunt/summary.json``;
|
||||
it decides nothing and exits 0 (e2e-hunt.yml: the input ``ab_network_webrtc_seed``).
|
||||
|
||||
Exit codes: 0 green, 1 red (a finding), 2 broken control (the A/A is red) or a run that could not run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -79,6 +84,13 @@ import ci_crash_evidence as crash # noqa: E402 (how each launch's parent ended
|
||||
FORMAT = "ab-network/1"
|
||||
DIFF_FORMAT = "ab-network-diff/1"
|
||||
EVIDENCE_FORMAT = "ab-network-evidence/1"
|
||||
HUNT_FORMAT = "ab-network-hunt/1"
|
||||
HUNT_SUMMARY_FORMAT = "ab-network-hunt-summary/1"
|
||||
#: The environment variable that makes ``ab`` repeat one walk of one seed and nothing else (``cmd_hunt``): ``webrtc:<seed>:<n>``.
|
||||
HUNT_ENV = "AB_NETWORK_HUNT"
|
||||
#: The engine's own log in a hunt (the launch's environment, in hunt mode only): nICEr's reasons for accepting or rejecting an answer or ending a transaction, and the signaling.
|
||||
#: ``sync`` makes each line reach the file as it is written, so a process that ends (or is killed) loses none.
|
||||
HUNT_MOZ_LOG = "sync,timestamp,nicer:5,signaling:5"
|
||||
VOLATILE_FORMAT = "ab-network-volatile/1"
|
||||
VOLATILE_FILE = ROOT / "ci" / "ab-network-volatile.json"
|
||||
SEEDS_FILE = ROOT / "ci" / "persona-seeds.json"
|
||||
@@ -86,6 +98,11 @@ SEEDS_FILE = ROOT / "ci" / "persona-seeds.json"
|
||||
FALLBACK_SEEDS = (11, 12, 13)
|
||||
ENGINE_TAG = "firefox-68"
|
||||
CANDIDATE = "candidate"
|
||||
#: The most times the engine sends one STUN request (a transmit and its retransmissions) before it gives the transaction up: the pref
|
||||
#: ``media.peerconnection.ice.stun_client_maximum_transmits`` (modules/libpref/init/all.js), 7. The first RTO is 100 ms and doubles, so how
|
||||
#: MANY transactions a walk has is the engine's and is compared, and how many datagrams each took is the network's timing and is not: a
|
||||
#: transaction over this number is a problem of the run (``udp_summary``'s ``over_limit``, ``_udp_overruns``), never a compared leaf.
|
||||
STUN_MAX_TRANSMITS = 7
|
||||
#: What a leaf that one side does not have reads as.
|
||||
MISSING = "<missing>"
|
||||
#: A value longer than this in diff.json is replaced by its length and its sha256.
|
||||
@@ -267,6 +284,65 @@ def _udp_attribution(la: Dict[str, Any], lb: Dict[str, Any]) -> Tuple[set, List[
|
||||
return paths, differences, unattributed
|
||||
|
||||
|
||||
_UDP_OVER_LIMIT = re.compile(r"^(?P<where>.*/udp)/over_limit/(?P<target>[^/]+)/\d+$")
|
||||
|
||||
|
||||
def _udp_overruns(la: Dict[str, Any], lb: Dict[str, Any], label_a: str, label_b: str) -> Tuple[set, List[str]]:
|
||||
"""The STUN transactions that were sent more times than the engine's maximum (``udp_summary``'s ``over_limit``: per destination, the number of transmits of each such
|
||||
transaction). They are not compared leaf by leaf: how many datagrams a transaction took is the network's timing, but more than the engine's own maximum is not
|
||||
timing, it is a client that does not stop. Returns the paths that take part and one problem line for each."""
|
||||
paths: set = set()
|
||||
problems: List[str] = []
|
||||
for label, leaves in ((label_a, la), (label_b, lb)):
|
||||
for path, value in sorted(leaves.items()):
|
||||
m = _UDP_OVER_LIMIT.match(path)
|
||||
if m:
|
||||
paths.add(path)
|
||||
problems.append("%s: a STUN transaction to %s was sent %s times, more than the engine's maximum of %d transmits (%s)"
|
||||
% (label, m.group("target"), value, STUN_MAX_TRANSMITS, m.group("where")))
|
||||
return paths, problems
|
||||
|
||||
|
||||
def turn_path_problems(transcript: Dict[str, Any], label: str) -> List[str]:
|
||||
"""Whether the TURN path of the lab WORKED in each WebRTC walk of a transcript: a relay candidate was made, no error names the lab's TURN server (701 is what a browser reports when
|
||||
every answer it got was thrown away as invalid, as with a wrong credential), and the server refused no request (``webrtc/turn/refused``, written by ``walk_webrtc``). An A/A that
|
||||
compared two runs in which the TURN path failed the same way would pass; this is the line that says it did not work. A transcript with no WebRTC walk says nothing."""
|
||||
out: List[str] = []
|
||||
for seed, body in sorted((transcript.get("seeds") or {}).items()):
|
||||
walk = body.get("webrtc")
|
||||
if not isinstance(walk, dict):
|
||||
continue
|
||||
errors = [e for e in walk.get("errors") or [] if TURN_TARGET in str(e)]
|
||||
refused = (walk.get("turn") or {}).get("refused") or 0
|
||||
if "relay" in (walk.get("candidate_types") or []) and not errors and not refused:
|
||||
continue
|
||||
seen = (errors + ["the lab TURN refused %d request(s)" % refused] * bool(refused)) or ["no error"]
|
||||
out.append("seeds/%s/webrtc: %s made no relay candidate through the lab TURN (%s). Fix: the probe's credential must be the lab TURN's (tests/_turn_chain.py PASSWORD) "
|
||||
"and the lab's answers must reach the browser. Rule: the A/A proves the TURN path it compares" % (seed, label, "; ".join(seen)))
|
||||
return out
|
||||
|
||||
|
||||
def turn_deallocation_problems(transcript: Dict[str, Any], label: str) -> List[str]:
|
||||
"""What the lab's TURN server heard of deallocations (``webrtc/turn/deallocation``, written by ``walk_webrtc`` with :func:`deallocation_facts`) that a walk must not have: an allocation ended
|
||||
by more than one deallocation, a deallocation from an address that has no allocation. One deallocation, or none, is the engine's best effort at teardown and is evidence, not a leaf."""
|
||||
out: List[str] = []
|
||||
for seed, body in sorted((transcript.get("seeds") or {}).items()):
|
||||
walk = body.get("webrtc")
|
||||
facts = ((walk or {}).get("turn") or {}).get("deallocation") if isinstance(walk, dict) else None
|
||||
if not isinstance(facts, dict):
|
||||
continue
|
||||
for key, what, fix in (("repeated", "%d allocation(s) of the lab TURN were ended by more than one deallocation (a Refresh with LIFETIME 0)",
|
||||
"find what sends the teardown twice; the engine sends it once"),
|
||||
("unallocated", "the lab TURN heard %d deallocation(s) (a Refresh with LIFETIME 0) from an address that has no allocation",
|
||||
"find what deallocates an allocation it never made; the lab's record is TurnServer.deallocations in tests/_turn_chain.py"),
|
||||
("early", "%d deallocation(s) (a Refresh with LIFETIME 0) reached the lab TURN before the page began closing its connection",
|
||||
"find what ends the allocation while the page still holds it; the engine sends it only while it shuts the client down, after the close")):
|
||||
if facts.get(key):
|
||||
out.append("seeds/%s/webrtc: %s: %s. Fix: %s. Rule: the TURN deallocation is one best-effort send at teardown (nICEr nr_turn_client_deallocate)"
|
||||
% (seed, label, what % facts[key], fix))
|
||||
return out
|
||||
|
||||
|
||||
def exit_lines(transcript: Dict[str, Any], label: str, side: str) -> List[str]:
|
||||
"""The red lines of the launches of one side that did not end with 0 (``exits``, which ``run`` writes: scripts/ci_crash_evidence.py). A transcript that has no ``exits``
|
||||
was not made by ``run`` and says nothing about it; one that has it and no launch in it is a run whose probe saw no browser, which is red."""
|
||||
@@ -286,7 +362,11 @@ def compare_transcripts(a: Dict[str, Any], b: Dict[str, Any], volatile: List[Dic
|
||||
run the same seeds, when fewer than ``floor`` leaves were compared, or when an entry of the volatile list matches no leaf of either transcript (``stale``)."""
|
||||
la, lb = flatten(a.get("seeds") or {}), flatten(b.get("seeds") or {})
|
||||
attribution, attribution_differences, unattributed = _udp_attribution(la, lb)
|
||||
paths = sorted((set(la) | set(lb)) - attribution)
|
||||
overrun_paths, overruns = _udp_overruns(la, lb, label_a, label_b)
|
||||
turn_problems = (turn_path_problems(a, label_a) + turn_path_problems(b, label_b) +
|
||||
turn_deallocation_problems(a, label_a) + turn_deallocation_problems(b, label_b))
|
||||
refused_paths = {p for p in set(la) | set(lb) if re.match(r"^seeds/[^/]+/webrtc/turn/(refused|deallocation/(repeated|unallocated|early))$", p)}
|
||||
paths = sorted((set(la) | set(lb)) - attribution - overrun_paths - refused_paths)
|
||||
problems: List[str] = []
|
||||
if set(a.get("seeds") or {}) != set(b.get("seeds") or {}):
|
||||
problems.append("the sides ran different seeds: %s and %s" % (sorted(a.get("seeds") or {}), sorted(b.get("seeds") or {})))
|
||||
@@ -324,6 +404,8 @@ def compare_transcripts(a: Dict[str, Any], b: Dict[str, Any], volatile: List[Dic
|
||||
problems += ["a direct connection: " + d for d in direct]
|
||||
problems += exit_lines(a, label_a, "A") + exit_lines(b, label_b, "B")
|
||||
problems += invariants
|
||||
problems += overruns
|
||||
problems += turn_problems
|
||||
problems += ["the volatile entry %r matches no leaf of either transcript: it is stale, drop it" % p for p in stale]
|
||||
problems += ["%s: %s %s | %s %s" % (d["path"], label_a, json.dumps(d["a"], sort_keys=True)[:160], label_b, json.dumps(d["b"], sort_keys=True)[:160])
|
||||
for d in differences]
|
||||
@@ -468,17 +550,31 @@ def dns_summary(queries: List[Tuple[str, int, str]], openers: Optional[List[Opti
|
||||
|
||||
|
||||
def udp_summary(events: List[Dict[str, Any]], norm: Normalizer) -> Dict[str, Any]:
|
||||
"""The datagrams the relay carried in one phase: per destination, the kinds of message and how many."""
|
||||
"""The datagrams the relay carried in one phase: per destination, the kinds of message and how many.
|
||||
|
||||
``counts`` is the number of STUN TRANSACTIONS (distinct transaction ids) per destination, plus one for each datagram that is not STUN: a retransmission carries the
|
||||
transaction id of the request it repeats, and how many times a request is repeated is the timing of the network (the first RTO is 100 ms and doubles; a late answer
|
||||
on a loaded host adds one), so it is not what the engine decides. ``over_limit`` (only when there is one) lists, per destination, the transmits of each transaction
|
||||
that has more than ``STUN_MAX_TRANSMITS``: ``compare_transcripts`` reports it as a problem and never compares it."""
|
||||
kinds: Dict[str, set] = collections.defaultdict(set)
|
||||
counts: collections.Counter = collections.Counter()
|
||||
transmits: Dict[str, collections.Counter] = collections.defaultdict(collections.Counter)
|
||||
plain: collections.Counter = collections.Counter()
|
||||
order: List[str] = []
|
||||
for e in events:
|
||||
target = norm.text(e["target"])
|
||||
if target not in kinds:
|
||||
order.append(target)
|
||||
kinds[target].add(e["message"])
|
||||
counts[target] += 1
|
||||
out: Dict[str, Any] = {"order": order, "messages": {t: sorted(kinds[t]) for t in sorted(kinds)}, "counts": dict(sorted(counts.items()))}
|
||||
if e.get("tid") is None:
|
||||
plain[target] += 1
|
||||
else:
|
||||
transmits[target][e["tid"]] += 1
|
||||
counts = {t: plain[t] + len(transmits[t]) for t in sorted(kinds)}
|
||||
out: Dict[str, Any] = {"order": order, "messages": {t: sorted(kinds[t]) for t in sorted(kinds)}, "counts": counts}
|
||||
over = {t: sorted((n for n in transmits[t].values() if n > STUN_MAX_TRANSMITS), reverse=True) for t in sorted(kinds)}
|
||||
over = {t: v for t, v in over.items() if v}
|
||||
if over:
|
||||
out["over_limit"] = over
|
||||
who = _openers([norm.text(e["target"]) for e in events], [e.get("opener") for e in events])
|
||||
if who:
|
||||
out["openers"] = who
|
||||
@@ -544,6 +640,93 @@ def message_kind(payload: bytes) -> str:
|
||||
return "other"
|
||||
|
||||
|
||||
def stun_tid(payload: bytes) -> Optional[str]:
|
||||
"""The transaction id of a STUN message (bytes 8 to 20 of the datagram) in hex: what ties a retransmission to the request it repeats. None when the datagram is not STUN
|
||||
(the same test as :func:`message_kind`: the magic cookie at bytes 4 to 8). Written in the evidence of the WebRTC walk, never compared."""
|
||||
if len(payload) >= 20 and payload[4:8] == b"\x21\x12\xa4\x42":
|
||||
return payload[8:20].hex()
|
||||
return None
|
||||
|
||||
|
||||
def stun_attributes(data: bytes) -> Dict[int, bytes]:
|
||||
"""The attributes of a STUN message by type (RFC 8489: type, length, value padded to 4 bytes); what a truncated tail says is left out."""
|
||||
out: Dict[int, bytes] = {}
|
||||
i = 20
|
||||
while i + 4 <= len(data):
|
||||
kind, length = int.from_bytes(data[i:i + 2], "big"), int.from_bytes(data[i + 2:i + 4], "big")
|
||||
if i + 4 + length > len(data):
|
||||
break
|
||||
out[kind] = data[i + 4:i + 4 + length]
|
||||
i += 4 + ((length + 3) & ~3)
|
||||
return out
|
||||
|
||||
|
||||
def xor_address(value: Optional[bytes]) -> Optional[str]:
|
||||
"""An XOR-MAPPED-ADDRESS or XOR-RELAYED-ADDRESS value (IPv4) as ``ip:port``; None for a missing value or another family."""
|
||||
if value is None or len(value) < 8 or value[1] != 1:
|
||||
return None
|
||||
cookie = b"\x21\x12\xa4\x42"
|
||||
port = int.from_bytes(value[2:4], "big") ^ int.from_bytes(cookie[:2], "big")
|
||||
return "%s:%d" % (socket.inet_ntoa(bytes(a ^ b for a, b in zip(value[4:8], cookie))), port)
|
||||
|
||||
|
||||
def turn_request_record(data: bytes, source: Tuple[str, int], t: float) -> Optional[Dict[str, Any]]:
|
||||
"""What the lab's TURN server writes down of a datagram it receives (None when it is not STUN): when, from where, the transaction id, the message type, whether it carried
|
||||
USERNAME and MESSAGE-INTEGRITY, and (``responses``, filled by :func:`turn_response_record`) what the server answered."""
|
||||
if stun_tid(data) is None:
|
||||
return None
|
||||
attrs = stun_attributes(data)
|
||||
return {"t": t, "src": "%s:%d" % (source[0], source[1]), "tid": stun_tid(data), "type": "0x%04x" % int.from_bytes(data[:2], "big"),
|
||||
"username": 0x0006 in attrs, "integrity": 0x0008 in attrs, "responses": []}
|
||||
|
||||
|
||||
def turn_response_record(data: bytes, destination: Tuple[str, int], t: float) -> Optional[Dict[str, Any]]:
|
||||
"""What the lab's TURN server sends: when, the type (0x0113 an Allocate error, 0x0103 its success), the address it is sent to and, of a success, the XOR-RELAYED-ADDRESS and the
|
||||
XOR-MAPPED-ADDRESS it carries (of an error, its code)."""
|
||||
if stun_tid(data) is None:
|
||||
return None
|
||||
attrs = stun_attributes(data)
|
||||
error = attrs.get(0x0009)
|
||||
return {"t": t, "tid": stun_tid(data), "type": "0x%04x" % int.from_bytes(data[:2], "big"), "to": "%s:%d" % (destination[0], destination[1]),
|
||||
"relayed": xor_address(attrs.get(0x0016)), "mapped": xor_address(attrs.get(0x0020)),
|
||||
"error": (error[2] * 100 + error[3]) if error is not None and len(error) >= 4 else None}
|
||||
|
||||
|
||||
class ExchangeSocket:
|
||||
"""The UDP socket of the lab's TURN server with a record of what it receives and sends (``owner.exchanges``): the server's own code runs on it unchanged, and a failure of the record
|
||||
is never a failure of the server. ``owner.clock`` is the moment (the recorder's)."""
|
||||
|
||||
def __init__(self, sock: socket.socket, owner: Any) -> None:
|
||||
self._sock, self._owner = sock, owner
|
||||
|
||||
def recvfrom(self, size: int) -> Tuple[bytes, Any]:
|
||||
data, source = self._sock.recvfrom(size)
|
||||
try:
|
||||
record = turn_request_record(data, source, self._owner.clock())
|
||||
if record is not None:
|
||||
self._owner.exchanges.append(record)
|
||||
except Exception: # noqa: BLE001 - evidence, never the road
|
||||
pass
|
||||
return data, source
|
||||
|
||||
def sendto(self, data: bytes, address: Any) -> int:
|
||||
try:
|
||||
record = turn_response_record(data, address, self._owner.clock())
|
||||
if record is not None:
|
||||
for exchange in reversed(self._owner.exchanges):
|
||||
if exchange.get("tid") == record["tid"]:
|
||||
exchange["responses"].append(record)
|
||||
break
|
||||
else:
|
||||
self._owner.exchanges.append({"t": record["t"], "src": None, "tid": record["tid"], "type": None, "username": None, "integrity": None, "responses": [record]})
|
||||
except Exception: # noqa: BLE001 - evidence, never the road
|
||||
pass
|
||||
return self._sock.sendto(data, address)
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._sock, name)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
# The seeds, the transcript and its files
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
@@ -591,6 +774,12 @@ class Recorder:
|
||||
self._t0 = time.monotonic()
|
||||
self._sources: Dict[str, list] = {}
|
||||
self._marks: List[Tuple[str, Dict[str, int]]] = []
|
||||
#: The moment (``t``, as an event's) at which each stage began: the evidence of the WebRTC walk says where its stages sit among the datagrams.
|
||||
self.phase_t: Dict[str, float] = {}
|
||||
|
||||
def now(self) -> float:
|
||||
"""The recorder's clock, the ``t`` of an event: seconds since the recorder started."""
|
||||
return round(time.monotonic() - self._t0, 3)
|
||||
|
||||
def attach(self, name: str, items: list) -> None:
|
||||
self._sources[name] = items
|
||||
@@ -600,6 +789,7 @@ class Recorder:
|
||||
with self._lock:
|
||||
self._marks.append((name, {k: len(v) for k, v in self._sources.items()}))
|
||||
self.phase = name
|
||||
self.phase_t[name] = self.now()
|
||||
|
||||
def event(self, kind: str, **fields: Any) -> None:
|
||||
with self._lock:
|
||||
@@ -707,7 +897,7 @@ def make_lab_classes() -> Tuple[type, type, type]:
|
||||
|
||||
import _doh_servers as ds
|
||||
from _socks_servers import MEASURE_NUMBER, STUN_NAME, STUN_NUMBER, STUN_PORT, WHOAMI4, WHOAMI6, WEB_NAME
|
||||
from _turn_chain import TURN_IP, TURN_PORT, TurnServer
|
||||
from _turn_chain import TURN_IP, TURN_PORT, TurnServer, is_deallocation
|
||||
|
||||
class LabGateway(ds.DohGateway):
|
||||
"""A coherent SOCKS5 gateway with the DoH road. Past loopback it carries only what the lab names: the CONNECTs to the servers of the lab that stand at the
|
||||
@@ -727,6 +917,17 @@ def make_lab_classes() -> Tuple[type, type, type]:
|
||||
self.opener_lookup: Callable[..., str] = self._look_up_opener
|
||||
super().__init__("lab", doh, udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, relay_host=host, exit_host=host)
|
||||
|
||||
def _deliver(self, relay: socket.socket, to: Any, host: str, port: int, payload: bytes) -> None:
|
||||
"""Every datagram the relay sends BACK to the browser is written down (``udp_back``: the address it claims in the SOCKS UDP header, where it is sent, from which relay
|
||||
socket, the STUN type and transaction id), then sent as it always was."""
|
||||
try:
|
||||
local = relay.getsockname()
|
||||
self.rec.event("udp_back", claimed="%s:%d" % (host, port), to="%s:%d" % (to[0], to[1]), relay="%s:%d" % (local[0], local[1]),
|
||||
message=message_kind(payload), tid=stun_tid(payload))
|
||||
except Exception: # noqa: BLE001 - evidence, never the road
|
||||
pass
|
||||
super()._deliver(relay, to, host, port, payload)
|
||||
|
||||
def _attributing(self) -> bool:
|
||||
phase = self.rec.phase
|
||||
return any(phase == p or phase.startswith(p + ".") for p in self.attribute_in)
|
||||
@@ -782,7 +983,9 @@ def make_lab_classes() -> Tuple[type, type, type]:
|
||||
|
||||
def _route(self, host: str, dport: int, atyp: int, payload: bytes, out_port: int, answer: Any) -> Any:
|
||||
association = getattr(self._dgram, "index", None)
|
||||
self.rec.event("udp", target="%s:%d" % (host, dport), message=message_kind(payload), opener=self._association_openers.get(association) if association is not None else None)
|
||||
# ``deallocation``: the datagram is a TURN deallocation by what it means (``_turn_chain.is_deallocation``, the reading the lab's TURN server uses): marked here, where the payload is.
|
||||
self.rec.event("udp", target="%s:%d" % (host, dport), message=message_kind(payload), tid=stun_tid(payload), deallocation=is_deallocation(payload),
|
||||
opener=self._association_openers.get(association) if association is not None else None)
|
||||
if atyp == 1 and (host, dport) == (TURN_IP, TURN_PORT):
|
||||
return self.turn.address, (host, dport)
|
||||
if (host, dport) in ((STUN_NAME, STUN_PORT), (STUN_NUMBER, STUN_PORT), (MEASURE_NUMBER, STUN_PORT)):
|
||||
@@ -796,12 +999,18 @@ def make_lab_classes() -> Tuple[type, type, type]:
|
||||
from an address of the host to loopback."""
|
||||
|
||||
def __init__(self, address: str) -> None:
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.bind((address, 0))
|
||||
self.address = self.sock.getsockname()
|
||||
raw = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
raw.bind((address, 0))
|
||||
self.address = raw.getsockname()
|
||||
#: Every STUN datagram it received with the answers it sent (``turn_request_record``), by the clock the lab sets (``Lab``): evidence of the WebRTC walk, never compared.
|
||||
self.exchanges: list = []
|
||||
self.clock: Callable[[], float] = time.monotonic
|
||||
self.sock = ExchangeSocket(raw, self)
|
||||
self.seen: list = []
|
||||
self.allocations: list = []
|
||||
self.requests: list = []
|
||||
self.deallocations: list = []
|
||||
self.refused: list = []
|
||||
self._closed = False
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
@@ -852,25 +1061,42 @@ JOURNEY_A, JOURNEY_O = "journey-a.test", "journey-o.test"
|
||||
PAGE_NAME, H1_NAME, H2_NAME, H3_NAME = "page.lab.test", "h1.lab.test", "h2.lab.test", "h3.lab.test"
|
||||
STUN_URL = "stun:198.51.100.5:19302"
|
||||
TURN_URL = "turn:198.51.100.7:3478?transport=udp"
|
||||
#: The probe of the WebRTC page: one STUN and one TURN server by address (the relay answers both), a data channel, and the page waits for the end of the gather (the
|
||||
#: The TURN server of ``TURN_URL`` as the gateway names the target of a datagram (a test holds it equal to ``tests/_turn_chain.py``).
|
||||
TURN_TARGET = "198.51.100.7:3478"
|
||||
#: The user name the probe gives the TURN server (the lab's server takes any: the key is made from it and the password of ``tests/_turn_chain.py``, which the walk passes as the credential).
|
||||
TURN_USERNAME = "lab"
|
||||
#: The probe of the WebRTC page: one STUN and one TURN server by address (the relay answers both; the TURN's user name and credential are its arguments, never written here), a data channel, and the page waits for the end of the gather (the
|
||||
#: timer is the safety net of a gather that never ends, not a measure of it).
|
||||
RTC_JS = r"""async (urls) => {
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: [urls[0]]}, {urls: [urls[1]], username: 'lab', credential: 'lab'}]});
|
||||
RTC_JS = r"""async (args) => {
|
||||
const [stunUrl, turnUrl, username, credential] = args;
|
||||
const T = {start: performance.now(), offer: null, local: null, candidates: [], errors: [], gathered: null, closing: null, closed: null};
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: [stunUrl]}, {urls: [turnUrl], username, credential}]});
|
||||
pc.createDataChannel('');
|
||||
const cands = [], errors = [];
|
||||
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
|
||||
pc.addEventListener('icecandidateerror', e => { errors.push({code: e.errorCode, url: e.url}); });
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
pc.addEventListener('icecandidate', e => {
|
||||
if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate);
|
||||
T.candidates.push({t: performance.now(), type: e.candidate ? (e.candidate.type || null) : 'end'});
|
||||
});
|
||||
pc.addEventListener('icecandidateerror', e => {
|
||||
errors.push({code: e.errorCode, url: e.url});
|
||||
T.errors.push({t: performance.now(), code: e.errorCode, url: e.url});
|
||||
});
|
||||
const offer = await pc.createOffer();
|
||||
T.offer = performance.now();
|
||||
await pc.setLocalDescription(offer);
|
||||
T.local = performance.now();
|
||||
await new Promise(resolve => {
|
||||
const timer = setTimeout(resolve, 30000);
|
||||
const done = () => { clearTimeout(timer); resolve(); };
|
||||
const done = () => { clearTimeout(timer); if (T.gathered === null) T.gathered = performance.now(); resolve(); };
|
||||
if (pc.iceGatheringState === 'complete') done();
|
||||
pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') done(); });
|
||||
});
|
||||
const sdp = (pc.localDescription && pc.localDescription.sdp) || '';
|
||||
const gathering = pc.iceGatheringState;
|
||||
T.closing = performance.now();
|
||||
try { pc.close(); } catch (e) {}
|
||||
return {candidates: cands, errors, sdp, gathering};
|
||||
T.closed = performance.now();
|
||||
return {candidates: cands, errors, sdp, gathering, times: T};
|
||||
}"""
|
||||
FETCH_JS = r"""async () => {
|
||||
await (await fetch('/api?x=1', {cache: 'no-store'})).text();
|
||||
@@ -975,6 +1201,8 @@ class Lab:
|
||||
self.roles: Dict[int, str] = {}
|
||||
self.collisions: List[Tuple[int, str, str]] = []
|
||||
self.norm = Normalizer(self.roles)
|
||||
#: What the WebRTC walk measured about itself (``walk_webrtc``), for ``webrtc_evidence``: never a leaf.
|
||||
self.webrtc: Dict[str, Any] = {}
|
||||
self._closers: List[Callable[[], None]] = []
|
||||
self.h1 = self.h2 = self.h3 = None
|
||||
self.origin_a = self.origin_o = ""
|
||||
@@ -991,6 +1219,7 @@ class Lab:
|
||||
self._closers.append(self.witness.close)
|
||||
self._claim(self.witness.port, "witness")
|
||||
self.turn = turn_class(self.host)
|
||||
self.turn.clock = self.rec.now
|
||||
self._closers.append(self.turn.close)
|
||||
self.gateway = gateway_class(self.rec, self.doh, self.turn, self.host, self.exit_ip)
|
||||
self.gateway.attribute_in = attribute_in
|
||||
@@ -1078,9 +1307,10 @@ def guarded(fn: Callable[[], Any]) -> Any:
|
||||
return {"error": _first_line(exc)}
|
||||
|
||||
|
||||
def phase_data(lab: Lab, phase: str, skip_connects: Callable[[str], bool] = lambda target: False) -> Dict[str, Any]:
|
||||
def phase_data(lab: Lab, phase: str, skip_connects: Callable[[str], bool] = lambda target: False,
|
||||
skip_udp: Callable[[Dict[str, Any]], bool] = lambda event: False) -> Dict[str, Any]:
|
||||
"""What the lab saw in a stage and the stages under it: the CONNECTs, the DoH questions, the datagrams, the HTTP requests of the tees. Where the lab looked who opened an entry
|
||||
(``Lab(attribute_in=...)``), each summary says so: ``openers``. ``skip_connects`` leaves out the CONNECTs it is true of."""
|
||||
(``Lab(attribute_in=...)``), each summary says so: ``openers``. ``skip_connects`` leaves out the CONNECTs it is true of, ``skip_udp`` the datagrams (events) it is true of."""
|
||||
queries = [(q.name, q.qtype, q.via) for q in lab.rec.slice("doh", phase)]
|
||||
gateway = getattr(lab, "gateway", None)
|
||||
attributing = bool(gateway is not None and gateway.attribute_in)
|
||||
@@ -1088,7 +1318,7 @@ def phase_data(lab: Lab, phase: str, skip_connects: Callable[[str], bool] = lamb
|
||||
connects = [e for e in lab.rec.of(phase, "connect") if not skip_connects(e["target"])]
|
||||
return {"connects": connect_summary([e["target"] for e in connects], lab.norm, [e.get("opener") for e in connects]),
|
||||
"dns": dns_summary(queries, [gateway.opener_of_connection(i) for i in asked_on] if attributing else None),
|
||||
"udp": udp_summary(lab.rec.of(phase, "udp"), lab.norm), "requests": request_summary(lab.rec.of(phase, "http"), lab.norm)}
|
||||
"udp": udp_summary([e for e in lab.rec.of(phase, "udp") if not skip_udp(e)], lab.norm), "requests": request_summary(lab.rec.of(phase, "http"), lab.norm)}
|
||||
|
||||
|
||||
def launch_data(lab: Lab) -> Dict[str, Any]:
|
||||
@@ -1403,22 +1633,88 @@ def walk_h3(browser: Any, lab: Lab, guard_ms: int = LEAVE_GUARD_MS) -> Dict[str,
|
||||
|
||||
|
||||
def walk_webrtc(browser: Any, lab: Lab) -> Dict[str, Any]:
|
||||
from _turn_chain import PASSWORD as TURN_PASSWORD # the one the lab's TURN server signs its answers with: a browser with another finds every success invalid and makes no relay
|
||||
|
||||
lab.rec.set_phase("webrtc")
|
||||
context = browser.new_context(ignore_https_errors=True)
|
||||
try:
|
||||
page = context.new_page()
|
||||
page.goto("http://%s:%d/rtc" % (PAGE_NAME, lab.site.port), wait_until="load", timeout=60000)
|
||||
result = page.evaluate(RTC_JS, [STUN_URL, TURN_URL])
|
||||
lab.webrtc["evaluate"] = {"called": lab.rec.now()}
|
||||
result = page.evaluate(RTC_JS, [STUN_URL, TURN_URL, TURN_USERNAME, TURN_PASSWORD])
|
||||
lab.webrtc["evaluate"]["returned"] = lab.rec.now()
|
||||
finally:
|
||||
context.close()
|
||||
lab.rec.set_phase("webrtc.end")
|
||||
data = phase_data(lab, "webrtc")
|
||||
# What the page measured of itself goes to the evidence and to nothing that is compared: ``webrtc_summary`` reads the fields it always read.
|
||||
lab.webrtc["page"] = result.pop("times", None)
|
||||
# The TURN deallocation (a Refresh with LIFETIME 0) is one best-effort send at teardown, so it is evidence (``webrtc_evidence``) and no leaf. Source: dom/media/webrtc/transport/third_party/
|
||||
# nICEr/src/stun/turn_client_ctx.cpp:693-730, ``nr_turn_client_deallocate``: ONE request, no retransmission, sent while the TURN context is destroyed. It reaches the lab in some walks and
|
||||
# not in others for the same engine, so it is out of the datagrams counted for the TURN address (told by the mark the gateway wrote on it from its payload, not by when it came) and out
|
||||
# of the messages (told by the transaction id the lab's TURN server wrote for it, recorded before the request itself).
|
||||
ended = {tid.hex() for tid in lab.turn.deallocation_tids()}
|
||||
data = phase_data(lab, "webrtc", skip_udp=lambda event: event["target"] == TURN_TARGET and bool(event.get("deallocation")))
|
||||
lab.webrtc["counted"] = len(lab.rec.of("webrtc", "udp"))
|
||||
out = webrtc_summary(result, lab.exit_ip)
|
||||
marked = [e for e in lab.rec.of("webrtc", "udp") if e["target"] == TURN_TARGET and e.get("deallocation")]
|
||||
out.update(connects=data["connects"], dns=data["dns"], udp=data["udp"],
|
||||
turn={"messages": sorted({"0x%04x" % t for _ip, _port, t in lab.turn.seen}), "allocated": bool(lab.turn.allocations)})
|
||||
turn={"messages": sorted({"0x%04x" % t for _when, tid, t, _credentials in lab.turn.requests if tid.hex() not in ended}), "allocated": bool(lab.turn.allocations),
|
||||
"refused": len(lab.turn.refused), "deallocation": deallocation_facts(lab.turn, marked, closing_began(lab.webrtc["evaluate"]["called"], lab.webrtc["page"]))})
|
||||
return lab.norm.walk(out)
|
||||
|
||||
|
||||
def closing_began(called: float, page: Optional[Dict[str, Any]]) -> Optional[float]:
|
||||
"""The moment, on the recorder's clock, from which the page was closing its connection: the recorder's time at which the walk called the page (``evaluate.called``) plus the time the page
|
||||
measured from its start to its ``closing`` (``performance.now()`` in milliseconds, of the page's own clock: ``start`` and ``closing`` are both read there, so their difference is a length
|
||||
of time and needs no common origin). The script starts at or after the call, so this is never later than the real moment: a deallocation before it was surely sent before the close.
|
||||
None when the page did not return its times."""
|
||||
if not isinstance(page, dict) or page.get("start") is None or page.get("closing") is None:
|
||||
return None
|
||||
return called + (page["closing"] - page["start"]) / 1000.0
|
||||
|
||||
|
||||
def deallocation_facts(turn: Any, marked: List[Dict[str, Any]], began_closing: Optional[float]) -> Dict[str, int]:
|
||||
"""What the lab heard of deallocations that a walk must not have: ``repeated`` allocations that were ended by more than one transaction, ``unallocated`` deallocations from an address
|
||||
that has no allocation (both from the lab's TURN server), and ``early`` deallocation transactions that the gateway carried (``marked``, its events of them) before the page began closing
|
||||
(``began_closing``, :func:`closing_began`; unknown: none is early). All are 0 in a healthy walk; ``turn_deallocation_problems`` says it when they are not, and they are never compared."""
|
||||
ends: collections.Counter = collections.Counter()
|
||||
unallocated = 0
|
||||
for _ip, _port, _tid, _t, allocation in turn.deallocation_transactions():
|
||||
if allocation is None:
|
||||
unallocated += 1
|
||||
else:
|
||||
ends[allocation] += 1
|
||||
first: Dict[Any, float] = {}
|
||||
for event in marked:
|
||||
first.setdefault(event.get("tid"), event["t"])
|
||||
early = sum(1 for t in first.values() if began_closing is not None and t < began_closing)
|
||||
return {"repeated": sum(1 for n in ends.values() if n > 1), "unallocated": unallocated, "early": early}
|
||||
|
||||
|
||||
def webrtc_evidence(lab: Lab) -> Dict[str, Any]:
|
||||
"""The WebRTC walk of a seed as it happened, outside the leaves that are compared: every datagram the gateway routed in its stages (when, to whom, the message, the STUN transaction id,
|
||||
its stage, and whether it was already there when the summary of the walk was taken: ``counted``), the moments of the stages and of the page's call on the recorder's clock, and the
|
||||
page's own ``performance.now()`` at each step of the gather (``page``: the offer, each candidate with its type, each error with its code and url, the end of the gather, the close).
|
||||
It exists to tell two readings of a run that differs from itself apart: a close that cuts the retransmissions of the TURN server short at a variable point, and a retransmission of the
|
||||
first request whose answer came late."""
|
||||
info = getattr(lab, "webrtc", None) or {}
|
||||
began = lab.rec.phase_t.get("webrtc")
|
||||
counted = info.get("counted")
|
||||
datagrams = [{"t": e["t"], "phase": e["phase"], "target": e["target"], "message": e["message"], "tid": e.get("tid"), "counted": counted is None or i < counted}
|
||||
for i, e in enumerate(lab.rec.of("webrtc", "udp"))]
|
||||
# The lab's TURN server: each request with what it carried and what it answered; the relay's datagrams back to the browser: the address each claims and the 5-tuple it goes to.
|
||||
exchanges = [e for e in getattr(getattr(lab, "turn", None), "exchanges", None) or [] if began is None or e["t"] >= began]
|
||||
returned = [{"t": e["t"], "phase": e["phase"], "claimed": e["claimed"], "to": e["to"], "relay": e["relay"], "message": e["message"], "tid": e.get("tid")} for e in lab.rec.of("webrtc", "udp_back")]
|
||||
# The deallocation (a Refresh with LIFETIME 0, sent once at teardown): whether the lab's TURN server heard it, and for each transaction when (the recorder's clock, from the exchange of
|
||||
# the same transaction id) and which. It is no leaf: the walk leaves it out of what it compares.
|
||||
heard = getattr(getattr(lab, "turn", None), "deallocation_transactions", None)
|
||||
when = {e["tid"]: e["t"] for e in reversed(exchanges)}
|
||||
records = [{"t": when.get(tid.hex()), "tid": tid.hex(), "src": "%s:%d" % (ip, port), "allocation": allocation} for ip, port, tid, _t, allocation in (heard() if heard else [])]
|
||||
return {"phase_t": {name: lab.rec.phase_t.get(name) for name in ("webrtc", "webrtc.end")}, "evaluate": info.get("evaluate"), "page": info.get("page"), "datagrams": datagrams,
|
||||
"turn": exchanges, "returned": returned, "send_errors": list(getattr(getattr(lab, "gateway", None), "send_errors", None) or []),
|
||||
"deallocation": {"seen": bool(records), "records": records}}
|
||||
|
||||
|
||||
def direct_report(lab: Lab, watcher: Any, trap: Any) -> Dict[str, Any]:
|
||||
"""Everything that reached the lab or the network around the proxy. Each list is empty on a browser that keeps its word; a watcher that never saw the
|
||||
browser is a list with that fact in it (a sink that sees nothing proves nothing)."""
|
||||
@@ -1515,7 +1811,7 @@ def wire_evidence(lab: Lab) -> Dict[str, Any]:
|
||||
for q in lab.h3.snapshot()["quic"]:
|
||||
h3.append({"phase": q["phase"], "requests": [{"t": r.get("t"), "written": r.get("written_t"),
|
||||
"request": "%s %s" % (dict(r["headers"]).get(":method"), lab.norm.text(dict(r["headers"]).get(":path", "")))} for r in q["requests"]]})
|
||||
return {"journey": journey, "https": https, "h3": h3}
|
||||
return {"journey": journey, "https": https, "h3": h3, "webrtc": webrtc_evidence(lab)}
|
||||
|
||||
|
||||
def sentinel_signature(lab: Lab) -> Dict[str, Any]:
|
||||
@@ -1726,13 +2022,19 @@ def judge(report: Dict[str, Any], control: bool) -> int:
|
||||
return 2 if control else 1
|
||||
|
||||
|
||||
def run_engine(binary: str, seal: Optional[str], label: str, seeds: Tuple[int, ...], out: Path) -> int:
|
||||
"""``run`` in a process of its own: the seal a process runs under is read at import, so each engine gets its own."""
|
||||
def engine_env(seal: Optional[str]) -> Dict[str, str]:
|
||||
"""The environment of a process that runs one engine: its seal, no autofix, no pin check, no browser logging."""
|
||||
env = dict(os.environ, INVISIBLE_CORE_AUTOFIX="off", INVISIBLE_CORE_PIN="allow")
|
||||
if seal:
|
||||
env["INVISIBLE_SEAL_FILE"] = str(seal)
|
||||
for name in ("MOZ_LOG", "MOZ_LOG_FILE"):
|
||||
env.pop(name, None)
|
||||
return env
|
||||
|
||||
|
||||
def run_engine(binary: str, seal: Optional[str], label: str, seeds: Tuple[int, ...], out: Path) -> int:
|
||||
"""``run`` in a process of its own: the seal a process runs under is read at import, so each engine gets its own."""
|
||||
env = engine_env(seal)
|
||||
env[crash.CRASH_DIR_ENV] = str(Path(out).parent / (Path(out).stem + ".crash")) # footprint-68.json -> transcript-68.crash/: what a launch that did not end with 0 left
|
||||
command = [sys.executable, "-u", str(Path(__file__).resolve()), "run", "--binary", binary, "--label", label, "--seeds", ",".join(map(str, seeds)), "--out", str(out)]
|
||||
print("=== run %s: %s (seal %s)" % (label, binary, seal or "the one this process has"))
|
||||
@@ -1746,6 +2048,167 @@ def run_engine(binary: str, seal: Optional[str], label: str, seeds: Tuple[int, .
|
||||
return 124
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
# The hunt: one walk of one seed, repeated, and the evidence of each repetition (never a verdict)
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
def parse_hunt(text: str) -> Tuple[str, int, int]:
|
||||
"""``webrtc:<seed>:<n>`` -> ``("webrtc", seed, n)``. Anything else is a usage error: the walk is named, the seed and the count are whole numbers, and n is at least 1."""
|
||||
parts = (text or "").strip().split(":")
|
||||
if len(parts) != 3 or parts[0] != "webrtc":
|
||||
raise ValueError("%s is %r: expected webrtc:<seed>:<n>" % (HUNT_ENV, text))
|
||||
try:
|
||||
seed, n = int(parts[1]), int(parts[2])
|
||||
except ValueError:
|
||||
raise ValueError("%s is %r: the seed and n are whole numbers" % (HUNT_ENV, text)) from None
|
||||
if n < 1:
|
||||
raise ValueError("%s is %r: n is at least 1" % (HUNT_ENV, text))
|
||||
return parts[0], seed, n
|
||||
|
||||
|
||||
def hunt_counts(evidence: Optional[Dict[str, Any]]) -> Dict[str, int]:
|
||||
"""Datagrams to the TURN server in a repetition: ``counted`` as the summary of the walk (what the A/A compares) took them, ``all`` with the ones that came after."""
|
||||
turn = [d for d in (evidence or {}).get("datagrams") or [] if d.get("target") == TURN_TARGET]
|
||||
return {"counted": sum(1 for d in turn if d.get("counted")), "all": len(turn)}
|
||||
|
||||
|
||||
def hunt_repetition(binary: str, label: str, i: int, seed: int, patch: Any, out_dir: Optional[Path] = None) -> Dict[str, Any]:
|
||||
"""One repetition: a launch behind a lab as the main launch has it, the WebRTC walk only, the close, and what the lab saw of it. A failure is the ``error`` of the record."""
|
||||
record: Dict[str, Any] = {"format": HUNT_FORMAT, "engine": label, "i": i, "seed": seed, "error": None, "evidence": None}
|
||||
if out_dir is not None:
|
||||
# The engine logs to ``<out_dir>/<engine>-<i>-mozlog`` (its child processes to the same name with ``.child-N``): the launch inherits this process's environment.
|
||||
record["mozlog"] = "%s-%d-mozlog" % (label, i)
|
||||
patch.setenv("MOZ_LOG", HUNT_MOZ_LOG)
|
||||
patch.setenv("MOZ_LOG_FILE", str(Path(out_dir) / record["mozlog"]))
|
||||
try:
|
||||
with open_lab(journey=True, wire=True) as lab:
|
||||
begin_launch(seed, "hunt")
|
||||
session = launch(binary, seed, lab, patch)
|
||||
with session as browser:
|
||||
browser.new_context(ignore_https_errors=True).new_page() # Glean is born when a window opens (``glean_ready``); the walk opens its own context
|
||||
record.update(glean_ready(session, seed, "hunt"))
|
||||
record["walk"] = guarded(lambda: walk_webrtc(browser, lab))
|
||||
record["evidence"] = webrtc_evidence(lab) # after the close: the datagrams the close leaves in flight are in it
|
||||
except Exception as exc: # noqa: BLE001 - evidence, never a verdict
|
||||
record["error"] = _first_line(exc)
|
||||
finally:
|
||||
if out_dir is not None:
|
||||
patch.delenv("MOZ_LOG", raising=False)
|
||||
patch.delenv("MOZ_LOG_FILE", raising=False)
|
||||
record["counts"] = hunt_counts(record["evidence"])
|
||||
return record
|
||||
|
||||
|
||||
def hunt_run(binary: str, label: str, seed: int, n: int, out_dir: Path) -> int:
|
||||
"""``n`` repetitions of the WebRTC walk of ``seed`` with one engine, each written to ``<out_dir>/<label>-<i>.json``. Exits 0: it decides nothing."""
|
||||
import pytest
|
||||
|
||||
patch = pytest.MonkeyPatch()
|
||||
work = Path(tempfile.mkdtemp(prefix="ab-network-hunt-"))
|
||||
try:
|
||||
import _lab_egress
|
||||
|
||||
_lab_egress.install(patch, work)
|
||||
global RUN_LABEL
|
||||
RUN_LABEL = label
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
for i in range(1, n + 1):
|
||||
record = hunt_repetition(binary, label, i, seed, patch, out_dir)
|
||||
write_json(out_dir / ("%s-%d.json" % (label, i)), record)
|
||||
print("hunt %s %d/%d: %d datagrams to the TURN server (%d with the late ones)%s" % (
|
||||
label, i, n, record["counts"]["counted"], record["counts"]["all"], "" if record["error"] is None else ", ERROR " + record["error"]))
|
||||
sys.stdout.flush()
|
||||
return 0
|
||||
finally:
|
||||
patch.undo()
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def hunt_summary(records: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""The summary of the repetition files: per repetition the count of datagrams to the TURN server (``count_3478``: as the A/A counts them; ``count_3478_all``: with the late ones) and, per
|
||||
target, the transaction ids in the order they first appeared with the number of datagrams each carried (``[tid, n]``: a retransmission repeats its request's id); per engine, how often
|
||||
each count came."""
|
||||
repetitions = []
|
||||
distribution: Dict[str, collections.Counter] = {}
|
||||
for record in records:
|
||||
counts = hunt_counts(record.get("evidence"))
|
||||
groups: Dict[str, Dict[Any, int]] = {}
|
||||
for d in (record.get("evidence") or {}).get("datagrams") or []:
|
||||
tids = groups.setdefault(d["target"], {})
|
||||
tids[d.get("tid")] = tids.get(d.get("tid"), 0) + 1
|
||||
repetitions.append({"engine": record["engine"], "i": record["i"], "count_3478": counts["counted"], "count_3478_all": counts["all"],
|
||||
"targets": {t: [[tid, n] for tid, n in groups[t].items()] for t in sorted(groups)}, "error": record.get("error")})
|
||||
distribution.setdefault(record["engine"], collections.Counter())[counts["counted"]] += 1
|
||||
return {"format": HUNT_SUMMARY_FORMAT, "target": TURN_TARGET, "repetitions": repetitions,
|
||||
"count_3478_by_engine": {engine: {str(k): v for k, v in sorted(c.items())} for engine, c in sorted(distribution.items())}}
|
||||
|
||||
|
||||
def read_hunt_records(folder: Path) -> List[Dict[str, Any]]:
|
||||
"""The repetition files of a folder, by engine and repetition."""
|
||||
records = []
|
||||
for path in sorted(Path(folder).glob("*.json")):
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
if document.get("format") == HUNT_FORMAT:
|
||||
records.append(document)
|
||||
return sorted(records, key=lambda r: (r["engine"], r["i"]))
|
||||
|
||||
|
||||
#: The safety net of a hunt's engine run, in seconds: a base and a share per repetition (a launch, Glean, the gather's own 30 s). Never a verdict.
|
||||
HUNT_BASE_S = 600
|
||||
HUNT_PER_REPETITION_S = 120
|
||||
|
||||
|
||||
def hunt_engine(binary: str, seal: Optional[str], label: str, seed: int, n: int, out_dir: Path) -> int:
|
||||
"""``hunt_run`` in a process of its own, as ``run_engine`` runs ``run``: each engine its own seal and its own cache."""
|
||||
env = engine_env(seal)
|
||||
command = [sys.executable, "-u", str(Path(__file__).resolve()), "hunt-run", "--binary", binary, "--label", label, "--seed", str(seed), "--n", str(n), "--out", str(out_dir)]
|
||||
print("=== hunt %s: %s (seal %s), %d repetitions of the WebRTC walk of seed %d" % (label, binary, seal or "the one this process has", n, seed))
|
||||
sys.stdout.flush()
|
||||
from ci_ab_oracle import own_cache_env
|
||||
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="ab-network-cache-") as cache:
|
||||
return subprocess.run(command, env=own_cache_env(env, cache), timeout=HUNT_BASE_S + n * HUNT_PER_REPETITION_S).returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
return 124
|
||||
|
||||
|
||||
def published_engine(args: argparse.Namespace, work: Path) -> Tuple[str, Optional[str]]:
|
||||
"""The published engine of an ``ab``: the binary the caller gave, or the one the release holds, with its seal."""
|
||||
if args.published_binary:
|
||||
return str(args.published_binary), (str(args.published_seal) if args.published_seal else None)
|
||||
import ci_ab_oracle as oracle
|
||||
|
||||
binary, seal = oracle.fetch_published(args.engine_tag, work)
|
||||
return binary, str(seal)
|
||||
|
||||
|
||||
def cmd_hunt(args: argparse.Namespace, spec: str) -> int:
|
||||
"""``ab`` with ``AB_NETWORK_HUNT=webrtc:<seed>:<n>``: the WebRTC walk of that seed, ``n`` times, for each engine of the A/A (the published engine twice), written to ``<out>/hunt``:
|
||||
``<engine>-<i>.json`` per repetition and ``summary.json``. It decides nothing and exits 0 (2 only for a spec that does not read)."""
|
||||
try:
|
||||
_walk, seed, n = parse_hunt(spec)
|
||||
except ValueError as exc:
|
||||
print("FAIL " + str(exc))
|
||||
return 2
|
||||
out = Path(args.out) / "hunt"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
work = Path(tempfile.mkdtemp(prefix="ab-network-"))
|
||||
try:
|
||||
binary, seal = published_engine(args, work)
|
||||
for label in (args.engine_tag, args.engine_tag + "-again"):
|
||||
code = hunt_engine(binary, seal, label, seed, n, out)
|
||||
if code != 0:
|
||||
print("hunt %s ended with %s" % (label, code))
|
||||
summary = hunt_summary(read_hunt_records(out))
|
||||
write_json(out / "summary.json", summary)
|
||||
for r in summary["repetitions"]:
|
||||
print("hunt %s %d: %d to the TURN server (%d with the late ones); %s" % (r["engine"], r["i"], r["count_3478"], r["count_3478_all"], r["targets"].get(TURN_TARGET)))
|
||||
print("hunt summary written: %s" % (out / "summary.json"))
|
||||
return 0
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def compare_files(a: Path, b: Path, out: Optional[Path], floor: int, volatile_path: Path, control: bool) -> Dict[str, Any]:
|
||||
ta, tb = read_transcript(a), read_transcript(b)
|
||||
report = compare_transcripts(ta, tb, load_volatile(volatile_path), floor, ta.get("label", "A"), tb.get("label", "B"))
|
||||
@@ -1757,6 +2220,9 @@ def compare_files(a: Path, b: Path, out: Optional[Path], floor: int, volatile_pa
|
||||
|
||||
|
||||
def cmd_ab(args: argparse.Namespace) -> int:
|
||||
spec = os.environ.get(HUNT_ENV)
|
||||
if spec:
|
||||
return cmd_hunt(args, spec)
|
||||
out = Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
seeds = parse_seeds(args.seeds)
|
||||
@@ -1768,13 +2234,7 @@ def cmd_ab(args: argparse.Namespace) -> int:
|
||||
return 2
|
||||
work = Path(tempfile.mkdtemp(prefix="ab-network-"))
|
||||
try:
|
||||
if args.published_binary:
|
||||
binary, seal = str(args.published_binary), (str(args.published_seal) if args.published_seal else None)
|
||||
else:
|
||||
import ci_ab_oracle as oracle
|
||||
|
||||
binary, seal = oracle.fetch_published(args.engine_tag, work)
|
||||
seal = str(seal)
|
||||
binary, seal = published_engine(args, work)
|
||||
tag = args.engine_tag.rsplit("-", 1)[-1]
|
||||
first, again = out / ("transcript-%s.json" % tag), out / ("transcript-%s-again.json" % tag)
|
||||
problems = []
|
||||
@@ -1810,6 +2270,12 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
r.add_argument("--label", default="engine")
|
||||
r.add_argument("--seeds", default=None)
|
||||
r.add_argument("--out", type=Path, required=True)
|
||||
h = sub.add_parser("hunt-run", help="one engine: the WebRTC walk of one seed, n times (what AB_NETWORK_HUNT makes `ab` run)")
|
||||
h.add_argument("--binary", required=True)
|
||||
h.add_argument("--label", required=True)
|
||||
h.add_argument("--seed", type=int, required=True)
|
||||
h.add_argument("--n", type=int, required=True)
|
||||
h.add_argument("--out", type=Path, required=True)
|
||||
c = sub.add_parser("compare", help="two transcripts: the diff and the leaf count")
|
||||
c.add_argument("a", type=Path)
|
||||
c.add_argument("b", type=Path)
|
||||
@@ -1835,6 +2301,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
args = ap.parse_args(argv)
|
||||
if args.cmd == "run":
|
||||
return run(args.binary, args.label, parse_seeds(args.seeds), args.out)
|
||||
if args.cmd == "hunt-run":
|
||||
return hunt_run(args.binary, args.label, args.seed, args.n, args.out)
|
||||
if args.cmd == "compare":
|
||||
return judge(compare_files(args.a, args.b, args.out, args.floor, args.volatile, args.a_a), args.a_a)
|
||||
if args.cmd == "judge":
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
"""Does a change have anything for a heavy workflow to test? The job `changes` of e2e.yml and of fakeweb.yml.
|
||||
|
||||
python scripts/ci_changes.py <e2e|fakeweb> <github.event_name> [BASE_SHA HEAD_SHA]
|
||||
|
||||
GitHub applies no `paths` filter to a merge queue run (`merge_group`), so without this a docs-only change would run the whole e2e and the whole fake web in
|
||||
the queue. In a queue run this lists the files that differ between the base and the head of the entry (`github.event.merge_group.base_sha` and
|
||||
`head_sha`) and applies the path rules the `push` trigger of the same workflow has, so the queue and main agree on what is worth a run:
|
||||
|
||||
e2e `paths-ignore`: a change runs it unless EVERY file matches IGNORE (`**.md`, `docs/**`, `LICENSE`);
|
||||
fakeweb `paths`: a change runs it only if SOME file matches ONLY (the fake web, its report, the pin, its workflow).
|
||||
|
||||
On any other event (push and workflow_dispatch: a push was already filtered by GitHub, a dispatch is a person asking) the answer is always `run=true`.
|
||||
|
||||
Prints `run=true|false` and `files=<n>` (the lines go to $GITHUB_OUTPUT). `run=false` is an explicit answer, "nothing to test": the verdict job of the workflow
|
||||
(scripts/ci_gate.py) then expects every other job `skipped` and says so in its last line; it is never a skip the verdict waves through. A change that cannot be
|
||||
listed (a commit that cannot be fetched) is an error: the job is red, and so is the verdict. A change that lists no file at all cannot be told from a broken
|
||||
diff, so it runs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# e2e.yml `on.push.paths-ignore`: a change of only these files is not a change the browsers can observe (tests/test_the_workflows_are_ready_for_the_merge_queue.py
|
||||
# holds this table equal to the filter of the workflow).
|
||||
IGNORE = {
|
||||
"e2e": ("**.md", "docs/**", "LICENSE"),
|
||||
}
|
||||
# fakeweb.yml `on.push.paths`.
|
||||
ONLY = {
|
||||
"fakeweb": (
|
||||
"tests/fakeweb/**",
|
||||
"tests/test_fakeweb_*.py",
|
||||
"scripts/run_fakeweb.py",
|
||||
"scripts/fakeweb_p4_report.py",
|
||||
"scripts/playwright_pin.txt",
|
||||
".github/workflows/fakeweb.yml",
|
||||
),
|
||||
}
|
||||
WORKFLOWS = tuple(sorted(set(IGNORE) | set(ONLY)))
|
||||
|
||||
|
||||
def glob_regex(pattern: str) -> "re.Pattern[str]":
|
||||
"""A path filter of a workflow as a regular expression: `**` is any characters, `*` any characters but `/`, `?` one character but `/`."""
|
||||
out = []
|
||||
i = 0
|
||||
while i < len(pattern):
|
||||
if pattern.startswith("**", i):
|
||||
out.append(".*")
|
||||
i += 2
|
||||
continue
|
||||
char = pattern[i]
|
||||
out.append("[^/]*" if char == "*" else "[^/]" if char == "?" else re.escape(char))
|
||||
i += 1
|
||||
return re.compile("".join(out) + r"\Z")
|
||||
|
||||
|
||||
def matches(path: str, patterns) -> bool:
|
||||
return any(glob_regex(p).match(path) for p in patterns)
|
||||
|
||||
|
||||
def should_run(workflow: str, files: list) -> bool:
|
||||
"""Is there something in `files` (the paths a change touches) for `workflow` to test?"""
|
||||
if workflow not in WORKFLOWS:
|
||||
raise ValueError("unknown workflow %r (one of %s)" % (workflow, ", ".join(WORKFLOWS)))
|
||||
if not files:
|
||||
return True
|
||||
if workflow in IGNORE:
|
||||
return any(not matches(f, IGNORE[workflow]) for f in files)
|
||||
return any(matches(f, ONLY[workflow]) for f in files)
|
||||
|
||||
|
||||
def changed_files(base: str, head: str, run=subprocess.run) -> list:
|
||||
"""The files that differ between the base and the head of a queue entry (fetched when the shallow checkout does not have them)."""
|
||||
for sha in (base, head):
|
||||
if run(["git", "cat-file", "-e", sha + "^{commit}"], capture_output=True, text=True).returncode != 0:
|
||||
run(["git", "fetch", "--no-tags", "--depth=1", "origin", sha], check=True, capture_output=True, text=True)
|
||||
done = run(["git", "diff", "--name-only", base, head], check=True, capture_output=True, text=True)
|
||||
return [line.strip() for line in done.stdout.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
args = sys.argv[1:] if argv is None else argv
|
||||
if len(args) not in (2, 4) or args[0] not in WORKFLOWS:
|
||||
print("usage: ci_changes.py <%s> EVENT_NAME [BASE_SHA HEAD_SHA]" % "|".join(WORKFLOWS), file=sys.stderr)
|
||||
return 2
|
||||
workflow, event = args[0], args[1]
|
||||
sys.stdout.reconfigure(newline="\n") # the lines go to $GITHUB_OUTPUT: a carriage return would be part of the value
|
||||
if event != "merge_group":
|
||||
print("%s: %s is not a merge queue run, it always runs" % (workflow, event or "no event"), file=sys.stderr)
|
||||
print("run=true")
|
||||
print("files=0")
|
||||
return 0
|
||||
if len(args) != 4 or not args[2] or not args[3]:
|
||||
print("FAIL changes: a merge queue run without the base and the head of its entry. Fix: pass github.event.merge_group.base_sha and head_sha", file=sys.stderr)
|
||||
return 2
|
||||
files = changed_files(args[2], args[3])
|
||||
run = should_run(workflow, files)
|
||||
print("%s: %d files changed, %s" % (workflow, len(files), "something to test" if run else "none under its paths: nothing to test"), file=sys.stderr)
|
||||
for name in files[:20]:
|
||||
print(" " + name, file=sys.stderr)
|
||||
print("run=%s" % ("true" if run else "false"))
|
||||
print("files=%d" % len(files))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -54,8 +54,74 @@ TAB_PREFIX = "crash.tab."
|
||||
TAB_LOST = ("cannot find session", "target closed", "targetclosederror", "session closed", "has been closed", "pipe is closed", "pipe closed", "page crashed", "tab crashed")
|
||||
STRACE_TAIL_LINES = 100
|
||||
SIGNAL_LINES = 20
|
||||
#: The gdb commands: every thread's stack, the reason MOZ_CRASH wrote, the libraries the core mapped.
|
||||
GDB_COMMANDS = ("thread apply all bt", "x/s *(char**)&gMozCrashReason", "info sharedlibrary")
|
||||
def argv_and_env_keys(word, cstring, argc, argv, environ, most=1024):
|
||||
"""The command line of a dead process and the NAMES of its environment, read from its memory: `word(address)` reads 8 bytes (little endian), `cstring(address)`
|
||||
a NUL-ended string; `argc`/`argv` are glibc's `__libc_argc`/`__libc_argv` (the arguments main received), `environ` is libc's `environ` (the environment at the
|
||||
end). Only the names of the variables are returned, never their values (a CI environment carries tokens). ([args], [names], what could not be read)."""
|
||||
args, names, problems = [], [], []
|
||||
if not 0 <= argc <= most:
|
||||
problems.append("argc %r is not a count" % (argc,))
|
||||
argc = 0
|
||||
for i in range(argc):
|
||||
try:
|
||||
args.append(cstring(word(argv + 8 * i)))
|
||||
except Exception as problem:
|
||||
problems.append("argv[%d]: %s" % (i, problem))
|
||||
break
|
||||
at = environ
|
||||
while at and len(names) < most:
|
||||
try:
|
||||
pointer = word(at)
|
||||
if pointer == 0:
|
||||
break
|
||||
names.append(cstring(pointer).split("=", 1)[0])
|
||||
except Exception as problem:
|
||||
problems.append("environ: %s" % (problem,))
|
||||
break
|
||||
at += 8
|
||||
return args, names, problems
|
||||
|
||||
|
||||
#: The readers gdb gives `argv_and_env_keys` (its memory of the core), and what it prints. Which process died (a parent, a background task, a content process) is in
|
||||
#: its arguments; the name of the crashing thread only says which thread. The core of run 45755178008 named a thread FSBroker7536 of a process the oracle did not launch.
|
||||
ARGV_GDB_READERS = r'''
|
||||
import gdb
|
||||
_inf = gdb.selected_inferior()
|
||||
def _word(a):
|
||||
return int.from_bytes(bytes(_inf.read_memory(a, 8)), "little")
|
||||
def _cstring(a):
|
||||
out = b""
|
||||
while len(out) < 65536:
|
||||
chunk = bytes(_inf.read_memory(a + len(out), 64))
|
||||
if b"\0" in chunk:
|
||||
return (out + chunk.split(b"\0", 1)[0]).decode("utf-8", "replace")
|
||||
out += chunk
|
||||
return out.decode("utf-8", "replace")
|
||||
def _value(expression):
|
||||
try:
|
||||
return int(gdb.parse_and_eval(expression))
|
||||
except Exception as problem:
|
||||
print("process: %s unreadable: %s" % (expression, problem))
|
||||
return 0
|
||||
'''
|
||||
ARGV_GDB_PRINT = r'''
|
||||
_args, _names, _problems = argv_and_env_keys(_word, _cstring, _value("*(int*)&__libc_argc"), _value("(long)*(char***)&__libc_argv"),
|
||||
_value("(long)*(char***)&environ"))
|
||||
print("process argv (%d): %r" % (len(_args), _args))
|
||||
print("process environment names (%d): %s" % (len(_names), " ".join(sorted(set(_names)))))
|
||||
for _p in _problems:
|
||||
print("process: %s" % _p)
|
||||
'''
|
||||
|
||||
|
||||
def argv_gdb_command() -> str:
|
||||
"""The one gdb command (`python exec(...)`) that prints the dead process's arguments and the names of its environment (`argv_and_env_keys`)."""
|
||||
import inspect
|
||||
return "python exec(%r)" % (ARGV_GDB_READERS + inspect.getsource(argv_and_env_keys) + ARGV_GDB_PRINT,)
|
||||
|
||||
|
||||
#: The gdb commands: every thread's stack, the reason MOZ_CRASH wrote, the libraries the core mapped, and which process it was (its arguments).
|
||||
GDB_COMMANDS = ("thread apply all bt", "x/s *(char**)&gMozCrashReason", "info sharedlibrary", argv_gdb_command())
|
||||
GDB_LIMIT = 400_000
|
||||
CORE_LIMIT = 3
|
||||
#: The exit code of Linux processes that a signal ended is the negative of its number (Python's `Popen`).
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
"""The verdict job of a workflow that gates a merge: every job it waits for must have ended in `success`.
|
||||
|
||||
NEEDS='<toJSON(needs)>' EVENT_NAME=<github.event_name> WORKFLOW=<tests|e2e|fakeweb> [CHANGES_RUN=<needs.changes.outputs.run>] python scripts/ci_gate.py
|
||||
|
||||
Three workflows have one: the job `gate` of tests.yml, `e2e verdict` of e2e.yml and `fakeweb verdict` of fakeweb.yml. WORKFLOW (default `tests`) picks
|
||||
the tables that belong to the workflow. A pull request runs the fast set (tests.yml); e2e.yml and fakeweb.yml run in the merge queue run
|
||||
(`merge_group`), and that run decides. `gate` is the one context main requires on a pull request.
|
||||
|
||||
Rule ci-13: nothing counts as passed that did not pass, so `skipped`, `cancelled` and `failure` are all red. A job that was skipped ran nothing: when
|
||||
`unit` was skipped for a core that was not on the index, the old gate said "ok".
|
||||
|
||||
The only jobs that may end in something else than `success` are the ones that are conditional BY DESIGN, and each says when:
|
||||
|
||||
* CONDITIONAL: the events on which the job runs; on any other event it is expected to be `skipped`, and on those events it must be `success`;
|
||||
* E2E_BY_OUTPUT: a job that runs only when another job of the workflow says so by an output (the final-seed shards, when the page oracle is touched);
|
||||
* E2E_NARROWED: what `workflow_dispatch` with `only: windows-control-a` leaves out on purpose (that run is the Windows job of one shortcut alone).
|
||||
|
||||
* NOTHING TO TEST: e2e.yml and fakeweb.yml start with the job `changes` (scripts/ci_changes.py: in a merge queue run, do the files of the entry fall under the
|
||||
paths of the workflow?). Its output `run` comes in as CHANGES_RUN. `run=false` is an explicit answer: `changes` must be `success` and every other job
|
||||
`skipped` (a job that ran anyway is red, so is one that is `success` here), and the verdict ends with `ok: nothing to test (<n> files changed, none under the
|
||||
paths of <workflow>)`. `run=true`: every job as above. A `run` that is missing or is not `true` or `false` is red: nothing is judged on a guess.
|
||||
|
||||
Nothing else is forgiven, and a job the workflow waits for that the table does not know is red as well (the table and the `needs:` of the verdict job
|
||||
cannot drift apart without tests/test_the_gate_is_red_when_a_needed_job_is_skipped.py and tests/test_the_workflows_are_ready_for_the_merge_queue.py
|
||||
saying so).
|
||||
|
||||
Prints one line per job that is not as expected, `FAIL <verdict job>: job <name> is <result>. Fix: <how>. Rule: ci-13 ...`, and exits 1; prints `ok` and
|
||||
exits 0 when every job is.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
RULE = "ci-13 nothing counts as passed that did not pass"
|
||||
|
||||
_CHANGES = "open the job `changes` and fix scripts/ci_changes.py (or the diff it lists): it must succeed and print run=true|false"
|
||||
_CORE = "wait for the publish of the pinned invisible-core to finish, or pin a published core, then re-run"
|
||||
|
||||
# tests.yml: the jobs `gate` waits for, each with what to do when it is not green.
|
||||
FIX = {
|
||||
"core-on-index": _CORE,
|
||||
"unit": "open the job pytest of the failing system and fix its test; when it is skipped, fix the job it needs (core-on-index) first",
|
||||
"docs-api": "open the job and fix the guide that names an API that does not exist; when it is skipped, fix core-on-index first",
|
||||
"english": "open the job and translate the lines it names; when it is skipped, fix core-on-index first",
|
||||
"claims": "open the job and fix the README sentence no measurement supports; when it is skipped, fix core-on-index first",
|
||||
"way-in": "open the job and make the install instruction uv; when it is skipped, fix core-on-index first",
|
||||
"install-job": "open the job and fix the user-install workflow; when it is skipped, fix core-on-index first",
|
||||
"noreply-identity": "open the job and rewrite the commit or tag whose email is not a GitHub noreply address",
|
||||
"version": "bump the version in pyproject.toml: the one this change proposes is already published",
|
||||
}
|
||||
|
||||
# Conditional by design: job -> the events on which it runs. On any other event it must be `skipped`.
|
||||
CONDITIONAL = {
|
||||
# `version` runs where a change is proposed: on a pull request and in the merge queue run (it compares the version the change proposes with the
|
||||
# published one, so it must run in the queue too). On main straight after a release the version IS the published one until somebody bumps, and a
|
||||
# check that is red at rest is one people learn to skip. So a push to main skips it on purpose.
|
||||
"version": ("pull_request", "merge_group"),
|
||||
}
|
||||
|
||||
# e2e.yml: the jobs `e2e verdict` waits for.
|
||||
E2E_FIX = {
|
||||
"changes": _CHANGES,
|
||||
"core-on-index": _CORE,
|
||||
"linux-deps-e2e": "open the job linux-deps-e2e and fix the package list of the Linux jobs; when it is skipped, fix core-on-index first",
|
||||
"e2e-linux": "open the failing part of `e2e (linux, part N)` and fix its test; when it is skipped, fix core-on-index or linux-deps-e2e first",
|
||||
"e2e": "open the job `e2e (linux, xvfb)`: one of the three Linux parts did not pass",
|
||||
"e2e-windows-control-a": "open the job `e2e (windows, Control+A)` and fix the shortcut test",
|
||||
"e2e-windows": "open the failing part of `e2e (windows, part N)` and fix its test; when it is skipped, fix core-on-index first",
|
||||
"e2e-network": "open the job of the network oracle on Linux and fix its test; when it is skipped, fix core-on-index or linux-deps-e2e first",
|
||||
"e2e-network-windows": "open the job of the network oracle on Windows and fix its test; when it is skipped, fix core-on-index first",
|
||||
"e2e-host": "open the job of the host oracle on Linux and fix its test; when it is skipped, fix core-on-index or linux-deps-e2e first",
|
||||
"e2e-host-windows": "open the job of the host oracle on Windows and fix its test; when it is skipped, fix core-on-index first",
|
||||
"e2e-page": "open the job of the page oracle on Linux and fix its test; when it is skipped, fix core-on-index or linux-deps-e2e first",
|
||||
"e2e-page-windows": "open the job of the page oracle on Windows and fix its test; when it is skipped, fix core-on-index first",
|
||||
"e2e-page-final-touched": "open the job and fix scripts/ci_ab_oracle.py touched: in the merge queue run it must print touched=true|false",
|
||||
"e2e-page-final": "open the failing shard of the page oracle on the final seeds (linux) and fix its test; when it is skipped, fix the job that decides it",
|
||||
"e2e-page-final-windows": "open the failing shard of the page oracle on the final seeds (windows) and fix its test; when it is skipped, fix the job that decides it",
|
||||
}
|
||||
E2E_CONDITIONAL = {
|
||||
# The base of the change is the one of the merge queue entry (`github.event.merge_group.base_sha`): the job runs there and nowhere else.
|
||||
"e2e-page-final-touched": ("merge_group",),
|
||||
}
|
||||
# A job that runs only when another job says so: job -> (the job that decides, its output, the value that makes it run). Otherwise it is `skipped`.
|
||||
E2E_BY_OUTPUT = {
|
||||
"e2e-page-final": ("e2e-page-final-touched", "touched", "true"),
|
||||
"e2e-page-final-windows": ("e2e-page-final-touched", "touched", "true"),
|
||||
}
|
||||
# What `workflow_dispatch` with `only: windows-control-a` skips on purpose: every job but the two that run it.
|
||||
E2E_NARROWED = tuple(sorted(set(E2E_FIX) - {"changes", "core-on-index", "e2e-windows-control-a"}))
|
||||
|
||||
# fakeweb.yml: every job runs on every event the workflow listens to.
|
||||
FAKEWEB_FIX = {
|
||||
"changes": _CHANGES,
|
||||
"core-on-index": _CORE,
|
||||
"linux-deps-fakeweb": "open the job linux-deps-fakeweb and fix the package list; when it is skipped, fix core-on-index first",
|
||||
"walk": "open the failing leg (`fakeweb p2` or `p4`, on linux or windows) and fix what differs from stock; when it is skipped, fix core-on-index first",
|
||||
}
|
||||
|
||||
# The workflows that start with the job `changes`, and the name of that job.
|
||||
CHANGES_JOB = "changes"
|
||||
HAS_CHANGES = ("e2e", "fakeweb")
|
||||
|
||||
# WORKFLOW -> (the name of the verdict job, its FIX table, its CONDITIONAL table).
|
||||
TABLES = {
|
||||
"tests": ("gate", FIX, CONDITIONAL),
|
||||
"e2e": ("e2e verdict", E2E_FIX, E2E_CONDITIONAL),
|
||||
"fakeweb": ("fakeweb verdict", FAKEWEB_FIX, {}),
|
||||
}
|
||||
|
||||
|
||||
def expected_result(name: str, needs: dict, event: str, workflow: str = "tests", only: str = "", changes_run: str = "true") -> str:
|
||||
"""`success`, or `skipped` for a job that is conditional by design on this event (or on this input, or on the output of another job, or because
|
||||
`changes` said there is nothing to test)."""
|
||||
conditional = TABLES[workflow][2]
|
||||
if workflow in HAS_CHANGES and name != CHANGES_JOB and changes_run == "false":
|
||||
return "skipped"
|
||||
if workflow == "e2e":
|
||||
if only == "windows-control-a" and name in E2E_NARROWED:
|
||||
return "skipped"
|
||||
if name in E2E_BY_OUTPUT:
|
||||
decider, output, value = E2E_BY_OUTPUT[name]
|
||||
entry = needs.get(decider)
|
||||
outputs = entry.get("outputs") if isinstance(entry, dict) else None
|
||||
ran = isinstance(outputs, dict) and outputs.get(output) == value
|
||||
return "success" if ran else "skipped"
|
||||
if name in conditional and event not in conditional[name]:
|
||||
return "skipped"
|
||||
return "success"
|
||||
|
||||
|
||||
def nothing_to_test(needs: dict, workflow: str) -> str:
|
||||
"""The last line of a verdict whose `changes` job said there is nothing to test."""
|
||||
entry = needs.get(CHANGES_JOB)
|
||||
outputs = entry.get("outputs") if isinstance(entry, dict) else None
|
||||
files = outputs.get("files") if isinstance(outputs, dict) else None
|
||||
count = files if isinstance(files, str) and files.isdigit() else "?"
|
||||
return "ok: nothing to test (%s files changed, none under the paths of %s)" % (count, workflow)
|
||||
|
||||
|
||||
def verdict(needs: dict, event: str, workflow: str = "tests", only: str = "", changes_run: "str | None" = None) -> list[str]:
|
||||
"""The FAIL lines for the results of `needs` (the object `toJSON(needs)` gives) of `workflow` on `event`; empty when every job is as expected.
|
||||
`changes_run` is the output `run` of the job `changes` (workflows that have one): `true` or `false`, anything else is red."""
|
||||
label, fix, _conditional = TABLES[workflow]
|
||||
out = []
|
||||
if workflow in HAS_CHANGES:
|
||||
if changes_run not in ("true", "false"):
|
||||
return ["FAIL %s: the output run of the job changes is %r, not true or false. Fix: pass CHANGES_RUN=${{ needs.changes.outputs.run }} and make the job changes print "
|
||||
"run=true|false. Rule: %s" % (label, "missing" if changes_run in (None, "") else changes_run, RULE)]
|
||||
else:
|
||||
changes_run = "true"
|
||||
for name in sorted(set(fix) | set(needs)):
|
||||
entry = needs.get(name)
|
||||
result = entry.get("result") if isinstance(entry, dict) else None
|
||||
if name not in fix:
|
||||
out.append(
|
||||
"FAIL %s: job %s is %s. Fix: add it to the table of %s in scripts/ci_gate.py, or take it out of `needs:` of the job %s. Rule: %s"
|
||||
% (label, name, result, workflow, label, RULE))
|
||||
elif result != expected_result(name, needs, event, workflow, only, changes_run):
|
||||
out.append("FAIL %s: job %s is %s. Fix: %s. Rule: %s" % (label, name, result or "missing", fix[name], RULE))
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
workflow = os.environ.get("WORKFLOW", "") or "tests"
|
||||
if workflow not in TABLES:
|
||||
print("FAIL gate: WORKFLOW is %r, not one of %s. Fix: pass WORKFLOW=tests, e2e or fakeweb. Rule: %s" % (workflow, "|".join(sorted(TABLES)), RULE))
|
||||
return 1
|
||||
label = TABLES[workflow][0]
|
||||
try:
|
||||
needs = json.loads(os.environ.get("NEEDS", ""))
|
||||
if not isinstance(needs, dict):
|
||||
raise ValueError("not an object")
|
||||
except ValueError as exc:
|
||||
print("FAIL %s: the results of the needed jobs cannot be read (%s). Fix: pass NEEDS=${{ toJSON(needs) }}. Rule: %s" % (label, exc, RULE))
|
||||
return 1
|
||||
event = os.environ.get("EVENT_NAME", "")
|
||||
for name in sorted(needs):
|
||||
entry = needs[name]
|
||||
print("%-24s %s" % (name + ":", entry.get("result") if isinstance(entry, dict) else entry))
|
||||
changes_run = os.environ.get("CHANGES_RUN")
|
||||
lines = verdict(needs, event, workflow, os.environ.get("INPUT_ONLY", ""), changes_run)
|
||||
for line in lines:
|
||||
print(line)
|
||||
if lines:
|
||||
return 1
|
||||
print(nothing_to_test(needs, workflow) if workflow in HAS_CHANGES and changes_run == "false" else "ok")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -29,6 +29,9 @@ import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
import ci_crash_evidence # noqa: E402 (the one reader of a dead process's arguments, shared with the oracles)
|
||||
|
||||
#: The folder under `$RUNNER_TEMP` the e2e workflows upload (`invpw-evidence-*`, "Keep what the tests saved").
|
||||
EVIDENCE_FOLDER = "invpw-evidence"
|
||||
CORES = "cores"
|
||||
@@ -51,6 +54,7 @@ GDB_COMMANDS = (
|
||||
"info sharedlibrary",
|
||||
"python print('\\n'.join('%s %s' % (o.filename, o.build_id) for o in gdb.objfiles()))",
|
||||
"info proc mappings",
|
||||
ci_crash_evidence.argv_gdb_command(), # which process it was: its arguments and the names of its environment
|
||||
)
|
||||
_HEADER = re.compile(r"Core was generated by `([^']*)'")
|
||||
#: The tests a phase of which failed: their teardown reads its cores too.
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""A test that is not e2e never leaves the machine: every connection, datagram and name lookup it makes goes to this host or is refused.
|
||||
|
||||
The markers say it already (pyproject.toml: ``unit`` is "no network", ``integration`` is "no network"), and nothing enforced it:
|
||||
``tests/unit/test_config_public.py`` composed the default prefs with no declared exit, the core asked api.ipify.org and icanhazip.com
|
||||
where it leaves from, and the test failed on a machine whose network refused them. A test cannot fail for the reasons of a third party.
|
||||
|
||||
:func:`install` patches the four doors of the standard library that every client in the process goes through (``socket.socket.connect``,
|
||||
``connect_ex`` and ``sendto``, and ``socket.getaddrinfo``): a destination on this host passes, anything else is refused with
|
||||
:class:`LeftTheMachine` (a ``ConnectionRefusedError``, so the code under test sees what an offline machine shows it) AND recorded, so the test
|
||||
fails at its teardown even when the code under test swallowed the refusal. The record names the test, the door and the destination.
|
||||
|
||||
asyncio has doors of its own, and on Windows they skip the four above: the Proactor loop connects with ``ConnectEx`` and sends datagrams with
|
||||
``WSASendTo`` (``_overlapped``), never through ``socket.socket``. So the guard also patches the loop methods every asyncio client goes through, for
|
||||
both loop kinds: ``BaseEventLoop.create_connection`` and ``create_datagram_endpoint`` (``remote_addr``), ``sock_connect`` and ``sock_sendto`` of the
|
||||
selector and of the Proactor loop, and the Proactor datagram transport's ``sendto``.
|
||||
|
||||
What it cannot see, on any system: a socket made from ``_socket`` directly or used through ``_overlapped`` by hand (no library of this project
|
||||
does), native code in the same process, and a child process (a subprocess has its own interpreter: the e2e are where a browser runs).
|
||||
|
||||
On this host: a loopback address (127/8, ::1), the unspecified address (0.0.0.0, ::, which a connect reaches on this host), a name that is
|
||||
``localhost`` or ends in ``.localhost``, and an AF_UNIX path. The documentation ranges (192.0.2/24, 198.51.100/24, 203.0.113/24, 2001:db8::/32)
|
||||
pass too: they are never routed, and the lab gives one of them to an interface of this host (the exit of the lab, tests/_lab_egress.py).
|
||||
And the address this host sends from (its default route's, tests/_host_address.py): a relay of the tests that leaves from the address of the
|
||||
host is on this host, and a datagram to it never leaves the machine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
import threading
|
||||
from typing import Any, List, Optional, Sequence, Tuple
|
||||
|
||||
_DOCUMENTATION = tuple(ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "2001:db8::/32"))
|
||||
|
||||
RULE = ("a test that is not e2e never leaves the machine (pyproject.toml markers: unit and integration are 'no network'): "
|
||||
"a test cannot fail for the reasons of a third party")
|
||||
FIX = ("declare the value the code would ask the network for (timezone=, locale=, proxy= with a local gateway), use a server of the tests "
|
||||
"on loopback (tests/_servers.py, the local_egress_echo fixture), or mark the test e2e if it is one")
|
||||
|
||||
|
||||
#: The ONE file whose job is to ask a third party, and the hosts it may ask. Nothing else is declared, and a new entry is a decision, not a fix.
|
||||
#: ``tests/test_version_is_not_taken.py`` is the version gate of a pull request: it asks the index whether the version the change proposes
|
||||
#: is already published, which only the index can answer. It is skipped unless ``IPW_CHECK_VERSION`` is set, which only the ``version`` job
|
||||
#: of tests.yml does. Its host is allowed for its name lookup and for the addresses that lookup answered, nothing else.
|
||||
DECLARED_THIRD_PARTIES = {
|
||||
"tests/test_version_is_not_taken.py": ("pypi.org",),
|
||||
}
|
||||
|
||||
|
||||
class LeftTheMachine(ConnectionRefusedError):
|
||||
"""A destination outside this host, refused by the guard of the tests."""
|
||||
|
||||
|
||||
def own_addresses() -> Tuple[str, ...]:
|
||||
"""The addresses this host sends from, IPv4 and IPv6 (the source its default route picks). A UDP connect sends no packet; a family with
|
||||
no route has none. Read BEFORE the doors are patched."""
|
||||
found = []
|
||||
for family, probe in ((socket.AF_INET, ("192.0.2.1", 9)), (socket.AF_INET6, ("2001:db8::1", 9))):
|
||||
try:
|
||||
with socket.socket(family, socket.SOCK_DGRAM) as s:
|
||||
s.connect(probe)
|
||||
found.append(s.getsockname()[0].split("%", 1)[0])
|
||||
except OSError:
|
||||
pass
|
||||
return tuple(found)
|
||||
|
||||
|
||||
def is_on_this_host(host: Any, own: Sequence[str] = ()) -> bool:
|
||||
"""Whether ``host`` (an address, a name, or None) is on this host, the way the guard decides it; ``own`` are the addresses of this host
|
||||
(:func:`own_addresses`)."""
|
||||
if host is None:
|
||||
return True
|
||||
if isinstance(host, bytes):
|
||||
host = host.decode("ascii", "replace")
|
||||
host = str(host).strip("[]").split("%", 1)[0]
|
||||
if host == "" or host.lower() == "localhost" or host.lower().endswith(".localhost"):
|
||||
return True
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return False # a name: resolving it is already a question to the network
|
||||
if getattr(address, "ipv4_mapped", None) is not None:
|
||||
address = address.ipv4_mapped
|
||||
return (address.is_loopback or address.is_unspecified or any(address in net for net in _DOCUMENTATION)
|
||||
or any(address == ipaddress.ip_address(mine) for mine in own))
|
||||
|
||||
|
||||
def _destination(address: Any, own: Sequence[str] = ()) -> Optional[str]:
|
||||
"""``host:port`` of a socket address that leaves the machine, or None when it does not (AF_UNIX paths and this host)."""
|
||||
if not isinstance(address, tuple) or not address:
|
||||
return None # an AF_UNIX path or an abstract name: this host
|
||||
host = address[0]
|
||||
if is_on_this_host(host, own):
|
||||
return None
|
||||
return "%s:%s" % (host, address[1] if len(address) > 1 else "?")
|
||||
|
||||
|
||||
class Guard:
|
||||
"""The record of one test: what it tried outside the machine. Thread-safe: a client thread of the test is recorded too."""
|
||||
|
||||
def __init__(self, test: str) -> None:
|
||||
self.test = test
|
||||
self.attempts: List[str] = []
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def refuse(self, door: str, destination: str) -> LeftTheMachine:
|
||||
sentence = "%s %s" % (door, destination)
|
||||
with self._lock:
|
||||
if sentence not in self.attempts:
|
||||
self.attempts.append(sentence)
|
||||
return LeftTheMachine("WHERE: %s. WHAT: %s, outside this host, refused. FIX: %s. RULE: %s." % (self.test, sentence, FIX, RULE))
|
||||
|
||||
def verdict(self) -> Optional[str]:
|
||||
"""The failure of the test, or None when it stayed on this host."""
|
||||
if not self.attempts:
|
||||
return None
|
||||
return ("WHERE: %s. WHAT: the test tried to leave the machine: %s (each was refused). FIX: %s. RULE: %s."
|
||||
% (self.test, "; ".join(self.attempts), FIX, RULE))
|
||||
|
||||
|
||||
def install(monkeypatch: Any, test: str) -> Guard:
|
||||
"""Patch the four doors for the duration of ``monkeypatch``; return the record of ``test``."""
|
||||
guard = Guard(test)
|
||||
declared_hosts = DECLARED_THIRD_PARTIES.get(test.split("::", 1)[0].replace("\\", "/"), ())
|
||||
answered = set() # the addresses a lookup of a declared host answered: a connection to them is that host
|
||||
own = tuple(own_addresses())
|
||||
|
||||
def mine():
|
||||
return own + tuple(answered)
|
||||
connect, connect_ex, sendto, getaddrinfo = (socket.socket.connect, socket.socket.connect_ex, socket.socket.sendto,
|
||||
socket.getaddrinfo)
|
||||
|
||||
def guarded_connect(self, address):
|
||||
where = _destination(address, mine())
|
||||
if where is not None:
|
||||
raise guard.refuse("connect to", where)
|
||||
return connect(self, address)
|
||||
|
||||
def guarded_connect_ex(self, address):
|
||||
where = _destination(address, mine())
|
||||
if where is not None:
|
||||
raise guard.refuse("connect to", where)
|
||||
return connect_ex(self, address)
|
||||
|
||||
def guarded_sendto(self, data, *rest):
|
||||
where = _destination(rest[-1] if rest else None, mine())
|
||||
if where is not None:
|
||||
raise guard.refuse("datagram to", where)
|
||||
return sendto(self, data, *rest)
|
||||
|
||||
def guarded_getaddrinfo(host, *args, **kwargs):
|
||||
if isinstance(host, str) and host.lower() in declared_hosts:
|
||||
found = getaddrinfo(host, *args, **kwargs)
|
||||
answered.update(info[4][0] for info in found)
|
||||
return found
|
||||
if not is_on_this_host(host, mine()):
|
||||
raise guard.refuse("name lookup of", str(host))
|
||||
return getaddrinfo(host, *args, **kwargs)
|
||||
|
||||
_install_asyncio(monkeypatch, guard, mine)
|
||||
monkeypatch.setattr(socket.socket, "connect", guarded_connect)
|
||||
monkeypatch.setattr(socket.socket, "connect_ex", guarded_connect_ex)
|
||||
monkeypatch.setattr(socket.socket, "sendto", guarded_sendto)
|
||||
monkeypatch.setattr(socket, "getaddrinfo", guarded_getaddrinfo)
|
||||
return guard
|
||||
|
||||
|
||||
def _install_asyncio(monkeypatch: Any, guard: Guard, mine: Any) -> None:
|
||||
"""The asyncio doors (module docstring), for the selector loop and, where it exists, the Proactor loop."""
|
||||
import asyncio.base_events as base_events
|
||||
import asyncio.selector_events as selector_events
|
||||
|
||||
loops = [selector_events.BaseSelectorEventLoop]
|
||||
datagram_transports = []
|
||||
try:
|
||||
import asyncio.proactor_events as proactor_events
|
||||
loops.append(proactor_events.BaseProactorEventLoop)
|
||||
datagram_transports.append(proactor_events._ProactorDatagramTransport)
|
||||
except ImportError: # pragma: no cover - the module exists on every system; its loop runs only on Windows
|
||||
pass
|
||||
|
||||
create_connection = base_events.BaseEventLoop.create_connection
|
||||
create_datagram_endpoint = base_events.BaseEventLoop.create_datagram_endpoint
|
||||
|
||||
async def guarded_create_connection(self, protocol_factory, host=None, port=None, *args, **kwargs):
|
||||
if host is not None and kwargs.get("sock") is None and not is_on_this_host(host, mine()):
|
||||
raise guard.refuse("asyncio connect to", "%s:%s" % (host, port))
|
||||
return await create_connection(self, protocol_factory, host, port, *args, **kwargs)
|
||||
|
||||
async def guarded_create_datagram_endpoint(self, protocol_factory, local_addr=None, remote_addr=None, **kwargs):
|
||||
where = _destination(remote_addr, mine())
|
||||
if where is not None:
|
||||
raise guard.refuse("asyncio datagram endpoint to", where)
|
||||
return await create_datagram_endpoint(self, protocol_factory, local_addr=local_addr, remote_addr=remote_addr, **kwargs)
|
||||
|
||||
monkeypatch.setattr(base_events.BaseEventLoop, "create_connection", guarded_create_connection)
|
||||
monkeypatch.setattr(base_events.BaseEventLoop, "create_datagram_endpoint", guarded_create_datagram_endpoint)
|
||||
|
||||
for loop in loops:
|
||||
sock_connect, sock_sendto = loop.sock_connect, loop.sock_sendto
|
||||
|
||||
def make(sock_connect=sock_connect, sock_sendto=sock_sendto):
|
||||
async def guarded_sock_connect(self, sock, address):
|
||||
where = _destination(address, mine())
|
||||
if where is not None:
|
||||
raise guard.refuse("asyncio connect to", where)
|
||||
return await sock_connect(self, sock, address)
|
||||
|
||||
async def guarded_sock_sendto(self, sock, data, address):
|
||||
where = _destination(address, mine())
|
||||
if where is not None:
|
||||
raise guard.refuse("asyncio datagram to", where)
|
||||
return await sock_sendto(self, sock, data, address)
|
||||
return guarded_sock_connect, guarded_sock_sendto
|
||||
|
||||
guarded_sock_connect, guarded_sock_sendto = make()
|
||||
monkeypatch.setattr(loop, "sock_connect", guarded_sock_connect)
|
||||
monkeypatch.setattr(loop, "sock_sendto", guarded_sock_sendto)
|
||||
|
||||
for transport in datagram_transports:
|
||||
def make_sendto(sendto=transport.sendto):
|
||||
def guarded_sendto(self, data, addr=None):
|
||||
where = _destination(addr, mine())
|
||||
if where is not None:
|
||||
raise guard.refuse("asyncio datagram to", where)
|
||||
return sendto(self, data, addr)
|
||||
return guarded_sendto
|
||||
monkeypatch.setattr(transport, "sendto", make_sendto())
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Where the operating system's own cursor is while a headed browser window is on the desktop the test runs on.
|
||||
|
||||
A real window that appears under the OS cursor receives a native ``WM_MOUSEMOVE`` for it, and the first native move of a process always passes Gecko's
|
||||
``LastMouseMoveData`` filter, so the page sees ``mousemove`` at the cursor's place with ``buttons=0``, at a moment the test does not choose. On a GitHub
|
||||
Windows runner the cursor sits at (512, 384) and the headed window covers (-8, -8) to (1928, 1040): the move reached the page once in the middle of a drag
|
||||
(``test_drag_motion.py::test_a_real_page_sees_a_drag_that_travelled`` saw ``mousemove 512,299 buttons=0`` after the press). The engine keeps delivering native
|
||||
input to content, so the arrangement is the test's: the cursor is parked on a point of the desktop that no window of the browser covers, before the browser
|
||||
starts, and a test that records pointer events checks it still is when its gesture begins.
|
||||
|
||||
* Windows: ``user32`` through ctypes. The windows are the visible top-level ones of the processes below the test process (the browsers it launched), seen from
|
||||
the desktop the test runs on: a ``headless=True`` browser runs on a Win32 desktop of its own (``make_virtual_display``), is not enumerated here and cannot
|
||||
receive the interactive cursor.
|
||||
* Linux and macOS: nothing to do. The Linux e2e run under ``xvfb-run``: an X server with virtual pointer and keyboard devices (XTEST) and no physical one,
|
||||
so nothing moves a pointer there; every function answers "outside" and ``park`` does nothing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import os
|
||||
import sys
|
||||
from typing import List, Optional, Sequence, Tuple
|
||||
|
||||
#: ``(left, top, right, bottom)`` as ``GetWindowRect`` gives it: ``right`` and ``bottom`` are the first pixel outside.
|
||||
Rect = Tuple[int, int, int, int]
|
||||
Point = Tuple[int, int]
|
||||
|
||||
#: How far from every window the parked cursor is, in pixels: a window is moved or grown by a border or a shadow, and the cursor must stay outside of it.
|
||||
MARGIN = 8
|
||||
|
||||
|
||||
class TheCursorIsInside(AssertionError):
|
||||
"""The OS cursor is over a window of the browser while a gesture is about to start."""
|
||||
|
||||
|
||||
class TheCursorCannotBeParked(RuntimeError):
|
||||
"""No point of the desktop is free of the browser's windows, or the system did not move the cursor."""
|
||||
|
||||
|
||||
def _inflate(rect: Rect, margin: int) -> Rect:
|
||||
return (rect[0] - margin, rect[1] - margin, rect[2] + margin, rect[3] + margin)
|
||||
|
||||
|
||||
def _contains(rect: Rect, point: Point) -> bool:
|
||||
return rect[0] <= point[0] < rect[2] and rect[1] <= point[1] < rect[3]
|
||||
|
||||
|
||||
def cursor_is_outside(window_rects: Sequence[Rect], cursor: Optional[Point] = None, margin: int = 0, *,
|
||||
api: Optional["_Win32"] = None) -> bool:
|
||||
"""True when ``cursor`` (read from the system when None) is outside every rectangle, ``margin`` pixels beyond its edge included.
|
||||
|
||||
Not Windows: True, there is no OS cursor that reaches a window."""
|
||||
if cursor is None:
|
||||
api = api or _api()
|
||||
if api is None:
|
||||
return True
|
||||
cursor = api.cursor_position()
|
||||
return not any(_contains(_inflate(r, margin), cursor) for r in window_rects)
|
||||
|
||||
|
||||
def park_outside(window_rects: Sequence[Rect], screen_rect: Rect, margin: int = MARGIN) -> Point:
|
||||
"""A pixel of the virtual screen that is at least ``margin`` pixels from every window rectangle: the bottom-right corner when it is free.
|
||||
|
||||
``screen_rect`` is ``(left, top, right, bottom)`` of the virtual screen, ``right`` and ``bottom`` exclusive (its origin is negative when a monitor lies left of or
|
||||
above the primary one). The candidates are the screen's edges and the places just beyond each window's inflated edges; a free pixel exists only if one
|
||||
of them is free (the free pixel can be slid left and up until it touches an edge, and it stays free), so a ``TheCursorCannotBeParked`` is exact."""
|
||||
left, top, right, bottom = screen_rect
|
||||
if right <= left or bottom <= top:
|
||||
raise TheCursorCannotBeParked(
|
||||
"park_outside: the virtual screen %r is empty. Where: the screen rectangle read from the system. What: no pixel to put the cursor on. "
|
||||
"Fix: run the e2e on an interactive desktop session." % (screen_rect,))
|
||||
inflated = [_inflate(r, margin) for r in window_rects]
|
||||
xs = sorted({right - 1, left, *(min(max(r[2], left), right - 1) for r in inflated), *(min(max(r[0] - 1, left), right - 1) for r in inflated)},
|
||||
reverse=True)
|
||||
ys = sorted({bottom - 1, top, *(min(max(r[3], top), bottom - 1) for r in inflated), *(min(max(r[1] - 1, top), bottom - 1) for r in inflated)},
|
||||
reverse=True)
|
||||
for y in ys:
|
||||
for x in xs:
|
||||
if not any(_contains(r, (x, y)) for r in inflated):
|
||||
return (x, y)
|
||||
raise TheCursorCannotBeParked(
|
||||
"park_outside: the windows %r cover every pixel of the screen %r with a margin of %d. Where: the headed browser window the test launched. What: the "
|
||||
"OS cursor would be over the page whatever the point, and a native mouse move would reach it. Fix: shrink the window below the screen (the test's own "
|
||||
"geometry; it is not this helper's to change) or run the test on a bigger desktop." % (list(window_rects), screen_rect, margin))
|
||||
|
||||
|
||||
class _Win32:
|
||||
"""What the desktop answers, by ``user32``. One object so a test can stand a fake in for it."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
from ctypes import wintypes
|
||||
|
||||
self.wintypes = wintypes
|
||||
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
u = self.user32
|
||||
u.GetCursorPos.argtypes = (ctypes.POINTER(wintypes.POINT),)
|
||||
u.GetCursorPos.restype = wintypes.BOOL
|
||||
u.SetCursorPos.argtypes = (ctypes.c_int, ctypes.c_int)
|
||||
u.SetCursorPos.restype = wintypes.BOOL
|
||||
u.GetSystemMetrics.argtypes = (ctypes.c_int,)
|
||||
u.GetSystemMetrics.restype = ctypes.c_int
|
||||
u.GetWindowRect.argtypes = (wintypes.HWND, ctypes.POINTER(wintypes.RECT))
|
||||
u.GetWindowRect.restype = wintypes.BOOL
|
||||
u.IsWindowVisible.argtypes = (wintypes.HWND,)
|
||||
u.IsWindowVisible.restype = wintypes.BOOL
|
||||
u.IsIconic.argtypes = (wintypes.HWND,)
|
||||
u.IsIconic.restype = wintypes.BOOL
|
||||
u.GetWindowThreadProcessId.argtypes = (wintypes.HWND, ctypes.POINTER(wintypes.DWORD))
|
||||
u.GetWindowThreadProcessId.restype = wintypes.DWORD
|
||||
self.enum_proc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
u.EnumWindows.argtypes = (self.enum_proc, wintypes.LPARAM)
|
||||
u.EnumWindows.restype = wintypes.BOOL
|
||||
|
||||
def cursor_position(self) -> Point:
|
||||
point = self.wintypes.POINT()
|
||||
if not self.user32.GetCursorPos(ctypes.byref(point)):
|
||||
raise TheCursorCannotBeParked(
|
||||
"GetCursorPos failed (error %d). Where: user32, on the desktop the test runs on. What: the OS cursor cannot be read. Fix: run the e2e on an "
|
||||
"interactive desktop session (not a locked screen or a service)." % ctypes.get_last_error())
|
||||
return (point.x, point.y)
|
||||
|
||||
def set_cursor_position(self, x: int, y: int) -> None:
|
||||
self.user32.SetCursorPos(x, y)
|
||||
|
||||
def screen(self) -> Rect:
|
||||
"""The virtual screen: ``SM_XVIRTUALSCREEN``, ``SM_YVIRTUALSCREEN``, ``SM_CXVIRTUALSCREEN``, ``SM_CYVIRTUALSCREEN``."""
|
||||
x, y, w, h = (self.user32.GetSystemMetrics(n) for n in (76, 77, 78, 79))
|
||||
return (x, y, x + w, y + h)
|
||||
|
||||
def windows_below(self, root_pid: int) -> List[Rect]:
|
||||
"""The rectangles of the visible, not minimised, top-level windows of the processes below ``root_pid``."""
|
||||
import psutil
|
||||
|
||||
try:
|
||||
pids = {p.pid for p in psutil.Process(root_pid).children(recursive=True)}
|
||||
except psutil.Error:
|
||||
return []
|
||||
found: List[Rect] = []
|
||||
|
||||
def each(hwnd, _):
|
||||
owner = self.wintypes.DWORD()
|
||||
self.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
|
||||
if owner.value in pids and self.user32.IsWindowVisible(hwnd) and not self.user32.IsIconic(hwnd):
|
||||
rect = self.wintypes.RECT()
|
||||
if self.user32.GetWindowRect(hwnd, ctypes.byref(rect)) and rect.right > rect.left and rect.bottom > rect.top:
|
||||
found.append((rect.left, rect.top, rect.right, rect.bottom))
|
||||
return True
|
||||
|
||||
self.user32.EnumWindows(self.enum_proc(each), 0)
|
||||
return found
|
||||
|
||||
|
||||
def _is_windows() -> bool:
|
||||
return sys.platform == "win32"
|
||||
|
||||
|
||||
def _api() -> Optional[_Win32]:
|
||||
return _Win32() if _is_windows() else None
|
||||
|
||||
|
||||
def browser_windows(root_pid: Optional[int] = None, *, api: Optional[_Win32] = None) -> List[Rect]:
|
||||
"""The rectangles of the windows of the browsers below ``root_pid`` (the test process by default) on this desktop; empty when not Windows."""
|
||||
api = api or _api()
|
||||
if api is None:
|
||||
return []
|
||||
return api.windows_below(os.getpid() if root_pid is None else root_pid)
|
||||
|
||||
|
||||
def park(root_pid: Optional[int] = None, *, api: Optional[_Win32] = None) -> Optional[Point]:
|
||||
"""Windows: put the OS cursor on a point no window of the browsers below ``root_pid`` covers and read it back. Returns the point; None when not Windows.
|
||||
|
||||
Called before the browser starts there is no window yet and the point is the bottom-right corner of the virtual screen, where the engine places no window."""
|
||||
api = api or _api()
|
||||
if api is None:
|
||||
return None
|
||||
target = park_outside(api.windows_below(os.getpid() if root_pid is None else root_pid), api.screen())
|
||||
api.set_cursor_position(*target)
|
||||
read_back = api.cursor_position()
|
||||
if read_back != target:
|
||||
raise TheCursorCannotBeParked(
|
||||
"SetCursorPos(%d, %d) left the cursor at %r. Where: user32, on the desktop the test runs on. What: the OS cursor cannot be moved, so a native "
|
||||
"mouse move for it can reach a window of the browser mid-gesture. Fix: run the e2e on an interactive desktop session (not a locked screen "
|
||||
"or a service), with no other program holding the cursor." % (target[0], target[1], read_back))
|
||||
return target
|
||||
|
||||
|
||||
def require_outside(root_pid: Optional[int] = None, *, api: Optional[_Win32] = None, margin: int = 0) -> None:
|
||||
"""The precondition of a gesture a test judges by the pointer events the page records: the OS cursor is outside every window of the browsers.
|
||||
|
||||
Raises ``TheCursorIsInside`` otherwise, with the cursor and the windows. Not Windows: nothing."""
|
||||
api = api or _api()
|
||||
if api is None:
|
||||
return
|
||||
windows = api.windows_below(os.getpid() if root_pid is None else root_pid)
|
||||
cursor = api.cursor_position()
|
||||
if not cursor_is_outside(windows, cursor, margin):
|
||||
raise TheCursorIsInside(
|
||||
"the OS cursor is at %r, inside the browser window(s) %r, when a pointer gesture is about to start. Where: the desktop the test runs on. What: "
|
||||
"a native WM_MOUSEMOVE for it passes Gecko's first-move filter and reaches the page as a mousemove with buttons=0 at a moment of the "
|
||||
"system's choosing, in the middle of the gesture the test records. Fix: park the cursor outside the window before the browser starts "
|
||||
"(the autouse fixture `_the_os_cursor_is_outside_the_browser_window` of tests/conftest.py does it for every e2e test on Windows)." % (cursor, windows))
|
||||
+70
-6
@@ -93,6 +93,15 @@ def _attrs(data: bytes) -> Dict[int, bytes]:
|
||||
return out
|
||||
|
||||
|
||||
def is_deallocation(data: bytes) -> bool:
|
||||
"""Whether a datagram is a TURN deallocation, by what it means (RFC 5766 section 7.1): a STUN Refresh (0x0004) whose LIFETIME (0x000D) is 0. A Refresh with a lifetime above 0, with
|
||||
none, or any other message type, is not one. The one reading of it: the TURN server of the lab and the gateway of the lab both use it."""
|
||||
if len(data) < 20 or struct.unpack("!I", data[4:8])[0] != MAGIC or struct.unpack("!H", data[:2])[0] != 0x0004:
|
||||
return False
|
||||
lifetime = _attrs(data).get(0x000D)
|
||||
return lifetime is not None and len(lifetime) == 4 and struct.unpack("!I", lifetime)[0] == 0
|
||||
|
||||
|
||||
def _attr(t: int, v: bytes) -> bytes:
|
||||
return struct.pack("!HH", t, len(v)) + v + b"\x00" * (-len(v) % 4)
|
||||
|
||||
@@ -111,11 +120,39 @@ def _message(mtype: int, tid: bytes, attrs: bytes, key: Optional[bytes] = None)
|
||||
return head + attrs + _attr(0x0008, mac)
|
||||
|
||||
|
||||
def long_term_key(user: str) -> bytes:
|
||||
"""The long-term credential key of RFC 5389 section 15.4: md5(username:realm:password)."""
|
||||
return hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
|
||||
|
||||
def integrity_valid(data: bytes, user: str) -> bool:
|
||||
"""Whether the MESSAGE-INTEGRITY of a request is the HMAC-SHA1 under the long-term key of ``user`` (RFC 5389 section 15.4): over the message up to the
|
||||
attribute, with the length field of the header set as if the message ended with that attribute (24 bytes more than what came before it). A request
|
||||
with no MESSAGE-INTEGRITY, or a truncated one, is not valid."""
|
||||
i = 20
|
||||
while i + 4 <= len(data):
|
||||
t, n = struct.unpack("!HH", data[i:i + 4])
|
||||
if t == 0x0008:
|
||||
if n != 20 or i + 24 > len(data):
|
||||
return False
|
||||
head = data[:2] + struct.pack("!H", i + 24 - 20) + data[4:20]
|
||||
return hmac.compare_digest(hmac.new(long_term_key(user), head + data[20:i], hashlib.sha1).digest(), data[i + 4:i + 24])
|
||||
i += 4 + ((n + 3) & ~3)
|
||||
return False
|
||||
|
||||
|
||||
class TurnServer:
|
||||
"""UDP TURN server on 127.0.0.1. ``seen`` is every datagram as (source ip, source port, STUN type), in order;
|
||||
``requests`` the same datagrams as (monotonic time, transaction id, STUN type, carries credentials): a retransmission has the
|
||||
transaction id of the request it repeats, so the TRANSACTIONS of a road are the distinct ids (:meth:`transactions`);
|
||||
``allocations`` the successful Allocates as (source ip, source port, username, time)."""
|
||||
``allocations`` the successful Allocates as (source ip, source port, username, time); ``deallocations`` the requests that END an allocation as (source ip, source
|
||||
port, transaction id, time, index in ``allocations`` of the allocation they end, or None when that source has none): a deallocation is recognised by what it means, a
|
||||
Refresh (0x0004) whose LIFETIME (0x000D) is 0 (RFC 5766 section 7.1), not by its type: a Refresh with a lifetime above 0 keeps the allocation and is not one. The server
|
||||
answers it as it answers any Refresh; a retransmission is another datagram of the same transaction (:meth:`deallocation_transactions`).
|
||||
|
||||
A request that carries USERNAME is checked: its MESSAGE-INTEGRITY must be the HMAC under the long-term key of that user (``PASSWORD``).
|
||||
A missing or wrong one is answered 401 with the realm and the nonce, makes no allocation, and is written in ``refused`` as
|
||||
(source ip, source port, username, transaction id, time): a client with the wrong password never gets a relay here, as on a real server."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
@@ -124,6 +161,8 @@ class TurnServer:
|
||||
self.seen: List[Tuple[str, int, int]] = []
|
||||
self.allocations: List[Tuple[str, int, str, float]] = []
|
||||
self.requests: List[Tuple[float, bytes, int, bool]] = []
|
||||
self.deallocations: List[Tuple[str, int, bytes, float, Optional[int]]] = []
|
||||
self.refused: List[Tuple[str, int, str, bytes, float]] = []
|
||||
self._closed = False
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
@@ -135,6 +174,17 @@ class TurnServer:
|
||||
first.setdefault(request[1], request)
|
||||
return sorted(first.values(), key=lambda r: r[0])
|
||||
|
||||
def deallocation_transactions(self) -> List[Tuple[str, int, bytes, float, Optional[int]]]:
|
||||
"""The first datagram of each deallocation transaction, in order: a retransmission of it is not another deallocation."""
|
||||
first: Dict[bytes, Tuple[str, int, bytes, float, Optional[int]]] = {}
|
||||
for record in list(self.deallocations):
|
||||
first.setdefault(record[2], record)
|
||||
return sorted(first.values(), key=lambda r: r[3])
|
||||
|
||||
def deallocation_tids(self) -> set:
|
||||
"""The transaction ids (bytes) of every deallocation received: what ties its datagrams on the wire to the server's record of it."""
|
||||
return {record[2] for record in list(self.deallocations)}
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
self.sock.close()
|
||||
@@ -148,26 +198,40 @@ class TurnServer:
|
||||
if len(data) < 20 or struct.unpack("!I", data[4:8])[0] != MAGIC:
|
||||
continue
|
||||
mtype, tid = struct.unpack("!H", data[:2])[0], data[8:20]
|
||||
self.seen.append((src[0], src[1], mtype))
|
||||
attrs = _attrs(data)
|
||||
if is_deallocation(data): # recorded BEFORE the request: whoever reads `requests` already knows which of them it ended
|
||||
held = [i for i, a in enumerate(self.allocations) if a[:2] == (src[0], src[1])]
|
||||
self.deallocations.append((src[0], src[1], tid, time.monotonic(), held[-1] if held else None))
|
||||
self.seen.append((src[0], src[1], mtype))
|
||||
self.requests.append((time.monotonic(), tid, mtype, 0x0008 in attrs and 0x0006 in attrs))
|
||||
user_raw = attrs.get(0x0006)
|
||||
if mtype in (0x0003, 0x0004, 0x0008, 0x0009) and user_raw is not None:
|
||||
user = user_raw.decode(errors="replace")
|
||||
if not integrity_valid(data, user): # the wrong password, or no MESSAGE-INTEGRITY: 401, no allocation
|
||||
self.refused.append((src[0], src[1], user, tid, time.monotonic()))
|
||||
self.sock.sendto(_message(mtype | 0x0110, tid, self._unauthorized()), src)
|
||||
continue
|
||||
if mtype == 0x0003: # Allocate
|
||||
if 0x0008 not in attrs or 0x0006 not in attrs: # no credentials: 401 with a realm and a nonce
|
||||
err = _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
|
||||
self.sock.sendto(_message(0x0113, tid, err), src)
|
||||
self.sock.sendto(_message(0x0113, tid, self._unauthorized()), src)
|
||||
continue
|
||||
user = attrs[0x0006].decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
key = long_term_key(user)
|
||||
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
|
||||
_attr(0x000D, struct.pack("!I", 600)))
|
||||
self.allocations.append((src[0], src[1], user, time.monotonic()))
|
||||
self.sock.sendto(_message(0x0103, tid, body, key), src)
|
||||
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
|
||||
user = attrs.get(0x0006, b"").decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
key = long_term_key(user)
|
||||
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
|
||||
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
|
||||
|
||||
@staticmethod
|
||||
def _unauthorized() -> bytes:
|
||||
"""The attributes of a 401: ERROR-CODE, the realm and the nonce of the long-term credential."""
|
||||
return _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
|
||||
|
||||
|
||||
# ── the gateway ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -177,6 +177,22 @@ def _offline_session_geo(request, monkeypatch):
|
||||
monkeypatch.setattr(_session, "session_geo", lambda *_a, **_k: geo)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _a_test_that_is_not_e2e_never_leaves_the_machine(request, monkeypatch):
|
||||
"""Outside the e2e, every connection, datagram and name lookup goes to this host or is refused, and the test fails naming each
|
||||
destination it tried (tests/_no_network.py), even when the code under test swallowed the refusal."""
|
||||
if request.node.get_closest_marker("e2e") is not None:
|
||||
yield
|
||||
return
|
||||
import _no_network
|
||||
|
||||
guard = _no_network.install(monkeypatch, request.node.nodeid)
|
||||
yield
|
||||
failure = guard.verdict()
|
||||
if failure:
|
||||
pytest.fail(failure, pytrace=False)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _what_the_core_declares_for_a_proxy_is_recorded(monkeypatch):
|
||||
"""The core keeps no UDP verdict in memory, so a test that wants to know what the launch declared reads it where it is
|
||||
@@ -254,6 +270,64 @@ def _no_test_asks_the_world_where_it_leaves_from():
|
||||
pytest.fail("the question of the exit went toward the internet: " + "; ".join(asked), pytrace=False)
|
||||
|
||||
|
||||
def _park_the_os_cursor():
|
||||
"""Windows: the OS cursor goes where no window of the browsers below the test process covers (the bottom-right corner while none is open), read back."""
|
||||
if sys.platform == "win32":
|
||||
import _os_cursor
|
||||
|
||||
_os_cursor.park()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def _the_os_cursor_is_outside_the_browser_window_of_a_module(request):
|
||||
"""A browser a module-scoped fixture starts opens its window before any test of the module runs: the cursor is parked before that, once per module that has an
|
||||
e2e test (``tests/_os_cursor.py``; Windows only, the Linux e2e run under xvfb-run whose pointer is virtual)."""
|
||||
if sys.platform == "win32" and any(getattr(item, "module", None) is request.module and item.get_closest_marker("e2e") is not None
|
||||
for item in request.session.items):
|
||||
_park_the_os_cursor()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _the_os_cursor_is_outside_the_browser_window(request):
|
||||
"""A headed window that opens under the real cursor gets a native mouse move for it (the runner's cursor is at 512,384, inside the window), and the first
|
||||
native move of a process passes Gecko's filter: the page sees a ``mousemove`` with ``buttons=0`` in the middle of the gesture a test records. Every e2e
|
||||
test on Windows starts with the cursor parked outside the window the engine opens, before its browser starts. A ``headless=True`` browser runs on a desktop of
|
||||
its own and never receives it; the parking is the same for it and costs one system call. The gestures that record pointer events then call
|
||||
``_os_cursor.require_outside()`` at their start."""
|
||||
if request.node.get_closest_marker("e2e") is not None:
|
||||
_park_the_os_cursor()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def lab_exit(monkeypatch, tmp_path):
|
||||
"""The exit of the lab and its GeoIP database, declared for one test that is not e2e (``tests/_lab_egress.py``, as the e2e have it).
|
||||
|
||||
With no proxy the core asks where this machine leaves from once per composition (``prepare_session_geo``: zone, language and position
|
||||
come from the exit, even when the zone is given), and a test that is not e2e never leaves the machine (``tests/_no_network.py``). A test
|
||||
that composes prefs or a session through the core takes this fixture."""
|
||||
import _lab_egress
|
||||
|
||||
return _lab_egress.install(monkeypatch, tmp_path / "lab-geoip")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def declared_engine(monkeypatch, tmp_path):
|
||||
"""An engine executable declared for one test that is not e2e, instead of the one the core resolves.
|
||||
|
||||
Without ``binary_path=`` the launch resolves the engine through ``ensure_binary`` (``_engine.resolve_executable``): with an engine in
|
||||
the cache of the machine it answers at once, and with none it asks GitHub's release index and downloads the archive. So a unit test that
|
||||
composes a launch passed on a machine that had run ``fetch`` and went to the internet on a fresh runner, and a test that is not e2e
|
||||
never leaves the machine (``tests/_no_network.py``). The file is never run: the tests that take this fixture stop at the environment,
|
||||
the arguments or a fake ``launch``. Returns its path."""
|
||||
from invisible_playwright import _engine
|
||||
|
||||
executable = tmp_path / "declared-engine" / ("firefox.exe" if sys.platform == "win32" else "firefox")
|
||||
executable.parent.mkdir(parents=True)
|
||||
executable.write_bytes(b"")
|
||||
monkeypatch.setattr(_engine, "ensure_binary", lambda *a, **k: executable)
|
||||
return executable
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def local_egress_echo(monkeypatch):
|
||||
"""The REAL discovery of the exit, for the test that must prove it, against an echo service of its own on loopback: the three services of the
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
{"file": "test_a_popup_of_a_link_reaches_the_client_e2e.py", "scope": "_router.route", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py", "scope": "<module>._PROBE_JS", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "scope": "<module>.TURN_PORT", "rule": "port", "nth": 1, "kind": "virtual-port", "reason": "A port number that nothing binds: the gateway of the test answers for the name or address by itself, so no worker can collide on it."},
|
||||
{"file": "test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "scope": "_go_back_and_record", "rule": "sleep", "nth": 1, "kind": "instrument", "reason": "Runs only after go_back has already raised: the pause dates a restore that lands after the wait, for the evidence of the red run; the error is raised unchanged and the pause decides nothing."},
|
||||
{"file": "test_caller_world_handles_e2e.py", "scope": "test_a_node_that_appears_later_ends_the_wait", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_caller_world_handles_e2e.py", "scope": "test_a_wait_for_function_object_handle_reads_in_the_page_world", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_declared_host_network_e2e.py", "scope": "<module>._GATHER_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s is the deadline of the wait for the end of the ICE gathering: the wait ends when the page says `complete`, a gathering that never completes returns what it has and fails the assertions on the candidates, and no verdict reads when the timer fired."},
|
||||
|
||||
@@ -1,384 +0,0 @@
|
||||
"""A docs-only change runs nothing heavy in the merge queue, and "nothing to test" is an explicit success the verdict knows.
|
||||
|
||||
GitHub applies no `paths` filter to a merge queue run (`merge_group`), so e2e.yml and fakeweb.yml would run in full for a change to a Markdown file. Both
|
||||
workflows now start with the job `changes` (scripts/ci_changes.py): in a queue run it lists the files between `github.event.merge_group.base_sha` and
|
||||
`head_sha` and applies the path rules the `push` trigger of the same workflow has (e2e: `paths-ignore` of `**.md`, `docs/**`, `LICENSE`; fakeweb: its
|
||||
`paths`); on push and workflow_dispatch it always says run=true. Every other job needs `changes` and runs only on `needs.changes.outputs.run == 'true'`.
|
||||
|
||||
That is NOT a skip the verdict waves through: scripts/ci_gate.py gets the output as CHANGES_RUN, and
|
||||
|
||||
* run=false: `changes` is success, every other job is `skipped` (one that ran anyway is red), and the verdict ends with
|
||||
`ok: nothing to test (<n> files changed, none under the paths of <workflow>)`;
|
||||
* run=true: every job is `success`, a skipped one is red;
|
||||
* a CHANGES_RUN that is missing or is not true or false is red, and so is a `changes` job that did not succeed.
|
||||
|
||||
Known-bad inputs: a heavy job that ran when there was nothing to test, a heavy job skipped when there was something to test, no output at all.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WORKFLOWS = ROOT / ".github" / "workflows"
|
||||
|
||||
|
||||
def _load(name: str):
|
||||
spec = importlib.util.spec_from_file_location(name + "_for_changes", ROOT / "scripts" / (name + ".py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
ci_changes = _load("ci_changes")
|
||||
ci_gate = _load("ci_gate")
|
||||
CHANGES = ROOT / "scripts" / "ci_changes.py"
|
||||
GATE = ROOT / "scripts" / "ci_gate.py"
|
||||
HEAVY = ("e2e", "fakeweb")
|
||||
RULE = "Rule: ci-13 nothing counts as passed that did not pass"
|
||||
|
||||
# ------------------------------------------------------------------------------ the path rules
|
||||
|
||||
|
||||
@pytest.mark.parametrize("files", [
|
||||
["README.md"],
|
||||
["docs/ARCHITECTURE.md"],
|
||||
["docs/diagram.png"],
|
||||
["docs/deep/er/file.txt"],
|
||||
["LICENSE"],
|
||||
["src/invisible_playwright/NOTES.md"],
|
||||
["README.md", "docs/a.png", "LICENSE"],
|
||||
])
|
||||
def test_a_docs_only_change_gives_run_false_for_both_workflows(files):
|
||||
assert ci_changes.should_run("e2e", files) is False
|
||||
assert ci_changes.should_run("fakeweb", files) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("files", [
|
||||
["src/invisible_playwright/launcher.py"],
|
||||
["tests/test_a_launch_has_one_deadline.py"],
|
||||
["README.md", "src/invisible_playwright/launcher.py"],
|
||||
["docs/a.md", "tests/test_something_e2e.py"],
|
||||
["pyproject.toml"],
|
||||
["scripts/ci_gate.py"],
|
||||
[".github/workflows/e2e.yml"],
|
||||
["LICENSE.txt"],
|
||||
])
|
||||
def test_a_change_to_a_test_or_to_src_gives_run_true_for_e2e(files):
|
||||
assert ci_changes.should_run("e2e", files) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [
|
||||
"tests/fakeweb/pages.json",
|
||||
"tests/fakeweb/deep/er/site.py",
|
||||
"tests/test_fakeweb_p4_report.py",
|
||||
"tests/test_fakeweb_p2_e2e.py",
|
||||
"scripts/run_fakeweb.py",
|
||||
"scripts/fakeweb_p4_report.py",
|
||||
"scripts/playwright_pin.txt",
|
||||
".github/workflows/fakeweb.yml",
|
||||
])
|
||||
def test_a_fake_web_file_gives_run_true_for_fakeweb(path):
|
||||
assert ci_changes.should_run("fakeweb", [path]) is True
|
||||
assert ci_changes.should_run("fakeweb", ["docs/a.md", path]) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [
|
||||
"src/invisible_playwright/launcher.py",
|
||||
"tests/test_a_launch_has_one_deadline.py",
|
||||
"tests/fakewebs/other.py",
|
||||
"tests/sub/test_fakeweb_x.py",
|
||||
"scripts/run_fakeweb.pyc",
|
||||
"README.md",
|
||||
])
|
||||
def test_a_file_that_is_not_the_fake_web_gives_run_false_for_fakeweb(path):
|
||||
assert ci_changes.should_run("fakeweb", [path]) is False
|
||||
|
||||
|
||||
def test_a_change_that_lists_no_file_runs_because_it_cannot_be_told_from_a_broken_diff():
|
||||
assert ci_changes.should_run("e2e", []) is True
|
||||
assert ci_changes.should_run("fakeweb", []) is True
|
||||
|
||||
|
||||
def test_an_unknown_workflow_is_an_error():
|
||||
with pytest.raises(ValueError):
|
||||
ci_changes.should_run("tests", ["README.md"])
|
||||
|
||||
|
||||
def _push_block(workflow_file: str) -> str:
|
||||
text = (WORKFLOWS / workflow_file).read_text(encoding="utf-8")
|
||||
on = re.search(r"^on:\s*\n(.*?)(?=^\S)", text, re.M | re.S).group(1)
|
||||
code = "\n".join(line for line in on.splitlines() if not line.lstrip().startswith("#"))
|
||||
return re.search(r"^ push:\s*\n(.*?)(?=^ \S|\Z)", code + "\n", re.M | re.S).group(1)
|
||||
|
||||
|
||||
def test_the_tables_are_the_path_filters_of_the_push_triggers():
|
||||
ignore = re.findall(r"- '([^']+)'", _push_block("e2e.yml").split("paths-ignore:", 1)[1])
|
||||
assert tuple(ignore) == ci_changes.IGNORE["e2e"]
|
||||
only = re.findall(r"- '([^']+)'", _push_block("fakeweb.yml").split("paths:", 1)[1])
|
||||
assert tuple(only) == ci_changes.ONLY["fakeweb"]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ the script on events and on a real diff
|
||||
|
||||
|
||||
def _changes(*args: str, cwd=ROOT) -> subprocess.CompletedProcess:
|
||||
return subprocess.run([sys.executable, str(CHANGES), *args], cwd=str(cwd), capture_output=True, text=True, timeout=60)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", ["push", "workflow_dispatch", "schedule", ""])
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
def test_a_push_and_a_dispatch_always_run(workflow, event):
|
||||
done = _changes(workflow, event)
|
||||
assert done.returncode == 0 and done.stdout.splitlines() == ["run=true", "files=0"], (done.stdout, done.stderr)
|
||||
|
||||
|
||||
def test_a_queue_run_without_its_commits_is_an_error():
|
||||
assert _changes("e2e", "merge_group").returncode == 2
|
||||
assert _changes("e2e", "merge_group", "", "").returncode == 2
|
||||
assert _changes("nope", "push").returncode == 2
|
||||
|
||||
|
||||
def _git(cwd, *args: str) -> str:
|
||||
done = subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@users.noreply.github.com", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=str(cwd), capture_output=True, text=True, timeout=60, check=True)
|
||||
return done.stdout.strip()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def repo(tmp_path):
|
||||
_git(tmp_path, "init", "-q")
|
||||
(tmp_path / "src").mkdir()
|
||||
(tmp_path / "docs").mkdir()
|
||||
(tmp_path / "src" / "a.py").write_text("a = 1\n")
|
||||
(tmp_path / "README.md").write_text("one\n")
|
||||
_git(tmp_path, "add", "-A")
|
||||
_git(tmp_path, "commit", "-q", "-m", "base")
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _entry(repo, files: dict) -> tuple:
|
||||
base = _git(repo, "rev-parse", "HEAD")
|
||||
for name, text in files.items():
|
||||
path = repo / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
_git(repo, "add", "-A")
|
||||
_git(repo, "commit", "-q", "-m", "change")
|
||||
return base, _git(repo, "rev-parse", "HEAD")
|
||||
|
||||
|
||||
def test_a_queue_entry_that_changes_only_markdown_says_run_false_and_the_count(repo):
|
||||
base, head = _entry(repo, {"README.md": "two\n", "docs/new.md": "x\n", "docs/pic.png": "y\n"})
|
||||
for workflow in HEAVY:
|
||||
done = _changes(workflow, "merge_group", base, head, cwd=repo)
|
||||
assert done.returncode == 0 and done.stdout.splitlines() == ["run=false", "files=3"], (workflow, done.stdout, done.stderr)
|
||||
|
||||
|
||||
def test_a_queue_entry_that_changes_src_says_run_true_for_e2e_and_false_for_fakeweb(repo):
|
||||
base, head = _entry(repo, {"src/a.py": "a = 2\n"})
|
||||
assert _changes("e2e", "merge_group", base, head, cwd=repo).stdout.splitlines() == ["run=true", "files=1"]
|
||||
assert _changes("fakeweb", "merge_group", base, head, cwd=repo).stdout.splitlines() == ["run=false", "files=1"]
|
||||
|
||||
|
||||
def test_a_queue_entry_that_changes_a_fake_web_file_says_run_true_for_fakeweb(repo):
|
||||
base, head = _entry(repo, {"tests/fakeweb/pages.json": "{}\n"})
|
||||
assert _changes("fakeweb", "merge_group", base, head, cwd=repo).stdout.splitlines() == ["run=true", "files=1"]
|
||||
|
||||
|
||||
def test_a_commit_that_cannot_be_listed_fails_the_job_instead_of_guessing(repo):
|
||||
done = _changes("e2e", "merge_group", "0" * 40, "1" * 40, cwd=repo)
|
||||
assert done.returncode != 0 and "run=" not in done.stdout
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ the workflows
|
||||
|
||||
|
||||
def _text(name: str) -> str:
|
||||
return (WORKFLOWS / name).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _jobs(text: str) -> dict:
|
||||
body = text.split("\njobs:\n", 1)[1]
|
||||
ids = list(re.finditer(r"^ ([A-Za-z0-9_-]+):\s*$", body, re.M))
|
||||
return {m.group(1): body[m.end(): ids[i + 1].start() if i + 1 < len(ids) else len(body)] for i, m in enumerate(ids)}
|
||||
|
||||
|
||||
def _needs(job_text: str) -> list:
|
||||
flow = re.search(r"^ needs: \[([^\]]*)\]\s*$", job_text, re.M)
|
||||
if flow:
|
||||
return [n.strip() for n in flow.group(1).split(",") if n.strip()]
|
||||
one = re.search(r"^ needs: ([A-Za-z0-9_-]+)\s*$", job_text, re.M)
|
||||
return [one.group(1)] if one else []
|
||||
|
||||
|
||||
def problems_changes(name: str, text: str) -> list:
|
||||
workflow = name.split(".")[0]
|
||||
out = []
|
||||
jobs = _jobs(text)
|
||||
if list(jobs)[0:1] != ["changes"]:
|
||||
return ["%s: the first job is not `changes`: %s" % (name, list(jobs)[:1])]
|
||||
body = jobs["changes"]
|
||||
if _needs(body):
|
||||
out.append("%s: `changes` needs %s: it must be the first job and wait for nothing" % (name, _needs(body)))
|
||||
if not re.search(r"^ run: \$\{\{ steps\.changes\.outputs\.run \}\}\s*$", body, re.M):
|
||||
out.append("%s: `changes` has no output `run`" % name)
|
||||
if not re.search(r"^ files: \$\{\{ steps\.changes\.outputs\.files \}\}\s*$", body, re.M):
|
||||
out.append("%s: `changes` has no output `files`" % name)
|
||||
if 'git show origin/main:scripts/ci_changes.py > "$RUNNER_TEMP/ci_changes.py"' not in body or "refs/heads/main:refs/remotes/origin/main" not in body:
|
||||
out.append("%s: `changes` does not read scripts/ci_changes.py from origin/main: a branch could decide that it needs no test" % name)
|
||||
if "ci_changes.py is not on origin/main yet: falling back to the copy of this branch" not in body:
|
||||
out.append("%s: `changes` falls back to the branch copy without saying so" % name)
|
||||
if not re.search(r'^ +python3 "\$RUNNER_TEMP/ci_changes\.py" %s "\$EVENT_NAME" "\$BASE_SHA" "\$HEAD_SHA" \| tee -a "\$GITHUB_OUTPUT"\s*$' % workflow, body, re.M):
|
||||
out.append("%s: `changes` does not run the copy it read from main with the workflow, the event and the two commits" % name)
|
||||
if "BASE_SHA: ${{ github.event.merge_group.base_sha }}" not in body or "HEAD_SHA: ${{ github.event.merge_group.head_sha }}" not in body:
|
||||
out.append("%s: `changes` does not read the base and the head of the queue entry" % name)
|
||||
if not re.search(r"^ shell: bash\s*$", body, re.M):
|
||||
out.append("%s: the step of `changes` has no `shell: bash` (the pipe to tee would hide a failure of the script: no pipefail)" % name)
|
||||
for job, text_ in jobs.items():
|
||||
if job in ("changes", "verdict"):
|
||||
continue
|
||||
if "changes" not in _needs(text_):
|
||||
out.append("%s: job %s does not need `changes`" % (name, job))
|
||||
cond = re.search(r"^ if: (.*)$", text_, re.M)
|
||||
if not cond or "needs.changes.outputs.run == 'true'" not in cond.group(1):
|
||||
out.append("%s: job %s does not run only on `needs.changes.outputs.run == 'true'`" % (name, job))
|
||||
verdict = jobs["verdict"]
|
||||
if "changes" not in _needs(verdict):
|
||||
out.append("%s: the verdict does not need `changes`" % name)
|
||||
if not re.search(r"^ +CHANGES_RUN: \$\{\{ needs\.changes\.outputs\.run \}\}\s*$", verdict, re.M):
|
||||
out.append("%s: the verdict does not pass CHANGES_RUN" % name)
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["e2e.yml", "fakeweb.yml"])
|
||||
def test_the_workflow_starts_with_changes_and_every_other_job_waits_for_its_answer(name):
|
||||
assert problems_changes(name, _text(name)) == []
|
||||
|
||||
|
||||
def test_a_workflow_that_forgets_changes_somewhere_is_refused():
|
||||
e2e = _text("e2e.yml")
|
||||
host = _jobs(e2e)["e2e-host"]
|
||||
assert any("job e2e-host does not need" in p for p in problems_changes("e2e.yml", e2e.replace(host, host.replace("needs: [changes, ", "needs: [", 1), 1)))
|
||||
no_if = e2e.replace(" if: needs.changes.outputs.run == 'true'\n uses: ./.github/workflows/core-on-index.yml", " uses: ./.github/workflows/core-on-index.yml", 1)
|
||||
assert no_if != e2e and any("job core-on-index does not run only on" in p for p in problems_changes("e2e.yml", no_if))
|
||||
fake = _text("fakeweb.yml")
|
||||
assert any("CHANGES_RUN" in p for p in problems_changes("fakeweb.yml", fake.replace("CHANGES_RUN: ${{ needs.changes.outputs.run }}", "X: 1", 1)))
|
||||
assert any("from origin/main" in p for p in problems_changes("fakeweb.yml", fake.replace('git show origin/main:scripts/ci_changes.py > "$RUNNER_TEMP/ci_changes.py"', "true", 1)))
|
||||
assert any("pipefail" in p for p in problems_changes("fakeweb.yml", fake.replace(" shell: bash\n env:\n EVENT_NAME", " env:\n EVENT_NAME", 1)))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ the verdict
|
||||
|
||||
|
||||
def _all_run(workflow: str) -> dict:
|
||||
"""Every job of the workflow as it ends when there was something to test."""
|
||||
needs = {name: {"result": "success", "outputs": {}} for name in ci_gate.TABLES[workflow][1]}
|
||||
needs["changes"]["outputs"] = {"run": "true", "files": "4"}
|
||||
if workflow == "e2e":
|
||||
needs["e2e-page-final-touched"]["outputs"] = {"touched": "true"}
|
||||
return needs
|
||||
|
||||
|
||||
def _nothing_to_test(workflow: str, files: str = "3") -> dict:
|
||||
"""Every job as it ends when `changes` said there was nothing to test."""
|
||||
needs = {name: {"result": "skipped", "outputs": {}} for name in ci_gate.TABLES[workflow][1]}
|
||||
needs["changes"] = {"result": "success", "outputs": {"run": "false", "files": files}}
|
||||
return needs
|
||||
|
||||
|
||||
def _heavy(workflow: str) -> list:
|
||||
return sorted(n for n in ci_gate.TABLES[workflow][1] if n != "changes")
|
||||
|
||||
|
||||
def _run(workflow: str, needs: dict, changes_run, event: str = "merge_group") -> subprocess.CompletedProcess:
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("NEEDS", "EVENT_NAME", "WORKFLOW", "INPUT_ONLY", "CHANGES_RUN")}
|
||||
env.update(NEEDS=json.dumps(needs), EVENT_NAME=event, WORKFLOW=workflow)
|
||||
if changes_run is not None:
|
||||
env["CHANGES_RUN"] = changes_run
|
||||
return subprocess.run([sys.executable, str(GATE)], env=env, capture_output=True, text=True, timeout=60)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
def test_every_job_ran_and_passed_is_ok_when_there_was_something_to_test(workflow):
|
||||
done = _run(workflow, _all_run(workflow), "true")
|
||||
assert done.returncode == 0 and done.stdout.splitlines()[-1] == "ok", done.stdout
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
def test_nothing_to_test_with_every_heavy_job_skipped_is_green_and_says_so(workflow):
|
||||
needs = _nothing_to_test(workflow)
|
||||
assert ci_gate.verdict(needs, "merge_group", workflow, "", "false") == []
|
||||
done = _run(workflow, needs, "false")
|
||||
assert done.returncode == 0, done.stdout
|
||||
assert done.stdout.splitlines()[-1] == "ok: nothing to test (3 files changed, none under the paths of %s)" % workflow
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
def test_nothing_to_test_but_a_heavy_job_ran_and_failed_is_red(workflow):
|
||||
for job in _heavy(workflow):
|
||||
needs = _nothing_to_test(workflow)
|
||||
needs[job]["result"] = "failure"
|
||||
done = _run(workflow, needs, "false")
|
||||
assert done.returncode == 1 and "job %s is failure" % job in done.stdout, (job, done.stdout)
|
||||
assert not done.stdout.splitlines()[-1].startswith("ok"), job
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
def test_nothing_to_test_but_a_heavy_job_ran_is_red_even_when_it_passed(workflow):
|
||||
for job in _heavy(workflow):
|
||||
needs = _nothing_to_test(workflow)
|
||||
needs[job]["result"] = "success"
|
||||
assert any("job %s is success" % job in line for line in ci_gate.verdict(needs, "merge_group", workflow, "", "false")), job
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
def test_something_to_test_but_a_heavy_job_skipped_is_red(workflow):
|
||||
for job in _heavy(workflow):
|
||||
if workflow == "e2e" and job in ci_gate.E2E_BY_OUTPUT:
|
||||
continue # skipped on purpose when the page oracle is not touched (run=true and touched=false)
|
||||
needs = _all_run(workflow)
|
||||
needs[job]["result"] = "skipped"
|
||||
done = _run(workflow, needs, "true")
|
||||
assert done.returncode == 1 and "FAIL %s: job %s is skipped. Fix: " % (ci_gate.TABLES[workflow][0], job) in done.stdout, (job, done.stdout)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
@pytest.mark.parametrize("value", [None, "", "maybe", "True", "1"])
|
||||
def test_a_missing_or_unreadable_answer_is_red_whatever_the_jobs_say(workflow, value):
|
||||
for needs in (_all_run(workflow), _nothing_to_test(workflow)):
|
||||
done = _run(workflow, needs, value)
|
||||
assert done.returncode == 1, (value, done.stdout)
|
||||
assert "FAIL %s: the output run of the job changes is" % ci_gate.TABLES[workflow][0] in done.stdout and RULE in done.stdout
|
||||
assert "ok" not in done.stdout.splitlines()
|
||||
assert ci_gate.verdict(_all_run(workflow), "merge_group", workflow)[0].startswith("FAIL "), "no answer given at all"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", HEAVY)
|
||||
@pytest.mark.parametrize("result", ["failure", "cancelled", "skipped"])
|
||||
@pytest.mark.parametrize("run", ["true", "false"])
|
||||
def test_a_changes_job_that_did_not_succeed_is_red_either_way(workflow, result, run):
|
||||
needs = _all_run(workflow) if run == "true" else _nothing_to_test(workflow)
|
||||
needs["changes"]["result"] = result
|
||||
assert any("job changes is %s" % result in line for line in ci_gate.verdict(needs, "merge_group", workflow, "", run))
|
||||
|
||||
|
||||
def test_a_push_and_a_dispatch_run_everything_so_nothing_there_may_be_skipped():
|
||||
for event in ("push", "workflow_dispatch"):
|
||||
needs = _all_run("fakeweb")
|
||||
needs["walk"]["result"] = "skipped"
|
||||
assert any("job walk is skipped" in line for line in ci_gate.verdict(needs, event, "fakeweb", "", "true"))
|
||||
|
||||
|
||||
def test_the_tests_workflow_has_no_changes_job_and_is_judged_as_before():
|
||||
assert "changes" not in ci_gate.FIX and "tests" not in ci_gate.HAS_CHANGES
|
||||
assert ci_gate.verdict({n: {"result": "success", "outputs": {}} for n in ci_gate.FIX}, "pull_request") == []
|
||||
@@ -0,0 +1,234 @@
|
||||
"""The guard of tests/_no_network.py: a destination on this host passes, anything else is refused and recorded, and the record fails the test.
|
||||
|
||||
Each case installs its own guard on top of the one the conftest gives every test that is not e2e; the inner guard refuses first, so nothing
|
||||
reaches the outer one and nothing leaves the machine: a refused connect never sends a packet.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
import _no_network
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
OUTSIDE = ("1.1.1.1", 443) # never contacted: the guard refuses before the system call
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", ["127.0.0.1", "127.8.9.10", "::1", "0.0.0.0", "::", "localhost", "LocalHost", "a.localhost", None, "",
|
||||
"198.51.100.9", "192.0.2.1", "203.0.113.7", "2001:db8::1", "::ffff:127.0.0.1", "[::1]"])
|
||||
def test_this_host_is_this_host(host):
|
||||
assert _no_network.is_on_this_host(host)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", ["1.1.1.1", "8.8.8.8", "10.0.0.1", "192.168.1.1", "2606:4700::1111", "api.ipify.org", "example.com",
|
||||
b"icanhazip.com", "::ffff:8.8.8.8", "fe80::1%lo"])
|
||||
def test_outside_is_outside(host):
|
||||
assert not _no_network.is_on_this_host(host)
|
||||
|
||||
|
||||
def test_a_connect_outside_is_refused_named_and_fails_the_test(monkeypatch):
|
||||
guard = _no_network.install(monkeypatch, "tests/test_x.py::test_y")
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
with pytest.raises(ConnectionRefusedError) as refused:
|
||||
s.connect(OUTSIDE)
|
||||
message = str(refused.value)
|
||||
for part in ("WHERE: tests/test_x.py::test_y", "WHAT: connect to 1.1.1.1:443", "FIX:", "RULE:"):
|
||||
assert part in message, message
|
||||
assert guard.verdict() is not None and "connect to 1.1.1.1:443" in guard.verdict()
|
||||
|
||||
|
||||
def test_a_refusal_the_code_swallowed_still_fails_the_test(monkeypatch):
|
||||
"""The code under test may catch the refusal and carry on (an offline fallback): the record is what fails the test."""
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
try:
|
||||
s.connect_ex(OUTSIDE)
|
||||
except OSError:
|
||||
pass
|
||||
assert guard.verdict() is not None
|
||||
|
||||
|
||||
def test_a_datagram_and_a_name_lookup_outside_are_refused(monkeypatch):
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
s.sendto(b"x", ("8.8.8.8", 53))
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
socket.getaddrinfo("api.ipify.org", 443)
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
socket.create_connection(("icanhazip.com", 443), timeout=1)
|
||||
assert guard.attempts == ["datagram to 8.8.8.8:53", "name lookup of api.ipify.org", "name lookup of icanhazip.com"]
|
||||
|
||||
|
||||
def test_a_client_thread_of_the_test_is_recorded(monkeypatch):
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
|
||||
def client():
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
try:
|
||||
s.connect(OUTSIDE)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
worker = threading.Thread(target=client)
|
||||
worker.start()
|
||||
worker.join(10)
|
||||
assert guard.attempts == ["connect to 1.1.1.1:443"]
|
||||
|
||||
|
||||
def test_this_host_passes_and_leaves_no_record(monkeypatch):
|
||||
"""The control: a server on loopback is reached through the same doors, by address and by name, and the test stays green."""
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
|
||||
server.bind(("127.0.0.1", 0))
|
||||
server.listen(1)
|
||||
port = server.getsockname()[1]
|
||||
with socket.create_connection(("localhost", port), timeout=5) as client:
|
||||
accepted, _ = server.accept()
|
||||
accepted.close()
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as other:
|
||||
assert other.connect_ex(("127.0.0.1", port)) == 0
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as receiver, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender:
|
||||
receiver.bind(("127.0.0.1", 0))
|
||||
sender.sendto(b"x", receiver.getsockname())
|
||||
assert guard.verdict() is None
|
||||
|
||||
|
||||
def test_the_address_this_host_sends_from_is_this_host(monkeypatch):
|
||||
"""A relay of the tests that leaves from the address of the host (tests/_host_address.py) is on this host: a datagram to it stays here."""
|
||||
own = _no_network.own_addresses()
|
||||
if not own:
|
||||
pytest.skip("this host has no default route, so no address of its own beside loopback")
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
with socket.socket(socket.AF_INET if ":" not in own[0] else socket.AF_INET6, socket.SOCK_DGRAM) as receiver:
|
||||
receiver.bind((own[0], 0))
|
||||
with socket.socket(receiver.family, socket.SOCK_DGRAM) as sender:
|
||||
sender.sendto(b"x", receiver.getsockname()[:2])
|
||||
assert guard.verdict() is None
|
||||
assert all(_no_network.is_on_this_host(a, own) for a in own)
|
||||
|
||||
|
||||
# The asyncio doors, for every loop kind this system has: the selector loop everywhere, and on Windows the Proactor loop too (the default
|
||||
# there), which connects with ConnectEx and sends with WSASendTo, never through socket.socket: the unit tier of the round runs on both systems.
|
||||
import asyncio # noqa: E402
|
||||
import sys # noqa: E402
|
||||
|
||||
LOOPS = ["selector"] + (["proactor"] if sys.platform == "win32" else [])
|
||||
|
||||
|
||||
def _run(kind, coroutine_function):
|
||||
loop = asyncio.SelectorEventLoop() if kind == "selector" else asyncio.ProactorEventLoop()
|
||||
try:
|
||||
return loop.run_until_complete(coroutine_function())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", LOOPS)
|
||||
def test_an_asyncio_connection_to_a_numeric_address_outside_is_refused(monkeypatch, kind):
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
|
||||
async def go():
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
await asyncio.open_connection(*OUTSIDE)
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.setblocking(False)
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
await asyncio.get_running_loop().sock_connect(s, OUTSIDE)
|
||||
|
||||
_run(kind, go)
|
||||
assert guard.attempts == ["asyncio connect to 1.1.1.1:443"], guard.attempts
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", LOOPS)
|
||||
def test_an_asyncio_datagram_outside_is_refused(monkeypatch, kind):
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
|
||||
async def go():
|
||||
loop = asyncio.get_running_loop()
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
await loop.create_datagram_endpoint(asyncio.DatagramProtocol, remote_addr=("8.8.8.8", 53))
|
||||
transport, _ = await loop.create_datagram_endpoint(asyncio.DatagramProtocol, local_addr=("127.0.0.1", 0))
|
||||
try:
|
||||
# the selector transport hands a refused send to its protocol (error_received) instead of raising it: the record is what counts
|
||||
try:
|
||||
transport.sendto(b"x", ("8.8.4.4", 53))
|
||||
except ConnectionRefusedError:
|
||||
pass
|
||||
finally:
|
||||
transport.close()
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.setblocking(False)
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
await loop.sock_sendto(s, b"x", ("8.8.8.8", 5353))
|
||||
|
||||
_run(kind, go)
|
||||
assert guard.attempts == ["asyncio datagram endpoint to 8.8.8.8:53", "asyncio datagram to 8.8.4.4:53", "asyncio datagram to 8.8.8.8:5353"] \
|
||||
or guard.attempts == ["asyncio datagram endpoint to 8.8.8.8:53", "datagram to 8.8.4.4:53", "asyncio datagram to 8.8.8.8:5353"], guard.attempts
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", LOOPS)
|
||||
def test_asyncio_on_this_host_passes(monkeypatch, kind):
|
||||
"""The control: a server on loopback, reached through asyncio by address and a datagram to a loopback receiver, leave no record."""
|
||||
guard = _no_network.install(monkeypatch, "t")
|
||||
|
||||
async def go():
|
||||
loop = asyncio.get_running_loop()
|
||||
server = await asyncio.start_server(lambda r, w: w.close(), "127.0.0.1", 0)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
writer.close()
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
receiver, _ = await loop.create_datagram_endpoint(asyncio.DatagramProtocol, local_addr=("127.0.0.1", 0))
|
||||
sender, _ = await loop.create_datagram_endpoint(asyncio.DatagramProtocol, remote_addr=receiver.get_extra_info("sockname"))
|
||||
sender.sendto(b"x")
|
||||
sender.close()
|
||||
receiver.close()
|
||||
|
||||
_run(kind, go)
|
||||
assert guard.verdict() is None
|
||||
|
||||
|
||||
# The one declared third party: the version gate asks the index. Faked below the guard, so nothing leaves the machine here either.
|
||||
INDEX_ADDRESS = "8.8.4.4" # stands for the index: faked, never contacted
|
||||
|
||||
|
||||
def _fake_index(monkeypatch):
|
||||
"""The system lookup answers the index's address for pypi.org, and the system connect records instead of connecting."""
|
||||
reached = []
|
||||
monkeypatch.setattr(socket, "getaddrinfo", lambda host, port, *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (INDEX_ADDRESS, port))])
|
||||
monkeypatch.setattr(socket.socket, "connect", lambda self, address: reached.append(address))
|
||||
return reached
|
||||
|
||||
|
||||
def test_the_version_gate_may_ask_the_index_and_only_the_index(monkeypatch):
|
||||
reached = _fake_index(monkeypatch)
|
||||
guard = _no_network.install(monkeypatch, "tests/test_version_is_not_taken.py::test_the_declared_version_is_not_already_published")
|
||||
(family, kind, proto, _name, address), = socket.getaddrinfo("pypi.org", 443)
|
||||
with socket.socket(family, kind) as s:
|
||||
s.connect(address)
|
||||
assert [a for a in reached if a[1] == 443] == [(INDEX_ADDRESS, 443)] # (the guard's own probe of this host's address is recorded too)
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
socket.getaddrinfo("files.example.net", 443)
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s, pytest.raises(ConnectionRefusedError):
|
||||
s.connect(OUTSIDE)
|
||||
assert guard.attempts == ["name lookup of files.example.net", "connect to 1.1.1.1:443"]
|
||||
|
||||
|
||||
def test_no_other_file_may_ask_the_index(monkeypatch):
|
||||
reached = _fake_index(monkeypatch)
|
||||
guard = _no_network.install(monkeypatch, "tests/test_x.py::test_y")
|
||||
with pytest.raises(ConnectionRefusedError):
|
||||
socket.getaddrinfo("pypi.org", 443)
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s, pytest.raises(ConnectionRefusedError):
|
||||
s.connect((INDEX_ADDRESS, 443))
|
||||
assert [a for a in reached if a[1] == 443] == [] and guard.attempts == ["name lookup of pypi.org", "connect to %s:443" % INDEX_ADDRESS]
|
||||
|
||||
|
||||
def test_the_declared_third_parties_are_the_version_gate_alone():
|
||||
"""A new entry is a decision: this test changes with it, in the same diff, where a reviewer sees it."""
|
||||
assert _no_network.DECLARED_THIRD_PARTIES == {"tests/test_version_is_not_taken.py": ("pypi.org",)}
|
||||
@@ -29,6 +29,7 @@ from http.server import BaseHTTPRequestHandler
|
||||
import pytest
|
||||
|
||||
from _bfcache_evidence import decide_outcome, read_after_go_back, wait_cacheable
|
||||
from _evidence_on_failure import FailureEvidence
|
||||
from _servers import LocalServer
|
||||
|
||||
STRATEGY_1 = {
|
||||
@@ -160,13 +161,30 @@ def _ask(page, where):
|
||||
return target.evaluate("window.__ask()")
|
||||
|
||||
|
||||
#: The engine's own log of the session history and the back-forward cache, kept with the evidence of a red run (one file per process): whether
|
||||
#: the restore happened, in which process, and what the parent did with the history entry. Run 45691494388 (job 139520127265) saw go_back
|
||||
#: end with "no new navigation on frame mainframe-11 in 30s" for top/other-site/goto and kept nothing to say whether the engine restored the
|
||||
#: page. A diagnostic no page reads.
|
||||
BFCACHE_LOG = "timestamp,SHIPBFCache:5,nsSHistory:5,SessionHistory:4,BCWebProgress:4,DocumentChannel:4,BrowsingContext:4"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("how", ["goto", "location"])
|
||||
@pytest.mark.parametrize("away", ["same-site", "other-site"])
|
||||
@pytest.mark.parametrize("where", ["top", "oop-frame"])
|
||||
def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(firefox_binary, sites, events, where,
|
||||
away, how, engine_at_least):
|
||||
"""When it fails it saves, under ``invpw-evidence/worker-back-from-the-cache-<where>-<away>-<how>/``, the Juggler wire, the engine trace,
|
||||
the engine log BFCACHE_LOG and ``after-go-back.jsonl`` (what the page said when go_back raised, and 2 s later)."""
|
||||
engine_at_least("firefox-62")
|
||||
reads = _Reads()
|
||||
with FailureEvidence("worker-back-from-the-cache-%s-%s-%s" % (where, away, how)) as evidence:
|
||||
evidence.note_records("after-go-back", reads)
|
||||
evidence.arm(moz_log=BFCACHE_LOG)
|
||||
_the_case(firefox_binary, sites, events, where, away, how, reads)
|
||||
|
||||
|
||||
def _the_case(firefox_binary, sites, events, where, away, how, reads):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
|
||||
@@ -206,7 +224,7 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
|
||||
|
||||
# 3. back from the cache: the same worker, told once, after the restored document's contexts are cleared
|
||||
back = len(events)
|
||||
page.go_back(wait_until="load")
|
||||
_go_back_and_record(page, reads)
|
||||
# What it knows is written down BEFORE anything is asserted. A goto is started by the PARENT and Firefox may refuse the cache for it,
|
||||
# to the same site or to another (measured: the navigation's own channel is still in the old document's loadgroup when the parent
|
||||
# checks: SHIPBFCache log, CanonicalBrowsingContext::AllowedInBFCache); then the document is built again and the contract is the one
|
||||
@@ -276,3 +294,34 @@ def _assert_a_new_page_with_a_new_worker(page, events, where, old, back):
|
||||
elif m == "Page.workerDestroyed":
|
||||
live.pop(p["workerId"], None)
|
||||
assert list(live) == [new[0]], "live workers after the page was built again: %r" % list(live.values())
|
||||
|
||||
|
||||
class _Reads:
|
||||
"""What the page says right after a go_back that raised, and once more later (``FailureEvidence.note_records`` shape)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.lock = threading.Lock()
|
||||
self.records = []
|
||||
|
||||
def read(self, page, when):
|
||||
record = {"when": when, "t": time.time(), "client_url": page.url}
|
||||
try:
|
||||
record.update(page.evaluate(
|
||||
"() => ({url: location.href, shown: window.__shown || null, history: history.length,"
|
||||
" type: (performance.getEntriesByType('navigation')[0] || {}).type || null, state: document.readyState})"))
|
||||
except Exception as problem: # the page may be gone or changing: that is what is being recorded
|
||||
record["read_error"] = "%s: %s" % (type(problem).__name__, problem)
|
||||
with self.lock:
|
||||
self.records.append(record)
|
||||
|
||||
|
||||
def _go_back_and_record(page, reads):
|
||||
"""``page.go_back(wait_until="load")``; when it raises, what the page says then and after a short pause is recorded first (the error is raised
|
||||
unchanged: the pause only dates a restore that lands after the wait, it decides nothing)."""
|
||||
try:
|
||||
page.go_back(wait_until="load")
|
||||
except Exception:
|
||||
reads.read(page, "right after the go_back raised")
|
||||
page.wait_for_timeout(2000)
|
||||
reads.read(page, "2 s later")
|
||||
raise
|
||||
@@ -2391,7 +2391,7 @@ def test_the_strace_tail_is_the_last_100_lines_and_the_signal_line_that_is_furth
|
||||
assert crash.strace_tail(short) == ['1 execve("/e", [], 0x1) = 0']
|
||||
|
||||
|
||||
def test_the_core_is_run_through_gdb_with_the_three_commands_and_the_build_ids_are_asked_of_readelf_and_eu_unstrip(tmp_path):
|
||||
def test_the_core_is_run_through_gdb_with_its_commands_and_the_build_ids_are_asked_of_readelf_and_eu_unstrip(tmp_path):
|
||||
core = tmp_path / "core.firefox.4242.1"
|
||||
core.write_bytes(b"\x7fELF")
|
||||
binary = tmp_path / "engine" / "firefox"
|
||||
@@ -2405,7 +2405,7 @@ def test_the_core_is_run_through_gdb_with_the_three_commands_and_the_build_ids_a
|
||||
gdb = [c for c in run.calls if c[0].endswith("gdb")][0]
|
||||
assert gdb[:2] == ["/usr/bin/gdb", "-batch"] and gdb[-2:] == [str(binary), str(core)]
|
||||
commands = [gdb[i + 1] for i, a in enumerate(gdb) if a == "-ex"]
|
||||
assert commands == ["thread apply all bt", "x/s *(char**)&gMozCrashReason", "info sharedlibrary"]
|
||||
assert commands == ["thread apply all bt", "x/s *(char**)&gMozCrashReason", "info sharedlibrary", crash.argv_gdb_command()]
|
||||
assert "Thread 1 (" in got["cores"]["backtraces"][core.name] and "MOZ_CRASH(shutdown)" in got["cores"]["backtraces"][core.name]
|
||||
ids = got["cores"]["build_ids"][core.name]
|
||||
assert ids["binary"] == "Build ID: abc123" and ids["libxul"] == "Build ID: abc123" and "deadbeef" in ids["core"]
|
||||
|
||||
@@ -37,7 +37,7 @@ def transcript(label="a", seeds=(11, 12)):
|
||||
"requests": {"GET A/": {"count": 1, "headers": [["Host", "journey-a.test:A"], ["Accept", "*/*"]], "name_orders": ["Host,Accept"],
|
||||
"body_length": 0}}}}},
|
||||
"https": {"h2": {"v1": {"connections": [{"alpn": "h2", "tls": wc.parse_client_hello(build_hello())}]}}},
|
||||
"webrtc": {"candidates": ["udp comp1 prio100 srflx <exit>"], "gathering": "complete"},
|
||||
"webrtc": {"candidates": ["udp comp1 prio100 srflx <exit>"], "candidate_types": ["relay", "srflx"], "gathering": "complete"},
|
||||
"idle": {"c1": {"destinations": {"connects": [], "dns": []}}},
|
||||
"lab": {"direct": {"witness_tcp": [], "witness_udp": [], "watcher": [], "doh_direct": [], "resolver_trap": [], "blind": []}},
|
||||
}
|
||||
@@ -1261,7 +1261,7 @@ def minimal_run():
|
||||
"end_stream": True}]}
|
||||
body = {"journey": {"steps": {"%02d" % i: step for i in range(17)}, "connects": ab.connect_summary(["127.0.0.1:7000"], norm),
|
||||
"dns": ab.dns_summary([("journey-a.test", 1, "lab")])}, "https": {"h2": {"v1": {"connections": [{"alpn": "h2", "tls": tls, "h2": h2}]}}},
|
||||
"webrtc": {"candidates": ["udp comp1 prio1 srflx <exit>"], "gathering": "complete"}, "idle": {"c1": {"destinations": {"connects": [], "dns": []}}},
|
||||
"webrtc": {"candidates": ["udp comp1 prio1 srflx <exit>"], "candidate_types": ["relay", "srflx"], "gathering": "complete"}, "idle": {"c1": {"destinations": {"connects": [], "dns": []}}},
|
||||
"lab": {"direct": {"witness_tcp": [], "witness_udp": [], "watcher": [], "doh_direct": [], "resolver_trap": [], "blind": []}}}
|
||||
leaves = ab.flatten({"11": body})
|
||||
by_category = {}
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
"""The probe of the WebRTC walk must hold the credential the lab's TURN server signs with, and the A/A must not count retransmissions (scripts/ci_ab_network.py, tests/_turn_chain.py), no browser.
|
||||
|
||||
Two defects of the oracle, each held here:
|
||||
|
||||
* The probe gave the TURN server ``lab``/``lab`` while the server signs its answers with the long-term key of its own password: the browser found the MESSAGE-INTEGRITY of every
|
||||
Allocate success invalid, dropped it, retransmitted up to the engine's maximum and ended in error 701, so no relay candidate was ever made. And the fake server never checked the
|
||||
request's own MESSAGE-INTEGRITY, so it "allocated" for a client with the wrong password. The probe now takes the credential as an argument (the walk passes the server's own
|
||||
constant) and the server refuses a request whose integrity is wrong, as a real one does.
|
||||
* The leaf ``seeds/<seed>/webrtc/udp/counts/<target>`` counted DATAGRAMS. A retransmission is network timing (the first RTO is 100 ms and doubles; a late 401 on a loaded host adds
|
||||
one), so 1+7 became 2+7 and the A/A of one engine read 8 against 9. The leaf now counts STUN TRANSACTIONS; a transaction with more transmits than the engine's maximum is a problem
|
||||
of the run, not a compared leaf.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import inspect
|
||||
import json
|
||||
import re
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import _turn_chain # noqa: E402
|
||||
import ci_ab_network as ab # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COOKIE = 0x2112A442
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the count of transactions
|
||||
def walk_transcript(label, tids):
|
||||
"""A transcript of seed 4 whose WebRTC walk sent ``tids`` (one entry per datagram, in order) to the TURN server, summarised as ``run`` summarises them."""
|
||||
events = [{"target": ab.TURN_TARGET, "message": "stun-0x0003", "tid": tid, "opener": None} for tid in tids]
|
||||
return {"format": ab.FORMAT, "label": label, "platform": "linux",
|
||||
"seeds": {"4": {"webrtc": {"candidates": ["udp comp1 prio1 relay <exit>"], "candidate_types": ["relay"], "gathering": "complete", "udp": ab.udp_summary(events, ab.Normalizer({}))}}}}
|
||||
|
||||
|
||||
A, B = "aa" * 12, "bb" * 12
|
||||
#: The recorded shape: the first Allocate once and the second seven times, against the first twice (a late 401) and the second seven times.
|
||||
FIRST_RUN, SECOND_RUN = [A] + [B] * 7, [A] * 2 + [B] * 7
|
||||
|
||||
|
||||
def test_a_late_401_that_adds_a_retransmission_is_not_a_difference_of_the_engine():
|
||||
a, b = walk_transcript("a", FIRST_RUN), walk_transcript("b", SECOND_RUN)
|
||||
assert len(FIRST_RUN) == 8 and len(SECOND_RUN) == 9, "the recorded 8 against 9"
|
||||
counts = lambda t: t["seeds"]["4"]["webrtc"]["udp"]["counts"][ab.TURN_TARGET] # noqa: E731
|
||||
assert (counts(a), counts(b)) == (2, 2), "two transactions on both sides"
|
||||
report = ab.compare_transcripts(a, b, [], 0, "a", "b")
|
||||
assert report["differences"] == [] and report["problems"] == [] and report["verdict"] == "green"
|
||||
|
||||
|
||||
def test_a_transaction_that_one_run_did_not_make_is_still_a_difference():
|
||||
a = walk_transcript("a", FIRST_RUN)
|
||||
c = walk_transcript("c", [A] + [B] * 7 + ["cc" * 12]) # a third transaction: the engine asked for something more
|
||||
report = ab.compare_transcripts(a, c, [], 0, "a", "c")
|
||||
assert [d["path"] for d in report["differences"]] == ["seeds/4/webrtc/udp/counts/%s" % ab.TURN_TARGET]
|
||||
assert (report["differences"][0]["a"], report["differences"][0]["b"]) == (2, 3) and report["verdict"] == "red"
|
||||
|
||||
|
||||
def test_a_datagram_that_is_not_stun_counts_one_each_and_the_messages_and_the_order_are_kept():
|
||||
events = [{"target": "127.0.0.1:5555", "message": "quic-long", "tid": None}] * 3 + [
|
||||
{"target": ab.TURN_TARGET, "message": "stun-0x0003", "tid": A}, {"target": ab.TURN_TARGET, "message": "stun-0x0113", "tid": A}]
|
||||
summary = ab.udp_summary(events, ab.Normalizer({}))
|
||||
assert summary == {"order": ["127.0.0.1:5555", ab.TURN_TARGET], "messages": {"127.0.0.1:5555": ["quic-long"], ab.TURN_TARGET: ["stun-0x0003", "stun-0x0113"]},
|
||||
"counts": {"127.0.0.1:5555": 3, ab.TURN_TARGET: 1}}
|
||||
|
||||
|
||||
def test_the_engines_maximum_is_the_pref_of_the_engine_and_a_transaction_over_it_is_a_problem_while_one_at_it_is_not():
|
||||
assert ab.STUN_MAX_TRANSMITS == 7
|
||||
source = (ROOT / "scripts" / "ci_ab_network.py").read_text(encoding="utf-8")
|
||||
assert "media.peerconnection.ice.stun_client_maximum_transmits" in source and "modules/libpref/init/all.js" in source
|
||||
|
||||
at_most = walk_transcript("a", [A] * 7)
|
||||
assert "over_limit" not in at_most["seeds"]["4"]["webrtc"]["udp"]
|
||||
assert ab.compare_transcripts(at_most, at_most, [], 0, "a", "a")["problems"] == []
|
||||
|
||||
over = walk_transcript("b", [A] * 8)
|
||||
assert over["seeds"]["4"]["webrtc"]["udp"]["over_limit"] == {ab.TURN_TARGET: [8]}
|
||||
report = ab.compare_transcripts(at_most, over, [], 0, "a", "b")
|
||||
assert report["verdict"] == "red" and len(report["problems"]) == 1 and "8 times" in report["problems"][0] and "maximum of 7" in report["problems"][0]
|
||||
assert report["problems"][0].startswith("b: ") and report["differences"] == [], "a problem of the run, not a compared leaf"
|
||||
both = ab.compare_transcripts(over, over, [], 0, "a", "b")
|
||||
assert len(both["problems"]) == 2 and both["differences"] == [], "each side that did it is named"
|
||||
|
||||
|
||||
def test_the_a_a_prints_a_transaction_over_the_maximum_as_a_fail_line_and_counts_it_among_the_problems(capsys):
|
||||
over = walk_transcript("a", [A] * 8)
|
||||
report = ab.compare_transcripts(over, walk_transcript("b", [A] * 7), [], 0, "a", "b")
|
||||
ab.print_report(report, True)
|
||||
out = capsys.readouterr().out
|
||||
assert re.search(r"^FAIL a: a STUN transaction to 198\.51\.100\.7:3478 was sent 8 times, more than the engine's maximum of 7 transmits", out, re.M), out
|
||||
assert "AB NETWORK A/A FAILED: 0 differences, 1 problems" in out and "\nDIFF " not in "\n" + out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the credential of the probe
|
||||
def test_the_probe_has_no_credential_written_in_it_and_the_walk_passes_the_one_of_the_lab_server():
|
||||
js = ab.RTC_JS
|
||||
assert not re.search(r"""credential\s*:\s*['"]""", js) and not re.search(r"""username\s*:\s*['"]""", js), "no literal credential or user name in the page's script"
|
||||
assert "'lab'" not in js and _turn_chain.PASSWORD not in js
|
||||
assert "async (args) =>" in js and "const [stunUrl, turnUrl, username, credential] = args;" in js
|
||||
assert "{urls: [turnUrl], username, credential}" in js and "{urls: [stunUrl]}" in js, "the STUN entry has no credential, the TURN entry has the arguments"
|
||||
walk = inspect.getsource(ab.walk_webrtc)
|
||||
assert "from _turn_chain import PASSWORD" in walk and "[STUN_URL, TURN_URL, TURN_USERNAME, TURN_PASSWORD]" in walk
|
||||
assert _turn_chain.PASSWORD not in (ROOT / "scripts" / "ci_ab_network.py").read_text(encoding="utf-8"), "the password is written once, in tests/_turn_chain.py"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the TURN server refuses a wrong integrity
|
||||
def attribute(kind, value):
|
||||
return struct.pack("!HH", kind, len(value)) + value + b"\x00" * (-len(value) % 4)
|
||||
|
||||
|
||||
def signed(mtype, tid, user, password, extra=b""):
|
||||
"""A request as a client builds it (RFC 5389 section 15.4), written here and not taken from the server's module: USERNAME, REALM, NONCE, then MESSAGE-INTEGRITY, the
|
||||
HMAC-SHA1 under md5(user:realm:password) over the message with the length of the header counting the attribute itself."""
|
||||
body = attribute(0x0006, user.encode()) + attribute(0x0014, _turn_chain.REALM.encode()) + attribute(0x0015, _turn_chain.NONCE.encode()) + extra
|
||||
head = struct.pack("!HHI", mtype, len(body) + 24, COOKIE) + tid
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, _turn_chain.REALM, password)).encode(), usedforsecurity=False).digest()
|
||||
return head + body + attribute(0x0008, hmac.new(key, head + body, hashlib.sha1).digest())
|
||||
|
||||
|
||||
def unsigned(mtype, tid):
|
||||
return struct.pack("!HHI", mtype, 0, COOKIE) + tid
|
||||
|
||||
|
||||
def ask(server, request):
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.settimeout(5)
|
||||
try:
|
||||
client.sendto(request, server.address)
|
||||
answer, _ = client.recvfrom(65536)
|
||||
finally:
|
||||
client.close()
|
||||
return struct.unpack("!H", answer[:2])[0], _turn_chain._attrs(answer)
|
||||
|
||||
|
||||
def error_code(attrs):
|
||||
return attrs[0x0009][2] * 100 + attrs[0x0009][3]
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def turn():
|
||||
server = _turn_chain.TurnServer()
|
||||
try:
|
||||
yield server
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def test_with_the_right_credential_an_allocate_is_answered_401_and_then_with_the_relay_and_nothing_is_refused(turn):
|
||||
kind, attrs = ask(turn, unsigned(0x0003, b"\x01" * 12))
|
||||
assert kind == 0x0113 and error_code(attrs) == 401 and attrs[0x0014] == _turn_chain.REALM.encode() and attrs[0x0015] == _turn_chain.NONCE.encode()
|
||||
kind, attrs = ask(turn, signed(0x0003, b"\x02" * 12, "lab", _turn_chain.PASSWORD))
|
||||
assert kind == 0x0103 and 0x0016 in attrs and 0x0008 in attrs, "the success carries XOR-RELAYED-ADDRESS and is signed"
|
||||
assert [a[2] for a in turn.allocations] == ["lab"] and turn.refused == []
|
||||
assert len(turn.seen) == 2 and [r[3] for r in turn.requests] == [False, True], "requests and seen keep their meaning"
|
||||
|
||||
|
||||
def test_with_a_wrong_credential_both_allocates_are_answered_401_and_nothing_is_allocated(turn):
|
||||
kind, attrs = ask(turn, unsigned(0x0003, b"\x01" * 12))
|
||||
assert kind == 0x0113 and error_code(attrs) == 401
|
||||
kind, attrs = ask(turn, signed(0x0003, b"\x02" * 12, "lab", "not-the-password"))
|
||||
assert kind == 0x0113 and error_code(attrs) == 401 and 0x0016 not in attrs, "no relay for a client with the wrong password"
|
||||
assert attrs[0x0014] == _turn_chain.REALM.encode() and attrs[0x0015] == _turn_chain.NONCE.encode(), "the 401 asks again, with the realm and the nonce"
|
||||
assert turn.allocations == []
|
||||
assert len(turn.refused) == 1 and turn.refused[0][2:4] == ("lab", b"\x02" * 12), turn.refused
|
||||
assert [r[3] for r in turn.requests] == [False, True], "the request still carried credentials: `requests` says what arrived, `refused` what was turned away"
|
||||
|
||||
|
||||
def test_a_request_with_a_user_name_and_no_integrity_or_a_changed_message_is_refused_too(turn):
|
||||
body = attribute(0x0006, b"lab")
|
||||
kind, _ = ask(turn, struct.pack("!HHI", 0x0003, len(body), COOKIE) + b"\x03" * 12 + body)
|
||||
assert kind == 0x0113 and turn.allocations == [] and len(turn.refused) == 1
|
||||
good = signed(0x0003, b"\x04" * 12, "lab", _turn_chain.PASSWORD)
|
||||
tampered = good[:20] + attribute(0x0006, b"lbb") + good[20 + len(attribute(0x0006, b"lab")):]
|
||||
assert len(tampered) == len(good) and ask(turn, tampered)[0] == 0x0113 and turn.allocations == [] and len(turn.refused) == 2
|
||||
assert ask(turn, good)[0] == 0x0103 and len(turn.allocations) == 1
|
||||
|
||||
|
||||
def test_a_refresh_with_a_wrong_integrity_is_refused_and_one_with_the_right_one_is_answered(turn):
|
||||
kind, attrs = ask(turn, signed(0x0004, b"\x05" * 12, "lab", "wrong"))
|
||||
assert kind == 0x0114 and error_code(attrs) == 401 and len(turn.refused) == 1
|
||||
kind, _ = ask(turn, signed(0x0004, b"\x06" * 12, "lab", _turn_chain.PASSWORD))
|
||||
assert kind == 0x0104 and len(turn.refused) == 1 and turn.allocations == []
|
||||
|
||||
|
||||
def test_the_integrity_check_is_the_one_of_rfc_5389_with_the_length_adjusted():
|
||||
good = signed(0x0003, b"\x07" * 12, "lab", _turn_chain.PASSWORD)
|
||||
assert _turn_chain.integrity_valid(good, "lab") and not _turn_chain.integrity_valid(good, "other")
|
||||
# an attribute after MESSAGE-INTEGRITY (a FINGERPRINT) does not change what is signed
|
||||
assert _turn_chain.integrity_valid(good + attribute(0x8028, b"\x00" * 4), "lab")
|
||||
assert not _turn_chain.integrity_valid(unsigned(0x0003, b"\x07" * 12), "lab") and not _turn_chain.integrity_valid(good[:-4], "lab")
|
||||
assert _turn_chain.long_term_key("lab") == hashlib.md5(("lab:%s:%s" % (_turn_chain.REALM, _turn_chain.PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
|
||||
|
||||
def test_the_server_of_the_lab_keeps_the_list_of_refusals_too():
|
||||
_gateway, turn_class, _page = ab.make_lab_classes()
|
||||
server = turn_class("127.0.0.1")
|
||||
try:
|
||||
assert server.refused == [] and isinstance(server, _turn_chain.TurnServer)
|
||||
kind, _ = ask(server, signed(0x0003, b"\x08" * 12, "lab", "wrong"))
|
||||
assert kind == 0x0113 and len(server.refused) == 1 and server.allocations == []
|
||||
kind, _ = ask(server, signed(0x0003, b"\x09" * 12, "lab", _turn_chain.PASSWORD))
|
||||
assert kind == 0x0103 and len(server.allocations) == 1
|
||||
json.dumps(server.exchanges)
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the A/A proves the TURN path it compares
|
||||
def with_walk(transcript, **fields):
|
||||
"""The same transcript with fields of its seed-4 WebRTC walk replaced."""
|
||||
out = json.loads(json.dumps(transcript))
|
||||
out["seeds"]["4"]["webrtc"].update(fields)
|
||||
return out
|
||||
|
||||
|
||||
def turn_lines(report):
|
||||
"""The problems that say the TURN path did not work (a leaf that differs because of it is reported too, as a difference: that is not what is held here)."""
|
||||
return [p for p in report["problems"] if p.startswith("seeds/4/webrtc: ")]
|
||||
|
||||
|
||||
def test_a_transcript_whose_walk_made_no_relay_candidate_is_a_problem_on_both_sides_of_the_a_a():
|
||||
good = walk_transcript("a", FIRST_RUN)
|
||||
assert ab.compare_transcripts(good, walk_transcript("b", SECOND_RUN), [], 0, "a", "b")["problems"] == []
|
||||
no_relay = with_walk(walk_transcript("b", FIRST_RUN), candidate_types=["host", "srflx"])
|
||||
report = ab.compare_transcripts(good, no_relay, [], 0, "a", "b")
|
||||
assert report["verdict"] == "red" and len(turn_lines(report)) == 1
|
||||
assert report["problems"][0].startswith("seeds/4/webrtc: b made no relay candidate through the lab TURN (no error). Fix: the probe's credential must be the lab TURN's (tests/_turn_chain.py PASSWORD)")
|
||||
assert report["problems"][0].endswith("Rule: the A/A proves the TURN path it compares")
|
||||
both = ab.compare_transcripts(no_relay, with_walk(good, candidate_types=[]), [], 0, "a", "b")
|
||||
assert [p.split(" made")[0] for p in turn_lines(both)] == ["seeds/4/webrtc: a", "seeds/4/webrtc: b"], "each side that has none is named"
|
||||
|
||||
|
||||
def test_a_701_for_the_lab_turn_is_a_problem_even_when_a_relay_candidate_is_there_and_one_for_another_server_is_not(capsys):
|
||||
good = walk_transcript("a", FIRST_RUN)
|
||||
broken = with_walk(good, errors=["701 turn:%s?transport=udp" % ab.TURN_TARGET])
|
||||
report = ab.compare_transcripts(good, broken, [], 0, "a", "b")
|
||||
assert report["verdict"] == "red" and len(turn_lines(report)) == 1 and "701 turn:198.51.100.7:3478" in turn_lines(report)[0] and turn_lines(report)[0].startswith("seeds/4/webrtc: b ")
|
||||
ab.print_report(report, True)
|
||||
out = capsys.readouterr().out
|
||||
assert re.search(r"^FAIL seeds/4/webrtc: b made no relay candidate through the lab TURN \(701 turn:", out, re.M) and "AB NETWORK A/A FAILED:" in out and "2 problems" in out
|
||||
other = with_walk(good, errors=["701 stun:198.51.100.5:19302"])
|
||||
assert turn_lines(ab.compare_transcripts(good, other, [], 0, "a", "b")) == []
|
||||
|
||||
|
||||
def test_a_transcript_with_a_relay_candidate_and_no_error_is_not_a_problem_and_one_with_no_walk_says_nothing():
|
||||
good = walk_transcript("a", FIRST_RUN)
|
||||
assert ab.turn_path_problems(good, "a") == []
|
||||
assert ab.turn_path_problems({"seeds": {"4": {"journey": {}}}}, "a") == []
|
||||
assert ab.turn_path_problems({"seeds": {}}, "a") == []
|
||||
|
||||
|
||||
def test_a_request_the_lab_turn_refused_is_a_problem_and_the_count_is_not_a_compared_leaf():
|
||||
good = with_walk(walk_transcript("a", FIRST_RUN), turn={"messages": ["0x0003"], "allocated": True, "refused": 0})
|
||||
refused = with_walk(good, turn={"messages": ["0x0003"], "allocated": True, "refused": 2})
|
||||
report = ab.compare_transcripts(good, refused, [], 0, "a", "b")
|
||||
assert report["differences"] == [] and len(report["problems"]) == 1 and len(turn_lines(report)) == 1 and "the lab TURN refused 2 request(s)" in report["problems"][0]
|
||||
assert ab.compare_transcripts(good, good, [], 0, "a", "b")["problems"] == []
|
||||
walk = inspect.getsource(ab.walk_webrtc)
|
||||
assert '"refused": len(lab.turn.refused)' in walk, "the walk writes what the lab TURN refused"
|
||||
@@ -0,0 +1,253 @@
|
||||
"""The TURN deallocation is evidence of the network oracle, never a compared leaf (scripts/ci_ab_network.py, tests/_turn_chain.py), no browser.
|
||||
|
||||
The engine ends an allocation with ONE Refresh whose LIFETIME is 0, best effort, while it shuts the TURN client down (nICEr ``nr_turn_client_deallocate``: "we are only sending a single
|
||||
request here because we are in the process of shutting everything down"). It reaches the lab in some walks and not in others for the same engine (the A/A of PR 611: two seeds whose
|
||||
``webrtc/turn/messages`` differed only by ``0x0004``). So it is recognised by what it MEANS (a Refresh, 0x0004, with LIFETIME, 0x000D, equal to 0), by the lab's TURN server, and the walk
|
||||
leaves it out of the messages and of the transactions the gateway counted for the TURN address; it goes to the evidence. More than one for one allocation, or one for an address that has
|
||||
no allocation, is a problem of the run. A Refresh that keeps the allocation alive (a lifetime above 0) is a message of the walk like any other.
|
||||
|
||||
The walks below are the real ``walk_webrtc`` on a real lab: a fake browser whose page sends the datagrams a TURN client sends to the lab's TURN server, over a socket on loopback, and
|
||||
whose gateway events are written as the gateway writes them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import _turn_chain # noqa: E402
|
||||
import ci_ab_network as ab # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ALLOCATE, REFRESH_A, REFRESH_B, REFRESH_C = (bytes([n]) * 12 for n in (1, 2, 3, 4))
|
||||
RELAY_CANDIDATE = "candidate:1 1 udp 100 192.0.2.1 5000 typ relay"
|
||||
RULE = "Rule: the TURN deallocation is one best-effort send at teardown (nICEr nr_turn_client_deallocate)"
|
||||
|
||||
|
||||
def signed_refresh(tid, lifetime, user=b"lab"):
|
||||
"""A Refresh as a TURN client sends it after the 401: USERNAME and LIFETIME, signed with the long-term key."""
|
||||
body = _turn_chain._attr(0x0006, user) + _turn_chain._attr(0x000D, struct.pack("!I", lifetime))
|
||||
return _turn_chain._message(0x0004, tid, body, _turn_chain.long_term_key(user.decode()))
|
||||
|
||||
|
||||
def signed_allocate(tid, user=b"lab"):
|
||||
return _turn_chain._message(0x0003, tid, _turn_chain._attr(0x0006, user), _turn_chain.long_term_key(user.decode()))
|
||||
|
||||
|
||||
def wait_for(condition, what):
|
||||
for _ in range(200):
|
||||
if condition():
|
||||
return
|
||||
time.sleep(0.025)
|
||||
raise AssertionError("never happened: " + what)
|
||||
|
||||
|
||||
class Client:
|
||||
"""A TURN client's socket (one 5-tuple) that talks to the lab's TURN server and tells the recorder what the gateway would have written."""
|
||||
|
||||
def __init__(self, lab):
|
||||
self.lab = lab
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.settimeout(5)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
|
||||
def send(self, datagram, message):
|
||||
before = len(self.lab.turn.requests)
|
||||
self.lab.gateway._route(_turn_chain.TURN_IP, _turn_chain.TURN_PORT, 1, datagram, 1, None) # the gateway writes the event, as it does for a browser's datagram
|
||||
self.sock.sendto(datagram, self.lab.turn.address)
|
||||
wait_for(lambda: len(self.lab.turn.requests) > before, "the lab TURN heard the datagram")
|
||||
self.sock.recvfrom(2048) # every request here is answered
|
||||
return self
|
||||
|
||||
def close(self):
|
||||
self.sock.close()
|
||||
|
||||
|
||||
def walk(label, script, times=None):
|
||||
"""The WebRTC walk of seed 4 on a lab, as ``run`` makes it, whose page does ``script(lab, clients)`` (the datagrams during the page, and at the close of the context, as the engine
|
||||
ends its allocations when the page closes), and the transcript of that seed."""
|
||||
clients = []
|
||||
|
||||
class Page:
|
||||
def goto(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def evaluate(self, js, arg):
|
||||
script(lab, clients, "page")
|
||||
result = {"candidates": [RELAY_CANDIDATE], "errors": [], "sdp": "v=0", "gathering": "complete"}
|
||||
return result if times is None else dict(result, times=times)
|
||||
|
||||
class Browser:
|
||||
def new_context(self, **kwargs):
|
||||
return types.SimpleNamespace(new_page=lambda: Page(), close=lambda: script(lab, clients, "close"))
|
||||
|
||||
try:
|
||||
with ab.Lab(host="127.0.0.1") as lab:
|
||||
out = ab.walk_webrtc(Browser(), lab)
|
||||
evidence = ab.webrtc_evidence(lab)
|
||||
finally:
|
||||
for client in clients:
|
||||
client.close()
|
||||
transcript = {"format": ab.FORMAT, "label": label, "platform": "linux", "seeds": {"4": {"webrtc": out}}}
|
||||
return transcript, evidence
|
||||
|
||||
|
||||
def allocation_then(*closing):
|
||||
"""A script: the allocation during the page, and ``closing`` (pairs of tid and lifetime sent from the allocation's own socket) when the context closes."""
|
||||
def script(lab, clients, stage):
|
||||
if stage == "page":
|
||||
clients.append(Client(lab).send(_turn_chain._message(0x0003, ALLOCATE, b""), "stun-0x0003"))
|
||||
clients[0].send(signed_allocate(ALLOCATE), "stun-0x0003")
|
||||
else:
|
||||
for tid, lifetime in closing:
|
||||
clients[0].send(signed_refresh(tid, lifetime), "stun-0x0004")
|
||||
return script
|
||||
|
||||
|
||||
def test_a_deallocation_seen_on_one_side_and_not_on_the_other_is_no_difference_of_the_walk():
|
||||
with_it, evidence_with = walk("a", allocation_then((REFRESH_A, 0)))
|
||||
without_it, evidence_without = walk("b", allocation_then())
|
||||
for transcript in (with_it, without_it):
|
||||
turn = transcript["seeds"]["4"]["webrtc"]["turn"]
|
||||
assert turn["messages"] == ["0x0003"], "the deallocation is not a message of the walk"
|
||||
assert transcript["seeds"]["4"]["webrtc"]["udp"]["counts"] == {ab.TURN_TARGET: 1}, "nor a transaction of the TURN address (the Allocate was one: its 401 and its retry share the id)"
|
||||
assert transcript["seeds"]["4"]["webrtc"]["udp"]["messages"] == {ab.TURN_TARGET: ["stun-0x0003"]}
|
||||
report = ab.compare_transcripts(with_it, without_it, [], 0, "a", "b")
|
||||
assert report["differences"] == [] and report["problems"] == [] and report["verdict"] == "green", report["problems"]
|
||||
assert evidence_with["deallocation"]["seen"] is True and evidence_without["deallocation"] == {"seen": False, "records": []}
|
||||
|
||||
|
||||
def test_a_refresh_with_a_lifetime_above_zero_stays_in_the_messages_and_in_the_count():
|
||||
kept, evidence = walk("a", allocation_then((REFRESH_A, 600)))
|
||||
walk_of = kept["seeds"]["4"]["webrtc"]
|
||||
assert walk_of["turn"]["messages"] == ["0x0003", "0x0004"] and walk_of["udp"]["counts"] == {ab.TURN_TARGET: 2}
|
||||
assert walk_of["udp"]["messages"] == {ab.TURN_TARGET: ["stun-0x0003", "stun-0x0004"]}
|
||||
assert evidence["deallocation"] == {"seen": False, "records": []}
|
||||
assert walk_of["turn"]["deallocation"] == {"repeated": 0, "unallocated": 0, "early": 0}
|
||||
gone, _ = walk("b", allocation_then())
|
||||
differing = [d["path"] for d in ab.compare_transcripts(kept, gone, [], 0, "a", "b")["differences"]]
|
||||
assert "seeds/4/webrtc/turn/messages/1" in differing and "seeds/4/webrtc/udp/counts/%s" % ab.TURN_TARGET in differing, "a keep-alive IS the engine's doing, and is compared"
|
||||
|
||||
|
||||
def test_the_deallocation_goes_to_the_evidence_with_its_time_and_its_transaction_id():
|
||||
transcript, evidence = walk("a", allocation_then((REFRESH_A, 0)))
|
||||
json.dumps(evidence)
|
||||
(record,) = evidence["deallocation"]["records"]
|
||||
assert evidence["deallocation"]["seen"] is True
|
||||
assert record["tid"] == REFRESH_A.hex() and record["allocation"] == 0 and record["src"].startswith("127.0.0.1:")
|
||||
assert isinstance(record["t"], float) and record["t"] >= evidence["phase_t"]["webrtc"], "the time is the recorder's, the one of the other evidence"
|
||||
assert [d["tid"] for d in evidence["datagrams"]].count(REFRESH_A.hex()) == 1, "the datagram itself is still in the evidence, as every datagram is"
|
||||
assert transcript["seeds"]["4"]["webrtc"]["turn"]["deallocation"] == {"repeated": 0, "unallocated": 0, "early": 0}
|
||||
|
||||
|
||||
def test_two_deallocations_of_one_allocation_are_a_problem_and_no_leaf(capsys):
|
||||
twice, _ = walk("b", allocation_then((REFRESH_A, 0), (REFRESH_B, 0)))
|
||||
once, _ = walk("a", allocation_then((REFRESH_A, 0)))
|
||||
assert twice["seeds"]["4"]["webrtc"]["turn"]["deallocation"] == {"repeated": 1, "unallocated": 0, "early": 0}
|
||||
assert twice["seeds"]["4"]["webrtc"]["turn"]["messages"] == ["0x0003"]
|
||||
report = ab.compare_transcripts(once, twice, [], 0, "a", "b")
|
||||
assert report["differences"] == [] and report["verdict"] == "red" and len(report["problems"]) == 1
|
||||
(line,) = report["problems"]
|
||||
assert line.startswith("seeds/4/webrtc: b: 1 allocation(s) of the lab TURN were ended by more than one deallocation") and ". Fix: " in line and line.endswith(RULE)
|
||||
ab.print_report(report, True)
|
||||
assert "FAIL " + line in capsys.readouterr().out
|
||||
assert ab.compare_transcripts(once, once, [], 0, "a", "a")["problems"] == []
|
||||
|
||||
|
||||
def test_a_deallocation_for_an_address_that_has_no_allocation_is_a_problem():
|
||||
def script(lab, clients, stage):
|
||||
if stage == "page":
|
||||
clients.append(Client(lab).send(signed_allocate(ALLOCATE), "stun-0x0003"))
|
||||
else:
|
||||
clients.append(Client(lab).send(signed_refresh(REFRESH_C, 0), "stun-0x0004")) # another socket: another address, which was never allocated
|
||||
|
||||
orphan, evidence = walk("b", script)
|
||||
assert orphan["seeds"]["4"]["webrtc"]["turn"]["deallocation"] == {"repeated": 0, "unallocated": 1, "early": 0}
|
||||
assert evidence["deallocation"]["records"][0]["allocation"] is None
|
||||
report = ab.compare_transcripts(orphan, orphan, [], 0, "a", "b")
|
||||
assert report["differences"] == [] and len(report["problems"]) == 2, "each side that did it is named"
|
||||
assert all("from an address that has no allocation. Fix: " in p and p.endswith(RULE) for p in report["problems"])
|
||||
assert [p.split(": ")[1] for p in report["problems"]] == ["a", "b"]
|
||||
|
||||
|
||||
def serve_one(request_after_allocation):
|
||||
"""A TurnServer on loopback that heard an allocation and then ``request_after_allocation`` from the same socket; what it recorded."""
|
||||
server = _turn_chain.TurnServer()
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.settimeout(5)
|
||||
try:
|
||||
client.sendto(signed_allocate(ALLOCATE), server.address)
|
||||
assert struct.unpack("!H", client.recvfrom(2048)[0][:2])[0] == 0x0103
|
||||
client.sendto(request_after_allocation, server.address)
|
||||
answer, _ = client.recvfrom(2048)
|
||||
port = client.getsockname()[1]
|
||||
finally:
|
||||
client.close()
|
||||
server.close()
|
||||
return server, answer, port
|
||||
|
||||
|
||||
def test_the_turn_server_records_a_signed_refresh_with_lifetime_zero_as_a_deallocation_and_answers_it_as_it_always_did():
|
||||
server, answer, port = serve_one(signed_refresh(REFRESH_A, 0))
|
||||
assert struct.unpack("!H", answer[:2])[0] == 0x0104, "the answer to a Refresh is what it was"
|
||||
assert server.deallocations == [("127.0.0.1", port, REFRESH_A, server.deallocations[0][3], 0)]
|
||||
assert server.deallocation_tids() == {REFRESH_A} and [r[2] for r in server.deallocation_transactions()] == [REFRESH_A]
|
||||
assert len(server.allocations) == 1 and server.refused == []
|
||||
|
||||
|
||||
def test_the_turn_server_does_not_record_a_refresh_with_lifetime_600_or_any_other_message_as_a_deallocation():
|
||||
server, answer, _ = serve_one(signed_refresh(REFRESH_A, 600))
|
||||
assert struct.unpack("!H", answer[:2])[0] == 0x0104 and server.deallocations == [] and server.deallocation_tids() == set()
|
||||
server, _, _ = serve_one(_turn_chain._message(0x0008, REFRESH_B, _turn_chain._attr(0x0006, b"lab") + _turn_chain._attr(0x000D, struct.pack("!I", 0)),
|
||||
_turn_chain.long_term_key("lab")))
|
||||
assert server.deallocations == [], "a lifetime of 0 in another message type (CreatePermission) is not a deallocation: the type counts too"
|
||||
server, _, _ = serve_one(signed_refresh(REFRESH_C, 0)[:20] + _turn_chain._attr(0x0006, b"lab"))
|
||||
assert server.deallocations == [], "a Refresh with no LIFETIME is not one"
|
||||
|
||||
|
||||
def test_the_gateway_marks_a_deallocation_from_its_payload_and_the_mark_alone_takes_it_out_of_the_count():
|
||||
"""The datagram can be at the gateway before the lab's TURN server has recorded it: the count does not wait for the server."""
|
||||
def script(lab, clients, stage):
|
||||
if stage == "page":
|
||||
clients.append(Client(lab).send(signed_allocate(ALLOCATE), "stun-0x0003"))
|
||||
else:
|
||||
for tid, lifetime in ((REFRESH_A, 600), (REFRESH_B, 0)):
|
||||
lab.gateway._route(_turn_chain.TURN_IP, _turn_chain.TURN_PORT, 1, signed_refresh(tid, lifetime), 1, None) # never sent to the server
|
||||
|
||||
transcript, _ = walk("a", script)
|
||||
walk_of = transcript["seeds"]["4"]["webrtc"]
|
||||
assert walk_of["udp"]["counts"] == {ab.TURN_TARGET: 2} and walk_of["udp"]["messages"] == {ab.TURN_TARGET: ["stun-0x0003", "stun-0x0004"]}, "the 600 stays, the 0 goes, by the mark"
|
||||
with ab.Lab(host="127.0.0.1") as lab:
|
||||
lab.rec.set_phase("webrtc")
|
||||
for tid, lifetime in ((REFRESH_A, 600), (REFRESH_B, 0)):
|
||||
lab.gateway._route(_turn_chain.TURN_IP, _turn_chain.TURN_PORT, 1, signed_refresh(tid, lifetime), 1, None)
|
||||
lab.gateway._route("127.0.0.1", 5555, 1, signed_refresh(REFRESH_C, 0), 1, None)
|
||||
events = lab.rec.of("webrtc", "udp")
|
||||
assert [e["deallocation"] for e in events] == [False, True, True], "marked by meaning, whoever the datagram is for (the walk counts only the TURN address's)"
|
||||
|
||||
|
||||
def test_a_deallocation_before_the_page_began_closing_is_a_problem_and_one_after_it_is_not():
|
||||
"""The page's own times on the recorder's clock: the call of the page plus (closing - start) of its performance.now() is the moment it began closing (``closing_began``)."""
|
||||
def at_page(lab, clients, stage):
|
||||
if stage == "page":
|
||||
clients.append(Client(lab).send(signed_allocate(ALLOCATE), "stun-0x0003"))
|
||||
clients[0].send(signed_refresh(REFRESH_A, 0), "stun-0x0004") # the deallocation comes while the page is still open
|
||||
before, _ = walk("b", at_page, times={"start": 100.0, "closing": 100.0 + 600000.0}) # the page closes ten minutes after the call
|
||||
assert before["seeds"]["4"]["webrtc"]["turn"]["deallocation"] == {"repeated": 0, "unallocated": 0, "early": 1}
|
||||
report = ab.compare_transcripts(before, before, [], 0, "a", "b")
|
||||
assert report["differences"] == [] and len(report["problems"]) == 2 and all(p.endswith(RULE) for p in report["problems"])
|
||||
assert all("reached the lab TURN before the page began closing its connection. Fix: " in p for p in report["problems"])
|
||||
|
||||
after, _ = walk("b", allocation_then((REFRESH_A, 0)), times={"start": 100.0, "closing": 100.0}) # closing at the start: the call itself is the bound
|
||||
assert after["seeds"]["4"]["webrtc"]["turn"]["deallocation"] == {"repeated": 0, "unallocated": 0, "early": 0}
|
||||
assert ab.compare_transcripts(after, after, [], 0, "a", "b")["problems"] == []
|
||||
assert ab.closing_began(5.0, {"start": 250.0, "closing": 1750.0}) == 6.5 and ab.closing_began(5.0, None) is None and ab.closing_began(5.0, {"start": 1.0}) is None
|
||||
@@ -0,0 +1,594 @@
|
||||
"""The WebRTC walk of the network oracle keeps its evidence OUTSIDE the leaves that are compared, and the hunt repeats that walk alone (scripts/ci_ab_network.py), no browser.
|
||||
|
||||
The A/A of the oracle found the published engine sending 8 or 9 TURN Allocate datagrams to 198.51.100.7:3478 in the WebRTC walk of one seed. The two readings are told apart by
|
||||
what each datagram carried and when: a STUN transaction id repeats on a retransmission, and the page's own ICE times and the moments of the stages say where the close fell. This file holds
|
||||
that evidence to its rules: it is in ``transcript["evidence"]`` (which ``compare_transcripts`` never reads), what the page returns for the compared fields is what it returned before, the
|
||||
transaction id comes from the header of the datagram, the gateway's summary is the one it was, and the hunt (``AB_NETWORK_HUNT=webrtc:<seed>:<n>``, wired into e2e-hunt.yml) writes one file
|
||||
per repetition and a summary and decides nothing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
import ci_ab_network as ab # noqa: E402
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import _turn_chain # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HUNT_WORKFLOW = ROOT / ".github" / "workflows" / "e2e-hunt.yml"
|
||||
|
||||
COOKIE = b"\x21\x12\xa4\x42"
|
||||
TID = bytes(range(1, 13))
|
||||
|
||||
|
||||
def stun(message_type: int, tid: bytes = TID) -> bytes:
|
||||
"""A STUN header (RFC 8489): type, length 0, the magic cookie and a 12-byte transaction id."""
|
||||
return message_type.to_bytes(2, "big") + b"\x00\x00" + COOKIE + tid
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the transaction id
|
||||
def test_the_transaction_id_is_bytes_8_to_20_of_a_stun_header():
|
||||
allocate = stun(0x0003)
|
||||
assert len(allocate) == 20
|
||||
assert ab.stun_tid(allocate) == TID.hex() == "0102030405060708090a0b0c"
|
||||
assert ab.stun_tid(allocate + b"\x00\x06\x00\x04lab\x00") == TID.hex(), "the attributes after the header change nothing"
|
||||
assert ab.stun_tid(stun(0x0113, b"\xff" * 12)) == "ff" * 12
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [b"", b"\xc3" + b"\x00" * 40, b"\x40" + b"\x01" * 30, b"\x00\x03\x00\x00" + b"\x00" * 16, stun(0x0003)[:19], b"hello world" * 3])
|
||||
def test_a_datagram_that_is_not_stun_has_no_transaction_id(payload):
|
||||
assert ab.stun_tid(payload) is None
|
||||
|
||||
|
||||
def test_the_gateway_writes_the_transaction_id_of_each_datagram_and_the_summary_of_the_phase_does_not_change():
|
||||
from _doh_servers import FakeDoh
|
||||
from _turn_chain import TURN_IP, TURN_PORT
|
||||
|
||||
assert "%s:%d" % (TURN_IP, TURN_PORT) == ab.TURN_TARGET, "the target the hunt counts is the TURN server of the lab"
|
||||
gateway_class, turn_class, _page = ab.make_lab_classes()
|
||||
rec = ab.Recorder()
|
||||
doh = FakeDoh({})
|
||||
turn = turn_class("127.0.0.1")
|
||||
gateway = gateway_class(rec, doh, turn, "127.0.0.1", "198.51.100.9")
|
||||
try:
|
||||
rec.set_phase("webrtc")
|
||||
gateway._route(TURN_IP, TURN_PORT, 1, stun(0x0003), 1, None)
|
||||
gateway._route(TURN_IP, TURN_PORT, 1, stun(0x0003), 1, None)
|
||||
gateway._route(TURN_IP, TURN_PORT, 1, stun(0x0003, b"\x09" * 12), 1, None)
|
||||
gateway._route("127.0.0.1", 5555, 1, b"\xc3" + b"\x00" * 20, 1, None)
|
||||
finally:
|
||||
gateway.close()
|
||||
turn.close()
|
||||
doh.close()
|
||||
events = rec.of("webrtc", "udp")
|
||||
assert [(e["target"], e["message"], e["tid"]) for e in events] == [
|
||||
(ab.TURN_TARGET, "stun-0x0003", TID.hex()), (ab.TURN_TARGET, "stun-0x0003", TID.hex()), (ab.TURN_TARGET, "stun-0x0003", "09" * 12), ("127.0.0.1:5555", "quic-long", None)]
|
||||
norm = ab.Normalizer({})
|
||||
# the count is of TRANSACTIONS: the first Allocate was sent twice (one transaction), the second once, and the QUIC datagram has no transaction id (one)
|
||||
assert ab.udp_summary(events, norm)["counts"] == {ab.TURN_TARGET: 2, "127.0.0.1:5555": 1}
|
||||
without = [{k: v for k, v in e.items() if k != "tid"} for e in events]
|
||||
assert ab.udp_summary(without, norm)["counts"] == {ab.TURN_TARGET: 3, "127.0.0.1:5555": 1}, "with no transaction id every datagram counts one"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the evidence key
|
||||
def lab_with(rec, **webrtc):
|
||||
return types.SimpleNamespace(rec=rec, webrtc=webrtc)
|
||||
|
||||
|
||||
def recorded_walk():
|
||||
"""A recorder that went through the stages of the walk, with the datagrams a TURN server's client sends: the first Allocate three times, the authenticated one twice, one late."""
|
||||
rec = ab.Recorder()
|
||||
rec.set_phase("webrtc")
|
||||
for target, message, tid in [(ab.TURN_TARGET, "stun-0x0003", "aa" * 12), (ab.TURN_TARGET, "stun-0x0003", "aa" * 12), ("198.51.100.5:19302", "stun-0x0001", "bb" * 12),
|
||||
(ab.TURN_TARGET, "stun-0x0003", "cc" * 12), ("127.0.0.1:5555", "quic-long", None)]:
|
||||
rec.event("udp", target=target, message=message, tid=tid, opener=None)
|
||||
counted = len(rec.of("webrtc", "udp"))
|
||||
rec.set_phase("webrtc.end")
|
||||
rec.event("udp", target=ab.TURN_TARGET, message="stun-0x0003", tid="cc" * 12, opener=None)
|
||||
return rec, counted
|
||||
|
||||
|
||||
def test_the_evidence_of_the_walk_lists_every_datagram_with_its_time_target_message_and_transaction_and_the_moments_of_the_stages():
|
||||
rec, counted = recorded_walk()
|
||||
page = {"start": 1.0, "offer": 2.0, "candidates": [{"t": 3.0, "type": "host"}], "errors": [{"t": 4.0, "code": 701, "url": "turn:x"}], "gathered": 5.0, "closing": 6.0, "closed": 6.5}
|
||||
evidence = ab.webrtc_evidence(lab_with(rec, counted=counted, evaluate={"called": 0.5, "returned": 7.0}, page=page))
|
||||
json.dumps(evidence)
|
||||
assert set(evidence) == {"phase_t", "evaluate", "page", "datagrams", "turn", "returned", "send_errors", "deallocation"}
|
||||
assert evidence["page"] == page and evidence["evaluate"] == {"called": 0.5, "returned": 7.0}
|
||||
assert set(evidence["phase_t"]) == {"webrtc", "webrtc.end"} and evidence["phase_t"]["webrtc"] <= evidence["phase_t"]["webrtc.end"]
|
||||
datagrams = evidence["datagrams"]
|
||||
assert [(d["target"], d["message"], d["tid"], d["phase"], d["counted"]) for d in datagrams] == [
|
||||
(ab.TURN_TARGET, "stun-0x0003", "aa" * 12, "webrtc", True), (ab.TURN_TARGET, "stun-0x0003", "aa" * 12, "webrtc", True), ("198.51.100.5:19302", "stun-0x0001", "bb" * 12, "webrtc", True),
|
||||
(ab.TURN_TARGET, "stun-0x0003", "cc" * 12, "webrtc", True), ("127.0.0.1:5555", "quic-long", None, "webrtc", True),
|
||||
(ab.TURN_TARGET, "stun-0x0003", "cc" * 12, "webrtc.end", False)]
|
||||
assert all(isinstance(d["t"], float) for d in datagrams) and [d["t"] for d in datagrams] == sorted(d["t"] for d in datagrams)
|
||||
|
||||
|
||||
def test_the_evidence_of_the_walk_leaves_out_the_datagrams_of_other_stages_and_says_nothing_when_the_walk_never_ran():
|
||||
rec = ab.Recorder()
|
||||
rec.set_phase("h3")
|
||||
rec.event("udp", target="127.0.0.1:1", message="quic-long", tid=None, opener=None)
|
||||
empty = ab.webrtc_evidence(lab_with(rec))
|
||||
assert empty == {"phase_t": {"webrtc": None, "webrtc.end": None}, "evaluate": None, "page": None, "datagrams": [], "turn": [], "returned": [], "send_errors": [], "deallocation": {"seen": False, "records": []}}
|
||||
|
||||
|
||||
def evidence_transcript(label, datagrams):
|
||||
"""A transcript as ``run`` writes it: ``seeds`` (compared) and ``evidence`` (not), with the webrtc evidence of a real recorder in it."""
|
||||
rec = ab.Recorder()
|
||||
rec.set_phase("webrtc")
|
||||
for tid in datagrams:
|
||||
rec.event("udp", target=ab.TURN_TARGET, message="stun-0x0003", tid=tid, opener=None)
|
||||
rec.set_phase("webrtc.end")
|
||||
evidence = ab.webrtc_evidence(lab_with(rec, counted=len(datagrams), page={"gathered": float(len(datagrams))}))
|
||||
return {"format": ab.FORMAT, "label": label, "platform": "linux",
|
||||
"seeds": {"4": {"webrtc": {"candidates": ["udp comp1 prio1 srflx <exit>"], "candidate_types": ["relay", "srflx"], "gathering": "complete", "udp": {"counts": {ab.TURN_TARGET: 8}}}}},
|
||||
"evidence": {"format": ab.EVIDENCE_FORMAT, "seeds": {"4": {"journey": [], "https": {}, "h3": [], "webrtc": evidence}}}}
|
||||
|
||||
|
||||
def test_two_transcripts_that_differ_only_in_the_evidence_of_the_walk_have_no_difference():
|
||||
a = evidence_transcript("a", ["aa" * 12] * 8)
|
||||
b = evidence_transcript("b", ["aa" * 12] * 7 + ["bb" * 12, "cc" * 12])
|
||||
assert a["evidence"] != b["evidence"] and a["seeds"] == b["seeds"]
|
||||
report = ab.compare_transcripts(a, b, [], 0, "a", "b")
|
||||
assert report["differences"] == [] and report["problems"] == [] and report["verdict"] == "green"
|
||||
assert report["leaves"] == ab.compare_transcripts(a, a, [], 0, "a", "a")["leaves"]
|
||||
assert ab.flatten(a["seeds"]).keys().isdisjoint({p for p in ab.flatten(a["evidence"]["seeds"], "evidence")}), "no leaf of the evidence is a leaf of the seeds"
|
||||
# and the same difference in the compared part IS one: the control of the test above
|
||||
c = json.loads(json.dumps(a))
|
||||
c["seeds"]["4"]["webrtc"]["udp"]["counts"][ab.TURN_TARGET] = 9
|
||||
assert [d["path"] for d in ab.compare_transcripts(a, c, [], 0, "a", "c")["differences"]] == ["seeds/4/webrtc/udp/counts/198.51.100.7:3478"]
|
||||
|
||||
|
||||
def test_a_run_writes_the_evidence_of_the_walk_under_the_evidence_of_its_seed(tmp_path, monkeypatch):
|
||||
import _lab_egress
|
||||
import ci_crash_evidence as crash
|
||||
|
||||
def walk_seed(binary, seed, with_idle, patch):
|
||||
ab.EVIDENCE[str(seed)] = evidence_transcript("x", ["aa" * 12] * 2)["evidence"]["seeds"]["4"]
|
||||
return {"webrtc": {}}
|
||||
|
||||
monkeypatch.setattr(ab, "walk_seed", walk_seed)
|
||||
monkeypatch.setattr(_lab_egress, "install", lambda patch, work: None)
|
||||
monkeypatch.setenv(crash.CRASH_DIR_ENV, str(tmp_path / "t.crash"))
|
||||
try:
|
||||
assert ab.run("/e/firefox", "firefox-68", (4,), tmp_path / "t.json") == 0
|
||||
finally:
|
||||
crash.stop_probe()
|
||||
document = json.loads((tmp_path / "t.json").read_text(encoding="utf-8"))
|
||||
assert [d["tid"] for d in document["evidence"]["seeds"]["4"]["webrtc"]["datagrams"]] == ["aa" * 12] * 2
|
||||
assert set(document) >= {"seeds", "evidence", "exits"} and "webrtc" not in document["evidence"], "the evidence is under the seed, not beside the seeds"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the page's probe
|
||||
def test_the_probe_returns_what_it_returned_and_its_times_beside_it():
|
||||
js = ab.RTC_JS
|
||||
assert "return {candidates: cands, errors, sdp, gathering, times: T};" in js, "the four fields that are compared come first and unchanged; `times` is the only addition"
|
||||
assert "cands.push(e.candidate.candidate)" in js and "errors.push({code: e.errorCode, url: e.url})" in js
|
||||
for what in ("T.offer = performance.now()", "T.gathered = performance.now()", "T.closing = performance.now()", "T.closed = performance.now()"):
|
||||
assert what in js, what
|
||||
assert re.search(r"T\.candidates\.push\(\{t: performance\.now\(\), type: ", js), "each icecandidate, with its type"
|
||||
assert re.search(r"T\.errors\.push\(\{t: performance\.now\(\), code: e\.errorCode, url: e\.url\}\)", js), "each icecandidateerror, with its code and url"
|
||||
assert js.index("T.closing = performance.now()") < js.index("pc.close()") < js.index("T.closed = performance.now()"), "the close is bracketed by its two times"
|
||||
|
||||
|
||||
def test_what_the_page_measures_of_itself_is_in_the_evidence_and_the_summary_of_the_walk_is_the_same_with_any_times():
|
||||
class Page:
|
||||
def __init__(self, result):
|
||||
self.result = result
|
||||
|
||||
def goto(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def evaluate(self, js, arg):
|
||||
assert js == ab.RTC_JS and arg == [ab.STUN_URL, ab.TURN_URL, ab.TURN_USERNAME, _turn_chain.PASSWORD]
|
||||
return json.loads(json.dumps(self.result))
|
||||
|
||||
class Browser:
|
||||
def __init__(self, result):
|
||||
self.page = Page(result)
|
||||
|
||||
def new_context(self, **kwargs):
|
||||
return types.SimpleNamespace(new_page=lambda: self.page, close=lambda: None)
|
||||
|
||||
base = {"candidates": ["candidate:1 1 udp 100 192.0.2.1 5000 typ host"], "errors": [{"code": 701, "url": "turn:198.51.100.7:3478"}], "sdp": "v=0\r\n", "gathering": "complete"}
|
||||
outs, labs = [], []
|
||||
for times in ({"start": 1.0, "gathered": 2.0}, {"start": 5.5, "gathered": 9.25, "closed": 11.0}, None):
|
||||
result = dict(base) if times is None else dict(base, times=times)
|
||||
with ab.Lab(host="127.0.0.1") as lab:
|
||||
outs.append(json.dumps(ab.walk_webrtc(Browser(result), lab), sort_keys=True))
|
||||
labs.append(lab.webrtc)
|
||||
assert outs[0] == outs[1] == outs[2], "the walk's summary does not depend on the page's times"
|
||||
assert '"times"' not in outs[0] and "gathered" not in outs[0]
|
||||
assert [x["page"] for x in labs] == [{"start": 1.0, "gathered": 2.0}, {"start": 5.5, "gathered": 9.25, "closed": 11.0}, None]
|
||||
assert all(x["evaluate"]["called"] <= x["evaluate"]["returned"] for x in labs) and all(isinstance(x["counted"], int) for x in labs)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the TURN server's answers and the relay's return path
|
||||
def signed_allocate(tid, user=b"lab"):
|
||||
"""An Allocate with USERNAME and the MESSAGE-INTEGRITY of the long-term key (the server of the lab checks it)."""
|
||||
from _turn_chain import _attr, _message, long_term_key
|
||||
|
||||
return _message(0x0003, tid, _attr(0x0006, user), long_term_key(user.decode()))
|
||||
|
||||
|
||||
def test_the_turn_server_of_the_lab_writes_every_request_with_what_it_carried_and_every_answer_with_where_it_went_and_answers_as_it_always_did():
|
||||
import socket
|
||||
|
||||
from _turn_chain import RELAYED, TurnServer
|
||||
|
||||
_gateway, turn_class, _page = ab.make_lab_classes()
|
||||
turn = turn_class("127.0.0.1")
|
||||
assert isinstance(turn, TurnServer) and isinstance(turn.sock, ab.ExchangeSocket)
|
||||
ticks = iter(x / 10 for x in range(1, 100))
|
||||
turn.clock = lambda: next(ticks)
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.settimeout(5)
|
||||
client.bind(("127.0.0.1", 0))
|
||||
first, second = b"\x01" * 12, b"\x02" * 12
|
||||
try:
|
||||
client.sendto(stun(0x0003, first), turn.address)
|
||||
unauthorized, _ = client.recvfrom(2048)
|
||||
client.sendto(signed_allocate(second), turn.address)
|
||||
success, _ = client.recvfrom(2048)
|
||||
client.sendto(b"not stun at all, twenty-odd bytes", turn.address)
|
||||
client.sendto(stun(0x0001, b"\x03" * 12), turn.address) # a Binding request: the server of the lab does not answer it
|
||||
port = client.getsockname()[1]
|
||||
for _ in range(100):
|
||||
if len(turn.exchanges) == 3:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
finally:
|
||||
client.close()
|
||||
turn.close()
|
||||
assert int.from_bytes(unauthorized[:2], "big") == 0x0113 and int.from_bytes(success[:2], "big") == 0x0103, "what the server answers is what it answered"
|
||||
assert len(turn.seen) == 3 and [a[2] for a in turn.allocations] == ["lab"] and turn.allocations[0][:2] == ("127.0.0.1", port)
|
||||
one, two, three = turn.exchanges
|
||||
json.dumps(turn.exchanges)
|
||||
assert (one["t"], one["src"], one["tid"], one["type"], one["username"], one["integrity"]) == (0.1, "127.0.0.1:%d" % port, first.hex(), "0x0003", False, False)
|
||||
assert one["responses"] == [{"t": 0.2, "tid": first.hex(), "type": "0x0113", "to": "127.0.0.1:%d" % port, "relayed": None, "mapped": None, "error": 401}]
|
||||
assert (two["tid"], two["type"], two["username"], two["integrity"]) == (second.hex(), "0x0003", True, True)
|
||||
(answer,) = two["responses"]
|
||||
assert answer["type"] == "0x0103" and answer["to"] == "127.0.0.1:%d" % port and answer["error"] is None
|
||||
assert answer["relayed"] == "%s:%d" % RELAYED and answer["mapped"] == "127.0.0.1:%d" % port, "the XOR-RELAYED-ADDRESS and XOR-MAPPED-ADDRESS the server put in, decoded"
|
||||
assert (three["type"], three["responses"]) == ("0x0001", []), "a request the server does not answer has no answer in its record"
|
||||
|
||||
|
||||
def test_a_failure_of_the_record_never_reaches_the_server():
|
||||
class Owner:
|
||||
exchanges = None # append on None: the record fails
|
||||
|
||||
def clock(self):
|
||||
raise RuntimeError("no clock")
|
||||
|
||||
class Raw:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def recvfrom(self, size):
|
||||
return stun(0x0003), ("127.0.0.1", 9)
|
||||
|
||||
def sendto(self, data, address):
|
||||
self.sent.append((data, address))
|
||||
return len(data)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
raw = Raw()
|
||||
sock = ab.ExchangeSocket(raw, Owner())
|
||||
assert sock.recvfrom(10) == (stun(0x0003), ("127.0.0.1", 9))
|
||||
assert sock.sendto(stun(0x0113), ("127.0.0.1", 9)) == 20 and raw.sent == [(stun(0x0113), ("127.0.0.1", 9))]
|
||||
sock.close()
|
||||
assert raw.closed is True
|
||||
|
||||
|
||||
def test_an_xor_address_is_decoded_and_an_answer_with_no_request_has_a_record_of_its_own():
|
||||
from _turn_chain import _attr, _xor_addr
|
||||
|
||||
assert ab.xor_address(_xor_addr("198.51.100.7", 50000)) == "198.51.100.7:50000"
|
||||
assert ab.xor_address(None) is None and ab.xor_address(b"\x00\x02" + b"\x00" * 18) is None
|
||||
assert ab.stun_attributes(stun(0x0003) + _attr(0x0006, b"lab") + _attr(0x0008, b"\x00" * 20)) == {0x0006: b"lab", 0x0008: b"\x00" * 20}
|
||||
assert ab.stun_attributes(stun(0x0003) + b"\x00\x06\x00\x40ab") == {}, "a truncated attribute says nothing"
|
||||
owner = types.SimpleNamespace(exchanges=[], clock=lambda: 1.5)
|
||||
ab.ExchangeSocket(types.SimpleNamespace(sendto=lambda data, address: 0), owner).sendto(stun(0x0113, b"\x07" * 12), ("127.0.0.1", 5))
|
||||
assert owner.exchanges == [{"t": 1.5, "src": None, "tid": "07" * 12, "type": None, "username": None, "integrity": None,
|
||||
"responses": [{"t": 1.5, "tid": "07" * 12, "type": "0x0113", "to": "127.0.0.1:5", "relayed": None, "mapped": None, "error": None}]}]
|
||||
|
||||
|
||||
def test_the_relay_writes_each_datagram_it_sends_back_with_the_address_it_claims_and_the_five_tuple_it_goes_to_and_still_sends_it():
|
||||
import socket
|
||||
import struct
|
||||
|
||||
from _doh_servers import FakeDoh
|
||||
|
||||
gateway_class, turn_class, _page = ab.make_lab_classes()
|
||||
rec = ab.Recorder()
|
||||
doh = FakeDoh({})
|
||||
turn = turn_class("127.0.0.1")
|
||||
gateway = gateway_class(rec, doh, turn, "127.0.0.1", "198.51.100.9")
|
||||
receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
receiver.settimeout(5)
|
||||
receiver.bind(("127.0.0.1", 0))
|
||||
relay = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
relay.bind(("127.0.0.1", 0))
|
||||
try:
|
||||
rec.set_phase("webrtc")
|
||||
gateway._deliver(relay, receiver.getsockname(), "198.51.100.7", 3478, stun(0x0103, b"\x05" * 12))
|
||||
gateway._deliver(relay, receiver.getsockname(), "198.51.100.5", 19302, b"\xc3" + b"\x00" * 5)
|
||||
first, _ = receiver.recvfrom(2048)
|
||||
second, _ = receiver.recvfrom(2048)
|
||||
relay_address = relay.getsockname()
|
||||
client_address = receiver.getsockname()
|
||||
finally:
|
||||
receiver.close()
|
||||
relay.close()
|
||||
gateway.close()
|
||||
turn.close()
|
||||
doh.close()
|
||||
assert first == b"\x00\x00\x00\x01" + socket.inet_aton("198.51.100.7") + struct.pack("!H", 3478) + stun(0x0103, b"\x05" * 12), "the datagram is sent as it always was"
|
||||
assert second.endswith(b"\xc3" + b"\x00" * 5)
|
||||
back = rec.of("webrtc", "udp_back")
|
||||
assert [(e["claimed"], e["to"], e["relay"], e["message"], e["tid"]) for e in back] == [
|
||||
("198.51.100.7:3478", "%s:%d" % client_address, "%s:%d" % relay_address, "stun-0x0103", "05" * 12),
|
||||
("198.51.100.5:19302", "%s:%d" % client_address, "%s:%d" % relay_address, "quic-long", None)]
|
||||
assert rec.of("webrtc", "udp") == [], "a datagram back is not a datagram of the browser: the compared UDP summary does not see it"
|
||||
|
||||
|
||||
def test_the_evidence_keeps_the_turn_exchanges_of_the_walk_and_the_return_datagrams_and_the_gateways_send_errors():
|
||||
rec = ab.Recorder()
|
||||
rec.set_phase("webrtc")
|
||||
rec.event("udp_back", claimed="198.51.100.7:3478", to="127.0.0.1:40000", relay="127.0.0.1:41000", message="stun-0x0103", tid="aa" * 12)
|
||||
rec.set_phase("webrtc.end")
|
||||
rec.phase_t["webrtc"] = 5.0 # the stage began at 5 s on the recorder's clock
|
||||
before = {"t": 1.0, "src": "x:1", "tid": "00" * 12, "type": "0x0003", "username": False, "integrity": False, "responses": []}
|
||||
inside = {"t": 5.5, "src": "127.0.0.1:40000", "tid": "aa" * 12, "type": "0x0003", "username": True, "integrity": True, "responses": []}
|
||||
lab = types.SimpleNamespace(rec=rec, webrtc={}, turn=types.SimpleNamespace(exchanges=[before, inside]), gateway=types.SimpleNamespace(send_errors=["the answer to the client: OSError x"]))
|
||||
evidence = ab.webrtc_evidence(lab)
|
||||
json.dumps(evidence)
|
||||
assert evidence["turn"] == [inside], "the exchanges of the walk, not what the server heard before its stage"
|
||||
assert [(e["claimed"], e["to"], e["relay"], e["tid"], e["phase"]) for e in evidence["returned"]] == [("198.51.100.7:3478", "127.0.0.1:40000", "127.0.0.1:41000", "aa" * 12, "webrtc")]
|
||||
assert evidence["send_errors"] == ["the answer to the client: OSError x"]
|
||||
|
||||
|
||||
def test_a_lab_gives_its_turn_server_the_clock_of_its_recorder():
|
||||
with ab.Lab(host="127.0.0.1") as lab:
|
||||
assert lab.turn.clock == lab.rec.now and lab.turn.exchanges == []
|
||||
|
||||
|
||||
def test_a_hunt_repetition_launches_the_engine_with_its_own_log_and_the_variables_are_gone_after(tmp_path, monkeypatch):
|
||||
import os
|
||||
|
||||
seen = []
|
||||
|
||||
def launch(binary, seed, lab, patch):
|
||||
seen.append((os.environ.get("MOZ_LOG"), os.environ.get("MOZ_LOG_FILE")))
|
||||
raise RuntimeError("stop here")
|
||||
|
||||
monkeypatch.setattr(ab, "launch", launch)
|
||||
monkeypatch.setattr(ab, "begin_launch", lambda seed, name: None)
|
||||
monkeypatch.delenv("MOZ_LOG", raising=False)
|
||||
monkeypatch.delenv("MOZ_LOG_FILE", raising=False)
|
||||
patch = pytest.MonkeyPatch()
|
||||
try:
|
||||
record = ab.hunt_repetition("/e/firefox", "firefox-68-again", 7, 4, patch, tmp_path)
|
||||
assert "MOZ_LOG" not in os.environ and "MOZ_LOG_FILE" not in os.environ, "the variables are the launch's: a repetition leaves none"
|
||||
without = ab.hunt_repetition("/e/firefox", "firefox-68", 1, 4, patch)
|
||||
finally:
|
||||
patch.undo()
|
||||
assert seen == [("sync,timestamp,nicer:5,signaling:5", str(tmp_path / "firefox-68-again-7-mozlog")), (None, None)] and ab.HUNT_MOZ_LOG == "sync,timestamp,nicer:5,signaling:5"
|
||||
assert record["mozlog"] == "firefox-68-again-7-mozlog" and "mozlog" not in without
|
||||
|
||||
|
||||
def test_the_run_of_a_normal_a_a_does_not_log_the_engine():
|
||||
import inspect
|
||||
|
||||
for function in (ab.run_main, ab.run, ab.run_engine, ab.launch, ab.engine_env):
|
||||
assert "HUNT_MOZ_LOG" not in inspect.getsource(function) and "setenv" not in inspect.getsource(function), function.__name__
|
||||
assert "MOZ_LOG" in inspect.getsource(ab.engine_env), "an engine's own environment still has the log variables taken out: only the hunt's repetition sets them"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the hunt
|
||||
def repetition(engine, i, tids, late=0, error=None):
|
||||
"""A repetition file as ``hunt_repetition`` writes it: ``tids`` are the transaction ids of the datagrams to the TURN server in order, the first ``late`` of the last ones after the close."""
|
||||
datagrams = [{"t": 0.1 * n, "phase": "webrtc.end" if n >= len(tids) - late else "webrtc", "target": ab.TURN_TARGET, "message": "stun-0x0003", "tid": tid, "counted": n < len(tids) - late}
|
||||
for n, tid in enumerate(tids)]
|
||||
datagrams.append({"t": 0.05, "phase": "webrtc", "target": "198.51.100.5:19302", "message": "stun-0x0001", "tid": "dd" * 12, "counted": True})
|
||||
record = {"format": ab.HUNT_FORMAT, "engine": engine, "i": i, "seed": 4, "error": error, "evidence": {"phase_t": {}, "evaluate": None, "page": None, "datagrams": datagrams}}
|
||||
record["counts"] = ab.hunt_counts(record["evidence"])
|
||||
return record
|
||||
|
||||
|
||||
def test_the_hunt_summary_counts_the_datagrams_to_the_turn_server_and_lists_the_transactions_of_each_target():
|
||||
a, b = "aa" * 12, "bb" * 12
|
||||
records = [repetition("firefox-68", 1, [a, a, a, b, b]), repetition("firefox-68", 2, [a, a, b, b, b, b], late=1), repetition("firefox-68-again", 1, [a] * 4 + [b] * 4),
|
||||
repetition("firefox-68-again", 2, [], error="Error: launch")]
|
||||
summary = ab.hunt_summary(records)
|
||||
json.dumps(summary)
|
||||
assert summary["format"] == ab.HUNT_SUMMARY_FORMAT and summary["target"] == "198.51.100.7:3478"
|
||||
first, second, third, failed = summary["repetitions"]
|
||||
assert (first["engine"], first["i"], first["count_3478"], first["count_3478_all"]) == ("firefox-68", 1, 5, 5)
|
||||
assert first["targets"] == {"198.51.100.5:19302": [["dd" * 12, 1]], ab.TURN_TARGET: [[a, 3], [b, 2]]}
|
||||
assert (second["count_3478"], second["count_3478_all"]) == (5, 6), "a datagram after the close is in `all` and not in the count the A/A makes"
|
||||
assert second["targets"][ab.TURN_TARGET] == [[a, 2], [b, 4]]
|
||||
assert (third["count_3478"], third["targets"][ab.TURN_TARGET]) == (8, [[a, 4], [b, 4]])
|
||||
assert failed["error"] == "Error: launch" and failed["count_3478"] == 0
|
||||
assert summary["count_3478_by_engine"] == {"firefox-68": {"5": 2}, "firefox-68-again": {"0": 1, "8": 1}}
|
||||
|
||||
|
||||
def test_the_hunt_summary_is_read_from_the_repetition_files_and_does_not_read_itself(tmp_path):
|
||||
for record in (repetition("firefox-68-again", 2, ["aa" * 12]), repetition("firefox-68", 10, ["aa" * 12]), repetition("firefox-68", 2, ["aa" * 12] * 2)):
|
||||
ab.write_json(tmp_path / ("%s-%d.json" % (record["engine"], record["i"])), record)
|
||||
ab.write_json(tmp_path / "summary.json", ab.hunt_summary(ab.read_hunt_records(tmp_path)))
|
||||
(tmp_path / "notes.txt").write_text("not json", encoding="utf-8")
|
||||
records = ab.read_hunt_records(tmp_path)
|
||||
assert [(r["engine"], r["i"]) for r in records] == [("firefox-68", 2), ("firefox-68", 10), ("firefox-68-again", 2)], "by engine, then by number (10 after 2)"
|
||||
assert len(ab.hunt_summary(records)["repetitions"]) == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text, expected", [("webrtc:4:20", ("webrtc", 4, 20)), (" webrtc:11:1 ", ("webrtc", 11, 1))])
|
||||
def test_the_hunt_spec_names_the_walk_the_seed_and_the_count(text, expected):
|
||||
assert ab.parse_hunt(text) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "webrtc", "webrtc:4", "webrtc:four:3", "webrtc:4:0", "webrtc:4:-1", "h3:4:3", "webrtc:4:3:1", "4:3"])
|
||||
def test_a_hunt_spec_that_does_not_read_is_refused(text):
|
||||
with pytest.raises(ValueError, match=ab.HUNT_ENV):
|
||||
ab.parse_hunt(text)
|
||||
|
||||
|
||||
|
||||
def test_ab_with_the_hunt_variable_runs_only_the_walk_n_times_for_each_engine_of_the_a_a_and_exits_0(tmp_path, monkeypatch, capsys):
|
||||
calls = []
|
||||
|
||||
def hunt_engine(binary, seal, label, seed, n, out_dir):
|
||||
calls.append((binary, seal, label, seed, n))
|
||||
for i in range(1, n + 1):
|
||||
ab.write_json(out_dir / ("%s-%d.json" % (label, i)), repetition(label, i, ["aa" * 12] * (8 + i % 2)))
|
||||
return 0
|
||||
|
||||
def never(*a, **k):
|
||||
raise AssertionError("the A/A, the A/B and the volatile list are not part of a hunt")
|
||||
|
||||
monkeypatch.setattr(ab, "hunt_engine", hunt_engine)
|
||||
monkeypatch.setattr(ab, "run_engine", never)
|
||||
monkeypatch.setattr(ab, "compare_files", never)
|
||||
monkeypatch.setenv(ab.HUNT_ENV, "webrtc:4:3")
|
||||
assert ab.main(["ab", "--a-a", "--out", str(tmp_path / "network"), "--published-binary", "/e/firefox"]) == 0
|
||||
binary = str(Path("/e/firefox"))
|
||||
assert calls == [(binary, None, "firefox-68", 4, 3), (binary, None, "firefox-68-again", 4, 3)]
|
||||
hunt = tmp_path / "network" / "hunt"
|
||||
assert sorted(p.name for p in hunt.iterdir()) == sorted(["summary.json"] + ["%s-%d.json" % (e, i) for e in ("firefox-68", "firefox-68-again") for i in (1, 2, 3)])
|
||||
summary = json.loads((hunt / "summary.json").read_text(encoding="utf-8"))
|
||||
assert [(r["engine"], r["i"], r["count_3478"]) for r in summary["repetitions"]] == [("firefox-68", 1, 9), ("firefox-68", 2, 8), ("firefox-68", 3, 9), ("firefox-68-again", 1, 9), ("firefox-68-again", 2, 8),
|
||||
("firefox-68-again", 3, 9)]
|
||||
assert summary["repetitions"][0]["targets"][ab.TURN_TARGET] == [["aa" * 12, 9]]
|
||||
assert not (tmp_path / "network" / "diff-a-a.json").exists()
|
||||
assert "hunt summary written" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_hunt_decides_nothing_even_when_an_engine_run_fails(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(ab, "hunt_engine", lambda *a, **k: 1)
|
||||
monkeypatch.setenv(ab.HUNT_ENV, "webrtc:4:2")
|
||||
assert ab.main(["ab", "--a-a", "--out", str(tmp_path / "network"), "--published-binary", "/e/firefox"]) == 0
|
||||
assert json.loads((tmp_path / "network" / "hunt" / "summary.json").read_text(encoding="utf-8"))["repetitions"] == []
|
||||
|
||||
|
||||
def test_a_hunt_variable_that_does_not_read_is_refused_and_runs_nothing(tmp_path, monkeypatch, capsys):
|
||||
monkeypatch.setattr(ab, "hunt_engine", lambda *a, **k: pytest.fail("a spec that does not read runs nothing"))
|
||||
monkeypatch.setenv(ab.HUNT_ENV, "webrtc:4")
|
||||
assert ab.main(["ab", "--a-a", "--out", str(tmp_path / "network"), "--published-binary", "/e/firefox"]) == 2
|
||||
assert "FAIL AB_NETWORK_HUNT" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_without_the_hunt_variable_ab_is_the_a_a_it_was(tmp_path, monkeypatch):
|
||||
monkeypatch.delenv(ab.HUNT_ENV, raising=False)
|
||||
monkeypatch.setattr(ab, "hunt_engine", lambda *a, **k: pytest.fail("no hunt without the variable"))
|
||||
ran = []
|
||||
monkeypatch.setattr(ab, "run_engine", lambda binary, seal, label, seeds, out: ran.append(label) or 1)
|
||||
assert ab.main(["ab", "--a-a", "--out", str(tmp_path / "network"), "--published-binary", "/e/firefox", "--seeds", "4"]) == 2
|
||||
assert ran == ["firefox-68", "firefox-68-again"], "the A/A runs the engine twice and says so when neither made a transcript: its own red, as before"
|
||||
|
||||
|
||||
def test_the_engine_of_a_hunt_runs_in_a_process_of_its_own_with_its_seal_and_its_own_cache(tmp_path, monkeypatch):
|
||||
seen = {}
|
||||
|
||||
class Done:
|
||||
returncode = 0
|
||||
|
||||
monkeypatch.setattr(ab.subprocess, "run", lambda cmd, env, timeout: seen.update(cmd=cmd, env=env, timeout=timeout) or Done())
|
||||
assert ab.hunt_engine("/e/firefox", "/e/seal.json", "firefox-68-again", 4, 20, tmp_path / "hunt") == 0
|
||||
cmd = seen["cmd"]
|
||||
assert cmd[3:] == ["hunt-run", "--binary", "/e/firefox", "--label", "firefox-68-again", "--seed", "4", "--n", "20", "--out", str(tmp_path / "hunt")]
|
||||
assert seen["env"]["INVISIBLE_SEAL_FILE"] == "/e/seal.json" and seen["env"]["INVISIBLE_CORE_AUTOFIX"] == "off"
|
||||
assert seen["timeout"] == ab.HUNT_BASE_S + 20 * ab.HUNT_PER_REPETITION_S
|
||||
|
||||
|
||||
def test_a_repetition_is_one_launch_the_walk_alone_and_the_evidence_read_after_the_close(monkeypatch):
|
||||
order = []
|
||||
|
||||
class Session:
|
||||
def __enter__(self):
|
||||
order.append("open")
|
||||
return types.SimpleNamespace(new_context=lambda **k: types.SimpleNamespace(new_page=lambda: order.append("page")))
|
||||
|
||||
def __exit__(self, *exc):
|
||||
order.append("closed")
|
||||
|
||||
monkeypatch.setattr(ab, "launch", lambda binary, seed, lab, patch: Session())
|
||||
monkeypatch.setattr(ab, "begin_launch", lambda seed, name: order.append("begin " + name))
|
||||
monkeypatch.setattr(ab, "glean_ready", lambda session, seed, name: order.append("glean") or {})
|
||||
monkeypatch.setattr(ab, "walk_webrtc", lambda browser, lab: order.append("walk") or {"udp": {}})
|
||||
for walker in ("walk_journey", "walk_h3", "walk_https"):
|
||||
monkeypatch.setattr(ab, walker, lambda *a, **k: pytest.fail("a hunt walks nothing but the WebRTC page"))
|
||||
monkeypatch.setattr(ab, "webrtc_evidence", lambda lab: order.append("evidence") or {"datagrams": [{"target": ab.TURN_TARGET, "counted": True}, {"target": ab.TURN_TARGET, "counted": False}]})
|
||||
record = ab.hunt_repetition("/e/firefox", "firefox-68", 3, 4, object())
|
||||
assert order == ["begin hunt", "open", "page", "glean", "walk", "closed", "evidence"]
|
||||
assert (record["engine"], record["i"], record["seed"], record["error"], record["counts"]) == ("firefox-68", 3, 4, None, {"counted": 1, "all": 2})
|
||||
|
||||
|
||||
def test_a_repetition_that_fails_is_a_record_with_its_error_and_the_hunt_goes_on(monkeypatch):
|
||||
def broken(binary, seed, lab, patch):
|
||||
raise RuntimeError("the engine did not start 17")
|
||||
|
||||
monkeypatch.setattr(ab, "launch", broken)
|
||||
monkeypatch.setattr(ab, "begin_launch", lambda seed, name: None)
|
||||
record = ab.hunt_repetition("/e/firefox", "firefox-68", 1, 4, object())
|
||||
assert record["error"] == "RuntimeError: the engine did not start N" and record["evidence"] is None and record["counts"] == {"counted": 0, "all": 0}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- e2e-hunt.yml
|
||||
def steps_of(text):
|
||||
"""The steps of the hunt job: ``{name: block}`` (the blocks of the lines that start with `` - ``)."""
|
||||
job = text[text.index("\n hunt:\n"):]
|
||||
blocks = re.split(r"\n(?= - )", job)
|
||||
return {b.split("name:", 1)[1].split("\n", 1)[0].strip(): b for b in blocks if b.startswith(" - name:")}
|
||||
|
||||
|
||||
def test_the_hunt_workflow_has_the_input_that_chooses_the_walk_and_stays_a_manual_one():
|
||||
text = HUNT_WORKFLOW.read_text(encoding="utf-8")
|
||||
on = text[text.index("\non:\n"):text.index("\npermissions:")]
|
||||
assert " workflow_dispatch:\n" in on and "push:" not in on and "pull_request" not in on and "schedule:" not in on
|
||||
inputs = on[on.index(" inputs:\n"):]
|
||||
block = inputs[inputs.index(" ab_network_webrtc_seed:\n"):]
|
||||
block = block[:block.index("\n os:")]
|
||||
assert 'default: ""' in block and "required: false" in block, "empty is today's behaviour"
|
||||
assert " runs:\n" in inputs and " os:\n" in inputs, "the inputs it had are still there"
|
||||
|
||||
|
||||
def test_the_step_of_the_walk_runs_the_hunt_mode_only_when_the_input_is_set_and_the_e2e_loop_only_when_it_is_not():
|
||||
steps = steps_of(HUNT_WORKFLOW.read_text(encoding="utf-8"))
|
||||
walk = next(b for n, b in steps.items() if n.startswith("The network oracle's WebRTC walk of one seed"))
|
||||
loop = steps["Loop until it catches one"]
|
||||
assert "if: inputs.ab_network_webrtc_seed != ''" in walk and "if: inputs.ab_network_webrtc_seed == ''" in loop
|
||||
assert "AB_NETWORK_HUNT: webrtc:${{ inputs.ab_network_webrtc_seed }}:${{ inputs.runs }}" in walk, "the seed and the number of repetitions come from the inputs, through the environment"
|
||||
assert "${{ inputs." not in walk.split("run: |")[1], "no input is written into the script text"
|
||||
assert "scripts/ci_ab_network.py ab --a-a --out network --published-binary \"$FF\"" in walk
|
||||
assert "xvfb-run -a" in walk and 'RUNNER_OS" = "Linux"' in walk
|
||||
assert "scripts/run_e2e.py" in loop and "run_e2e" not in walk
|
||||
for name in ("The security state (a fixed directory of the repository)", "The GeoIP database (made by the repository, same bytes every run)"):
|
||||
assert "if: inputs.ab_network_webrtc_seed != ''" in steps[name], "what only the hunt needs is made only for it"
|
||||
names = list(steps)
|
||||
assert names.index("The security state (a fixed directory of the repository)") < names.index("Fetch the published firefox binary") < names.index(next(n for n in names if n.startswith("The network oracle's WebRTC walk")))
|
||||
|
||||
|
||||
def test_the_hunt_uploads_network_hunt_as_an_artifact_and_every_action_it_uses_is_pinned_by_sha():
|
||||
text = HUNT_WORKFLOW.read_text(encoding="utf-8")
|
||||
steps = steps_of(text)
|
||||
upload = next(b for n, b in steps.items() if n.startswith("Upload the hunt of the network oracle's WebRTC walk"))
|
||||
assert "if: always() && inputs.ab_network_webrtc_seed != ''" in upload and "path: network/hunt" in upload
|
||||
assert re.search(r"uses: actions/upload-artifact@[0-9a-f]{40} # v4", upload)
|
||||
for line in text.splitlines():
|
||||
m = re.match(r"\s*- uses: (\S+)|\s+uses: (\S+)", line)
|
||||
if m and not (m.group(1) or m.group(2)).startswith("./"):
|
||||
assert re.search(r"@[0-9a-f]{40}\b", line), line
|
||||
@@ -629,7 +629,7 @@ def _job(text, name):
|
||||
def _needs_core_on_index(body, linux):
|
||||
"""A Linux job of e2e.yml waits for the core on the index and for the run's linux-deps-e2e job (its Ubuntu packages, from the archive once, never by the job);
|
||||
a Windows job waits for the core only."""
|
||||
return ("needs: [changes, core-on-index, linux-deps-e2e]" in body) if linux else ("needs: [changes, core-on-index]\n" in body)
|
||||
return ("needs: [core-on-index, linux-deps-e2e]" in body) if linux else ("needs: core-on-index\n" in body)
|
||||
|
||||
|
||||
def _linux_deps_e2e_packages(text):
|
||||
@@ -638,12 +638,12 @@ def _linux_deps_e2e_packages(text):
|
||||
return job[job.index("packages:"):].split("\n", 1)[0]
|
||||
|
||||
|
||||
def test_the_e2e_workflow_runs_the_step_in_the_merge_queue_run_in_the_jobs_that_run_the_oracles_and_the_e2e_tests_read_its_variables():
|
||||
def test_the_e2e_workflow_runs_the_step_on_a_pull_request_in_the_jobs_that_run_the_oracles_and_the_e2e_tests_read_its_variables():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
text = (root / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
legs = {name: _job(text, name) for name in ("e2e-linux", "e2e-windows-control-a", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows", "e2e-page", "e2e-page-windows")}
|
||||
step = (' - name: How many seeds the A/A of each oracle visits (all of them when the pull request touches the oracle)\n'
|
||||
" if: github.event_name == 'merge_group'\n shell: bash\n env:\n BASE_SHA: ${{ github.event.merge_group.base_sha }}\n"
|
||||
" if: github.event_name == 'pull_request'\n shell: bash\n env:\n BASE_SHA: ${{ github.event.pull_request.base.sha }}\n"
|
||||
' run: python scripts/ci_ab_pr_seeds.py "$BASE_SHA" >> "$GITHUB_ENV"\n')
|
||||
assert [name for name, body in legs.items() if step in body] == ["e2e-linux", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows", "e2e-page", "e2e-page-windows"], "the jobs that run the oracles' tests, and only those"
|
||||
for name in ("e2e-linux", "e2e-windows", "e2e-network", "e2e-network-windows", "e2e-host", "e2e-host-windows", "e2e-page", "e2e-page-windows"):
|
||||
@@ -1089,10 +1089,10 @@ def test_the_final_set_has_jobs_of_its_own_in_four_shards_on_each_system_and_the
|
||||
for body in (linux, windows):
|
||||
assert "shard: [1, 2, 3, 4]" in body and "AB_ORACLE_SEED_SET: final" in body and "AB_ORACLE_SHARD: ${{ matrix.shard }}/4" in body
|
||||
assert body.count(page) == 1 and "scripts/run_e2e.py" not in body and "timeout-minutes: 40" in body and "fail-fast: false" in body
|
||||
assert ("needs: [changes, core-on-index, e2e-page-final-touched, linux-deps-e2e]" if body is linux else "needs: [changes, core-on-index, e2e-page-final-touched]") in body and "needs.e2e-page-final-touched.outputs.touched == 'true'" in body
|
||||
assert ("needs: [core-on-index, e2e-page-final-touched, linux-deps-e2e]" if body is linux else "needs: [core-on-index, e2e-page-final-touched]") in body and "needs.e2e-page-final-touched.outputs.touched == 'true'" in body
|
||||
assert "skipped\": 0" in body and '{"tests": 1, "failures": 0, "errors": 0, "skipped": 0}' in body, "one test, passed: a skipped one is red"
|
||||
assert "matrix.shard" in body.split("name: invpw-evidence-page-final", 1)[1].split("path:", 1)[0], "four shards, four artifact names"
|
||||
assert "scripts/ci_ab_oracle.py touched" in touched and "github.event_name == 'merge_group'" in touched and "github.event.merge_group.base_sha" in touched and "outputs:" in touched
|
||||
assert "scripts/ci_ab_oracle.py touched" in touched and "pull_request" in touched and "outputs:" in touched
|
||||
shared_linux, shared_windows = _job(text, "e2e-linux"), _job(text, "e2e-windows")
|
||||
assert "AB_ORACLE_SEED_SET" not in shared_linux + shared_windows + _job(text, "e2e-windows-control-a"), "the shared jobs run the candidate set and do not grow"
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ def test_async_default_context_kwargs_match_sync():
|
||||
|
||||
# ── parity with the sync launcher, driven rather than declared ───────────────
|
||||
|
||||
def test_the_async_api_stamps_the_session_token_into_the_browser_env():
|
||||
def test_the_async_api_stamps_the_session_token_into_the_browser_env(declared_engine):
|
||||
"""The gap that shipped a "fixed" leak to half the users.
|
||||
|
||||
The Windows process-leak fix went into 0.4.0 and was described as fixed. It
|
||||
|
||||
@@ -25,19 +25,17 @@ the files themselves:
|
||||
a job of its own that waits for them. A job that `needs` another is
|
||||
SKIPPED when that one fails unless its `if:` says `always()`, and a
|
||||
skipped check is not red. So: the job `e2e` needs the parts and
|
||||
`core-on-index`; its `if:` is `always()` and the gate of the parts (not the
|
||||
Windows-only dispatch) joined by `&&`, so that it is skipped exactly when
|
||||
the parts are skipped by that dispatch, and runs in every other case (a
|
||||
core that is not on the index fails `core-on-index`, the parts are then
|
||||
skipped and this job runs and is red: no output of `core-on-index` is
|
||||
read by any `if:`, ci-13); its one
|
||||
`core-on-index`; its `if:` is `always()` and the gate of the parts (the
|
||||
core on the index, not the Windows-only dispatch) joined by `&&`, so that
|
||||
it is skipped exactly when the parts are skipped for the core, as the
|
||||
Linux job was before the split, and runs in every other case; its one
|
||||
step binds `needs.e2e-linux.result` (`success` only when every part
|
||||
succeeded) and fails unless it is `success`, in exactly the form
|
||||
`if [ "$PARTS" != "success" ]; then ... exit 1 ... fi`, with no other
|
||||
result named in its code (a cancelled part measured nothing, a skipped
|
||||
one ran nothing); no `continue-on-error`; no other job has its name.
|
||||
Known-bad: without `always()`, accepting `skipped`, not needing the
|
||||
parts, exiting 0, reading another job, dropping the gate of the dispatch,
|
||||
parts, exiting 0, reading another job, dropping the gate of the core,
|
||||
`success() || failure()`, the single job before the split.
|
||||
|
||||
The checkers are tested on known-bad inputs first, because a check that has
|
||||
@@ -207,8 +205,8 @@ def problems_concurrency(name: str, spec: dict) -> list[str]:
|
||||
if "github.run_id" not in group:
|
||||
out.append(f"{name}: outside a pull request the group is not unique to the run, "
|
||||
f"so a newer pending run of main replaces an older one")
|
||||
if ("github.ref" in group and "merge_group" not in group) or "head_ref" in group:
|
||||
out.append(f"{name}: the group is keyed on the ref, which is main for every push to main (only a merge queue run may key on it: its ref is its own)")
|
||||
if "github.ref" in group or "head_ref" in group:
|
||||
out.append(f"{name}: the group is keyed on the ref, which is main for every push to main")
|
||||
return out
|
||||
|
||||
|
||||
@@ -319,9 +317,9 @@ def test_the_push_triggers_the_release_reads_are_still_there():
|
||||
e2e = triggers(_load(WORKFLOWS / "e2e.yml"))
|
||||
assert e2e["push"]["branches"] == ["main"], \
|
||||
"scripts/e2e_is_green.py needs the e2e of the push to main on the tagged commit"
|
||||
assert "merge_group" in e2e and "pull_request" not in e2e, "e2e runs in the merge queue run, not on the pull request"
|
||||
assert "pull_request" in e2e
|
||||
tests = triggers(_load(WORKFLOWS / "tests.yml"))
|
||||
assert tests["push"]["branches"] == ["main"] and "pull_request" in tests and "merge_group" in tests
|
||||
assert tests["push"]["branches"] == ["main"] and "pull_request" in tests
|
||||
publish = triggers(_load(WORKFLOWS / "publish.yml"))
|
||||
assert publish["push"]["tags"] == ["v*"], "publish must start on a release tag"
|
||||
|
||||
@@ -389,7 +387,7 @@ def problems_linux_check(text: str) -> list:
|
||||
if PARTS_JOB not in needs:
|
||||
out.append("the check does not need the parts (%s): it would not wait for them, nor read their result" % PARTS_JOB)
|
||||
if INDEX_GATE not in needs:
|
||||
out.append("the check does not need %s: it would run before the index was asked" % INDEX_GATE)
|
||||
out.append("the check does not need %s: its `if:` cannot read whether the core is on the index" % INDEX_GATE)
|
||||
if "||" in str(check.get("if", "")):
|
||||
out.append("the `if:` of the check has a `||`: it must be `always()` and the gate of the parts")
|
||||
cond = _conjuncts(check.get("if"))
|
||||
@@ -444,7 +442,7 @@ def test_a_linux_check_that_accepts_skipped_is_refused():
|
||||
|
||||
|
||||
def test_a_linux_check_that_does_not_need_the_parts_is_refused():
|
||||
body = _check_body().replace("needs: [changes, core-on-index, e2e-linux]", "needs: [changes, core-on-index]", 1)
|
||||
body = _check_body().replace("needs: [core-on-index, e2e-linux]", "needs: [core-on-index]", 1)
|
||||
assert body != _check_body()
|
||||
assert any("does not need the parts" in p for p in problems_linux_check(_e2e_with_check(body)))
|
||||
|
||||
@@ -459,8 +457,8 @@ def test_a_linux_check_that_reads_another_job_is_refused():
|
||||
assert any("does not bind PARTS" in p for p in problems_linux_check(_e2e_with_check(body)))
|
||||
|
||||
|
||||
def test_a_linux_check_that_drops_the_gate_of_the_dispatch_is_refused():
|
||||
body = _check_body().replace(" && inputs.only != 'windows-control-a'", "", 1)
|
||||
def test_a_linux_check_that_drops_the_gate_of_the_core_is_refused():
|
||||
body = _check_body().replace(" && needs.core-on-index.outputs.available == 'true'", "", 1)
|
||||
assert body != _check_body()
|
||||
assert any("not `always()` and the gate of the parts" in p for p in problems_linux_check(_e2e_with_check(body)))
|
||||
|
||||
|
||||
@@ -422,6 +422,7 @@ def test_a_real_page_sees_a_drag_that_travelled(firefox_binary):
|
||||
"""
|
||||
import urllib.parse
|
||||
|
||||
import _os_cursor
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
html = (
|
||||
@@ -445,6 +446,11 @@ def test_a_real_page_sees_a_drag_that_travelled(firefox_binary):
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("data:text/html," + urllib.parse.quote(html))
|
||||
# ⛔ THE OS CURSOR IS NOT IN THE WINDOW. A window under the real cursor gets a native move for it, the first native move of a process passes Gecko's
|
||||
# filter, and the page saw `mousemove 512,299 buttons=0` after the press (the runner's cursor is at 512,384, the window covers it). The cursor is
|
||||
# parked before the browser starts (`tests/_os_cursor.py`, the autouse fixture of conftest); here the test says it is still outside, so a gesture
|
||||
# judged by the events it records is never judged with the system's own move among them.
|
||||
_os_cursor.require_outside()
|
||||
page.mouse.move(300, 300)
|
||||
page.evaluate("() => { window.__e = []; }")
|
||||
page.drag_and_drop("#a", "#b")
|
||||
|
||||
@@ -593,14 +593,12 @@ WORKFLOW = (ROOT / ".github" / "workflows" / "fakeweb.yml").read_text(encoding="
|
||||
|
||||
|
||||
def test_the_workflow_has_four_legs_and_one_verdict_job():
|
||||
assert len(re.findall(r"^ [a-z0-9_-]+:\n (?:name|uses|needs):", WORKFLOW, re.MULTILINE)) == 5 # changes, core-on-index, linux-deps-fakeweb, walk, verdict
|
||||
assert len(re.findall(r"^ [a-z0-9_-]+:\n (?:name|uses):", WORKFLOW, re.MULTILINE)) == 4 # core-on-index, linux-deps-fakeweb, walk, verdict
|
||||
assert WORKFLOW.count("{ profile: ") == 4
|
||||
for leg in ("p2, os: linux", "p2, os: windows", "p4, os: linux", "p4, os: windows"):
|
||||
assert "profile: " + leg in WORKFLOW
|
||||
assert "name: fakeweb verdict" in WORKFLOW and "if: always()" in WORKFLOW.split("name: fakeweb verdict", 1)[1]
|
||||
verdict = WORKFLOW.split("name: fakeweb verdict", 1)[1]
|
||||
assert "needs: [changes, core-on-index, linux-deps-fakeweb, walk]" in verdict and "WORKFLOW: fakeweb" in verdict and "NEEDS: ${{ toJSON(needs) }}" in verdict
|
||||
# a leg that did not run is not green: scripts/ci_gate.py (read from main) expects `success` of `walk`, see tests/test_the_workflows_are_ready_for_the_merge_queue.py
|
||||
assert '"${{ needs.walk.result }}" != "success"' in WORKFLOW # a leg that did not run is not green
|
||||
|
||||
|
||||
def test_every_action_is_pinned_to_a_commit():
|
||||
@@ -618,8 +616,7 @@ def test_the_workflow_runs_stock_and_ours_and_never_reruns_or_forgives():
|
||||
assert WORKFLOW.index("scripts/ci_lab_geoip.py build") < first_run and WORKFLOW.index("scripts/ci_lab_security_state.py set") < WORKFLOW.index("fetch | tail -1")
|
||||
|
||||
|
||||
def test_the_workflow_starts_in_the_merge_queue_run_and_on_the_fake_web_files_of_main_and_by_hand():
|
||||
def test_the_workflow_starts_on_the_fake_web_files_of_a_pull_request_and_of_main_and_by_hand():
|
||||
on = WORKFLOW.split("\npermissions:", 1)[0]
|
||||
assert " push:\n branches: [main]\n paths:" in on and " merge_group:\n types: [checks_requested]\n" in on and " workflow_dispatch:" in on
|
||||
assert "pull_request" not in on.split("\non:\n", 1)[1], "a pull request runs the fast set; this workflow runs in the queue run"
|
||||
assert on.count("'tests/fakeweb/**'") == 1 and on.count("'.github/workflows/fakeweb.yml'") == 1
|
||||
assert " push:\n branches: [main]\n paths:" in on and " pull_request:\n paths:" in on and " workflow_dispatch:" in on
|
||||
assert on.count("'tests/fakeweb/**'") == 2 and on.count("'.github/workflows/fakeweb.yml'") == 2
|
||||
@@ -174,7 +174,7 @@ def no_geo_lookup(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_enter_with_profile_dir_calls_launch_persistent_context(tmp_path, monkeypatch, no_geo_lookup):
|
||||
def test_enter_with_profile_dir_calls_launch_persistent_context(tmp_path, monkeypatch, no_geo_lookup, declared_engine):
|
||||
"""When profile_dir is set, __enter__ must call
|
||||
`firefox.launch_persistent_context(user_data_dir=...)` and NOT
|
||||
`firefox.launch(...)`. This is the structural test that the persistent
|
||||
@@ -217,7 +217,7 @@ def test_enter_with_profile_dir_calls_launch_persistent_context(tmp_path, monkey
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_enter_without_profile_dir_calls_launch_not_persistent(tmp_path, monkeypatch, no_geo_lookup):
|
||||
def test_enter_without_profile_dir_calls_launch_not_persistent(tmp_path, monkeypatch, no_geo_lookup, declared_engine):
|
||||
"""Default path: profile_dir=None → firefox.launch, not
|
||||
launch_persistent_context. Sentinel that the non-persistent flow
|
||||
isn't accidentally rerouted."""
|
||||
@@ -246,7 +246,7 @@ def test_enter_without_profile_dir_calls_launch_not_persistent(tmp_path, monkeyp
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_persistent_context_user_data_dir_is_created_if_missing(tmp_path, monkeypatch, no_geo_lookup):
|
||||
def test_persistent_context_user_data_dir_is_created_if_missing(tmp_path, monkeypatch, no_geo_lookup, declared_engine):
|
||||
"""First-run scenario: the directory the user names doesn't exist yet.
|
||||
__enter__ must mkdir -p it (Playwright won't, and would crash with
|
||||
'user_data_dir does not exist')."""
|
||||
@@ -269,7 +269,7 @@ def test_persistent_context_user_data_dir_is_created_if_missing(tmp_path, monkey
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_teardown_closes_persistent_context(tmp_path, monkeypatch, no_geo_lookup):
|
||||
def test_teardown_closes_persistent_context(tmp_path, monkeypatch, no_geo_lookup, declared_engine):
|
||||
"""The teardown must close the persistent context. Forgetting this
|
||||
leaves Firefox + Playwright running until the parent process exits,
|
||||
which on long-running tools (job orchestrators, MCP servers) leaks
|
||||
|
||||
@@ -108,7 +108,7 @@ def test_default_context_viewport_follows_a_pinned_taskbar():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_default_context_screen_matches_profile():
|
||||
def test_default_context_screen_matches_profile(lab_exit):
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
kw = ip._default_context_kwargs()
|
||||
p = ip._profile
|
||||
@@ -125,7 +125,7 @@ def test_default_context_screen_matches_profile():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_default_context_color_scheme_follows_dark_theme():
|
||||
def test_default_context_color_scheme_follows_dark_theme(lab_exit):
|
||||
"""The theme follows ``dark_theme``, but through the DECLARATION.
|
||||
|
||||
Previously the wrapper passed ``color_scheme`` to Playwright, which translated it
|
||||
@@ -186,14 +186,14 @@ def test_default_context_with_no_language_asked_is_en_us():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_carries_the_declared_network():
|
||||
def test_build_env_carries_the_declared_network(declared_engine):
|
||||
from invisible_core import network_to_declare
|
||||
env = InvisiblePlaywright(seed=42)._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == network_to_declare(42)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_caller_env_override_wins(monkeypatch):
|
||||
def test_build_env_caller_env_override_wins(monkeypatch, declared_engine):
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", "v4=198.51.100.5;v6=1")
|
||||
env = InvisiblePlaywright(seed=42)._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == "v4=198.51.100.5;v6=1" # caller wins
|
||||
@@ -223,7 +223,7 @@ def test_build_env_drops_the_variables_the_display_names_absent():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_never_injects_font_env():
|
||||
def test_build_env_never_injects_font_env(declared_engine):
|
||||
# The patched binary is self-contained for fonts (always bundle-only; the
|
||||
# exposed set IS the bundle, system-ui + generics baked in C++). The wrapper
|
||||
# must NOT inject any STEALTHFOX_FONTLIST/SYSTEMUI env - even if legacy font
|
||||
@@ -238,7 +238,7 @@ def test_build_env_never_injects_font_env():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_no_font_keys_when_absent():
|
||||
def test_build_env_no_font_keys_when_absent(declared_engine):
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
env = ip._build_env({})
|
||||
assert "STEALTHFOX_FONTLIST" not in env
|
||||
|
||||
@@ -20,6 +20,7 @@ import urllib.parse
|
||||
|
||||
import pytest
|
||||
|
||||
import _os_cursor
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
|
||||
@@ -140,6 +141,8 @@ def _humanize_move_count(firefox_binary, humanize):
|
||||
"<div id=d style='width:600px;height:400px' "
|
||||
"onmousemove=\"window.__n=(window.__n||0)+1\">x</div>"
|
||||
))
|
||||
# A native move of the OS cursor would count among the page's mousemoves (`off <= 2` below); it is parked outside the window (tests/_os_cursor.py).
|
||||
_os_cursor.require_outside()
|
||||
page.mouse.move(10, 10)
|
||||
page.evaluate("window.__n = 0")
|
||||
page.mouse.move(500, 300)
|
||||
|
||||
@@ -46,7 +46,7 @@ DELIBERATE_VS_PUBLIC_API = {
|
||||
}
|
||||
|
||||
|
||||
def test_the_wrapper_composes_what_the_public_api_composes():
|
||||
def test_the_wrapper_composes_what_the_public_api_composes(lab_exit):
|
||||
profile = generate_profile(SEED)
|
||||
mine = build_prefs(profile=profile, locale=LOCALE, timezone=TZ,
|
||||
extra_prefs=None, virtual_display=False,
|
||||
|
||||
@@ -146,3 +146,55 @@ def test_without_a_core_folder_nothing_is_done_and_the_session_s_limit_is_the_ha
|
||||
assert soft == hard, "the session's core limit is (%r, %r)" % (soft, hard)
|
||||
else: # Windows has no core limit and no core files: lifting is a no-op that does not raise
|
||||
assert os.name == "nt", os.name
|
||||
|
||||
|
||||
def _memory(strings, arrays):
|
||||
"""A fake memory of a dead process: `strings` {address: bytes with their NUL}, `arrays` {address: [pointer, ...]}; the two readers gdb gives."""
|
||||
cells = {}
|
||||
for address, data in strings.items():
|
||||
for i, byte in enumerate(data):
|
||||
cells[address + i] = byte
|
||||
for address, pointers in arrays.items():
|
||||
for k, pointer in enumerate(pointers):
|
||||
for i, byte in enumerate(pointer.to_bytes(8, "little")):
|
||||
cells[address + 8 * k + i] = byte
|
||||
|
||||
def word(address):
|
||||
return int.from_bytes(bytes(cells[address + i] for i in range(8)), "little")
|
||||
|
||||
def cstring(address):
|
||||
out = b""
|
||||
while cells[address] != 0:
|
||||
out += bytes([cells[address]])
|
||||
address += 1
|
||||
return out.decode("utf-8")
|
||||
|
||||
return word, cstring
|
||||
|
||||
|
||||
def test_the_reader_of_a_dead_process_gives_its_arguments_and_only_the_names_of_its_environment():
|
||||
"""Run 45755178008 kept a core named after a thread (FSBroker7536) of a process the oracle had not launched: its arguments say which process it was. The values of
|
||||
the environment are never read out (a CI environment carries tokens)."""
|
||||
import ci_crash_evidence as crash
|
||||
|
||||
word, cstring = _memory({0x3000: b"/e/firefox\0", 0x3100: b"--backgroundtask\0", 0x3200: b"HOME=/home/runner\0", 0x3300: b"GITHUB_TOKEN=s3cr3t\0"},
|
||||
{0x1000: [0x3000, 0x3100], 0x2000: [0x3200, 0x3300, 0]})
|
||||
args, names, problems = crash.argv_and_env_keys(word, cstring, 2, 0x1000, 0x2000)
|
||||
assert args == ["/e/firefox", "--backgroundtask"]
|
||||
assert names == ["HOME", "GITHUB_TOKEN"] and "s3cr3t" not in repr((args, names, problems))
|
||||
assert problems == []
|
||||
# an argc that is not a count, and memory that ends in the middle, are said, not raised
|
||||
args, names, problems = crash.argv_and_env_keys(word, cstring, -1, 0x1000, 0x5000)
|
||||
assert args == [] and names == [] and len(problems) == 2
|
||||
|
||||
|
||||
def test_both_readers_of_a_core_print_which_process_it_was():
|
||||
"""The e2e reader (tests/_crash_cores.py) and the oracles' (scripts/ci_crash_evidence.py) run the same gdb step, and its Python is valid."""
|
||||
import ci_crash_evidence as crash
|
||||
|
||||
command = crash.argv_gdb_command()
|
||||
assert command in _crash_cores.GDB_COMMANDS and command in crash.GDB_COMMANDS
|
||||
assert command.startswith("python exec(") and command.endswith(")")
|
||||
source = eval(command[len("python exec("):-1])
|
||||
compile(source, "<gdb>", "exec")
|
||||
assert "__libc_argv" in source and "environ" in source and "def argv_and_env_keys" in source
|
||||
@@ -1,278 +0,0 @@
|
||||
"""Rule ci-13, nothing counts as passed that did not pass: the verdict `gate` of tests.yml is red when a job it waits for is skipped.
|
||||
|
||||
`gate` is the one context main requires. It used to treat `skipped` as a pass, and `unit` was skipped when `core-on-index` said the pinned
|
||||
invisible-core was not on the package index yet: a pull request could merge with no test run. Now:
|
||||
|
||||
* `core-on-index` FAILS (it does not skip anything) when the pinned core is not on the index, with the message
|
||||
`FAIL core-on-index: the pinned invisible-core <version> is not on the index. Fix: ... Rule: ci-13 ...`, and it has no `available` output;
|
||||
no `if:` of any workflow reads that output (a missing output reads as '' and would silently skip the job it guards);
|
||||
* `gate` runs `scripts/ci_gate.py`, read from origin/main and never from the branch it judges, on `toJSON(needs)`: every needed job must be `success`, one `FAIL gate: job <name> is <result>. Fix: ...` line
|
||||
for each that is not. The only job conditional by design is `version` (pull requests only): `skipped` on any other event, `success` on a pull request.
|
||||
|
||||
Known-bad inputs: a `skipped`, a `cancelled` and a `failure` job, a skipped `version` on a pull request, a needed job that the script does not
|
||||
know, an unreadable `NEEDS`, the tests.yml with the old generic `case ... failure|cancelled` arms, a workflow with an `if:` that reads the removed
|
||||
output. The green case is the state of the repository.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WORKFLOWS = ROOT / ".github" / "workflows"
|
||||
SCRIPT = ROOT / "scripts" / "ci_gate.py"
|
||||
RULE = "Rule: ci-13 nothing counts as passed that did not pass"
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("ci_gate", SCRIPT)
|
||||
ci_gate = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(ci_gate)
|
||||
|
||||
|
||||
def _needs(result: str = "success", **overrides: str) -> dict:
|
||||
jobs = {name: {"result": result, "outputs": {}} for name in ci_gate.FIX}
|
||||
for name, value in overrides.items():
|
||||
jobs[name.replace("_", "-")] = {"result": value, "outputs": {}}
|
||||
return jobs
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ the script
|
||||
|
||||
|
||||
def test_every_job_green_on_a_pull_request_is_ok():
|
||||
assert ci_gate.verdict(_needs(), "pull_request") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("result", ["skipped", "cancelled", "failure"])
|
||||
def test_a_needed_job_that_is_not_success_is_red(result):
|
||||
lines = ci_gate.verdict(_needs(unit=result), "pull_request")
|
||||
assert len(lines) == 1
|
||||
assert lines[0].startswith("FAIL gate: job unit is %s. Fix: " % result)
|
||||
assert lines[0].endswith(RULE)
|
||||
|
||||
|
||||
def test_a_skipped_unit_is_red_on_a_push_too():
|
||||
assert any("job unit is skipped" in line for line in ci_gate.verdict(_needs(unit="skipped"), "push"))
|
||||
|
||||
|
||||
def test_a_skipped_core_on_index_is_red():
|
||||
assert any("job core-on-index is skipped" in line for line in ci_gate.verdict(_needs(core_on_index="skipped"), "pull_request"))
|
||||
|
||||
|
||||
def test_every_job_that_is_not_success_gets_its_own_line():
|
||||
lines = ci_gate.verdict(_needs(unit="skipped", docs_api="skipped", english="failure"), "pull_request")
|
||||
assert [line.split(" is ")[0] for line in lines] == ["FAIL gate: job docs-api", "FAIL gate: job english", "FAIL gate: job unit"]
|
||||
|
||||
|
||||
def test_version_is_skipped_on_a_push_and_must_succeed_on_a_pull_request():
|
||||
assert ci_gate.verdict(_needs(version="skipped"), "push") == []
|
||||
assert any("job version is skipped" in line for line in ci_gate.verdict(_needs(version="skipped"), "pull_request"))
|
||||
assert any("job version is failure" in line for line in ci_gate.verdict(_needs(version="failure"), "push"))
|
||||
|
||||
|
||||
def test_only_version_is_conditional():
|
||||
assert set(ci_gate.CONDITIONAL) == {"version"}
|
||||
|
||||
|
||||
def test_a_needed_job_the_script_does_not_know_is_red():
|
||||
needs = _needs()
|
||||
needs["brand-new"] = {"result": "success", "outputs": {}}
|
||||
assert any("job brand-new is success" in line for line in ci_gate.verdict(needs, "pull_request"))
|
||||
|
||||
|
||||
def test_a_job_that_is_missing_from_needs_is_red():
|
||||
needs = _needs()
|
||||
del needs["unit"]
|
||||
assert any("job unit is missing" in line for line in ci_gate.verdict(needs, "pull_request"))
|
||||
|
||||
|
||||
def _run(needs_text: str, event: str = "pull_request") -> subprocess.CompletedProcess:
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("NEEDS", "EVENT_NAME")}
|
||||
env.update(NEEDS=needs_text, EVENT_NAME=event)
|
||||
return subprocess.run([sys.executable, str(SCRIPT)], env=env, capture_output=True, text=True, timeout=60)
|
||||
|
||||
|
||||
def test_the_script_exits_1_with_the_fail_line_when_unit_is_skipped():
|
||||
done = _run(json.dumps(_needs(unit="skipped")))
|
||||
assert done.returncode == 1
|
||||
assert "FAIL gate: job unit is skipped. Fix: " in done.stdout and RULE in done.stdout
|
||||
assert "ok" not in done.stdout.splitlines()
|
||||
|
||||
|
||||
def test_the_script_exits_0_when_every_job_is_as_expected():
|
||||
done = _run(json.dumps(_needs()))
|
||||
assert done.returncode == 0 and done.stdout.splitlines()[-1] == "ok"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "not json", "[]"])
|
||||
def test_the_script_is_red_when_it_cannot_read_the_results(text):
|
||||
done = _run(text)
|
||||
assert done.returncode == 1 and done.stdout.startswith("FAIL gate: ")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the workflow
|
||||
|
||||
|
||||
def _job_text(text: str, job: str) -> str:
|
||||
body = text.split("\njobs:\n", 1)[1] if "\njobs:\n" in text else ""
|
||||
found = re.search(r"^ %s:\s*\n(.*?)(?=^ [A-Za-z0-9_-]+:\s*$|\Z)" % re.escape(job), body, re.M | re.S)
|
||||
return found.group(1) if found else ""
|
||||
|
||||
|
||||
def problems_gate(tests_yml: str) -> list:
|
||||
"""What is wrong with the job `gate` of this tests.yml, as the rule ci-13 reads it."""
|
||||
out = []
|
||||
body = _job_text(tests_yml, "gate")
|
||||
if not body:
|
||||
return ["tests.yml has no job `gate`"]
|
||||
needs = re.search(r"^ needs: \[([^\]]*)\]\s*$", body, re.M)
|
||||
names = [n.strip() for n in needs.group(1).split(",")] if needs else []
|
||||
if sorted(names) != sorted(ci_gate.FIX):
|
||||
out.append("the `needs:` of gate (%s) is not the table of scripts/ci_gate.py (%s)" % (sorted(names), sorted(ci_gate.FIX)))
|
||||
if not re.search(r"^ +if: always\(\)\s*$", body, re.M):
|
||||
out.append("gate has no `if: always()`: a failed job would leave it skipped")
|
||||
if not re.search(r"^ +NEEDS: \$\{\{ toJSON\(needs\) \}\}\s*$", body, re.M):
|
||||
out.append("gate does not pass `toJSON(needs)` to the script")
|
||||
if 'git show origin/main:scripts/ci_gate.py > "$RUNNER_TEMP/ci_gate.py"' not in body:
|
||||
out.append("gate does not read scripts/ci_gate.py from origin/main: the judge would come from the branch it judges")
|
||||
if "git fetch" not in body or "refs/heads/main:refs/remotes/origin/main" not in body:
|
||||
out.append("gate does not fetch main before it reads the judge")
|
||||
if "ci_gate.py is not on origin/main yet: falling back to the copy of this branch" not in body:
|
||||
out.append("gate falls back to the branch copy without saying so")
|
||||
if not re.search(r'^ +python3 "\$RUNNER_TEMP/ci_gate\.py"\s*$', body, re.M):
|
||||
out.append("gate does not run the copy it read from main")
|
||||
if re.search(r"python3? +(\./)?scripts/ci_gate\.py", body):
|
||||
out.append("gate runs the script of the branch directly")
|
||||
for line in body.splitlines():
|
||||
code = line.split("#", 1)[0]
|
||||
if re.search(r"failure\|cancelled|\bskipped\b|continue-on-error", code):
|
||||
out.append("gate names a result or `continue-on-error` outside the script: %s" % line.strip())
|
||||
return out
|
||||
|
||||
|
||||
def _tests_yml() -> str:
|
||||
return (WORKFLOWS / "tests.yml").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_the_gate_of_tests_yml_runs_the_script_on_every_needed_job():
|
||||
assert problems_gate(_tests_yml()) == []
|
||||
|
||||
|
||||
def _gate_run_replaced(text: str, run: str) -> str:
|
||||
body = _job_text(text, "gate")
|
||||
start = body.index(" # The judge is read from main")
|
||||
end = body.index("\n\n", start) if "\n\n" in body[start:] else len(body)
|
||||
return text.replace(body, body[:start] + run + body[end:])
|
||||
|
||||
|
||||
def test_a_gate_with_the_old_generic_case_arms_is_refused():
|
||||
run = ' run: |\n case "${{ needs.unit.result }}" in\n failure|cancelled) exit 1 ;;\n esac'
|
||||
found = problems_gate(_gate_run_replaced(_tests_yml(), run))
|
||||
assert any("failure|cancelled" in p for p in found) and any("from origin/main" in p for p in found), found
|
||||
|
||||
|
||||
def test_a_gate_that_runs_the_script_of_the_branch_it_judges_is_refused():
|
||||
found = problems_gate(_gate_run_replaced(_tests_yml(), " run: python3 scripts/ci_gate.py"))
|
||||
assert any("from origin/main" in p for p in found) and any("of the branch directly" in p for p in found), found
|
||||
|
||||
|
||||
def test_a_gate_that_falls_back_in_silence_is_refused():
|
||||
text = _tests_yml()
|
||||
quiet = text.replace("ci_gate.py is not on origin/main yet: falling back to the copy of this branch", "fallback", 1)
|
||||
assert quiet != text
|
||||
assert any("without saying so" in p for p in problems_gate(quiet))
|
||||
|
||||
|
||||
def test_a_gate_that_does_not_fetch_main_is_refused():
|
||||
text = _tests_yml()
|
||||
no_fetch = text.replace("git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main", "true", 1)
|
||||
assert no_fetch != text
|
||||
assert any("does not fetch main" in p for p in problems_gate(no_fetch))
|
||||
|
||||
|
||||
def test_a_gate_that_forgets_a_job_is_refused():
|
||||
text = _tests_yml()
|
||||
body = _job_text(text, "gate")
|
||||
assert any("table of scripts/ci_gate.py" in p for p in problems_gate(text.replace(body, body.replace(" unit,", "", 1))))
|
||||
|
||||
|
||||
def test_a_gate_that_is_skipped_when_a_job_fails_is_refused():
|
||||
text = _tests_yml()
|
||||
body = _job_text(text, "gate")
|
||||
assert any("no `if: always()`" in p for p in problems_gate(text.replace(body, body.replace(" if: always()\n", "", 1))))
|
||||
|
||||
|
||||
# ------------------------------------------------- the removed `available` output
|
||||
|
||||
|
||||
def problems_available(workflows: dict) -> list:
|
||||
"""`workflows` maps a file name to its text. Nothing may read, set or declare the `available` answer of core-on-index."""
|
||||
out = []
|
||||
for name, text in sorted(workflows.items()):
|
||||
for number, line in enumerate(text.splitlines(), 1):
|
||||
code = line.split("#", 1)[0]
|
||||
if re.search(r"core-on-index\.outputs\.available|steps\.probe\.outputs\.available|jobs\.probe\.outputs\.available|available=(true|false)", code):
|
||||
out.append("%s:%d reads or sets the removed `available` output: %s" % (name, number, line.strip()))
|
||||
if name == "core-on-index.yml" and re.match(r"\s+available:", code):
|
||||
out.append("%s:%d declares an `available` output" % (name, number))
|
||||
return out
|
||||
|
||||
|
||||
def _workflows() -> dict:
|
||||
return {p.name: p.read_text(encoding="utf-8") for p in sorted(WORKFLOWS.glob("*.yml"))}
|
||||
|
||||
|
||||
def test_no_workflow_reads_or_sets_the_available_output_of_core_on_index():
|
||||
assert problems_available(_workflows()) == []
|
||||
|
||||
|
||||
def test_no_job_of_tests_yml_has_an_if_that_reads_core_on_index():
|
||||
for number, line in enumerate(_tests_yml().splitlines(), 1):
|
||||
code = line.split("#", 1)[0]
|
||||
assert not (re.match(r"\s+if:", code) and "core-on-index" in code), "tests.yml:%d: %s" % (number, line.strip())
|
||||
|
||||
|
||||
def test_an_if_that_reads_the_removed_output_is_refused():
|
||||
workflows = _workflows()
|
||||
workflows["tests.yml"] = workflows["tests.yml"].replace(" needs: core-on-index\n runs-on: ${{ matrix.os }}", " needs: core-on-index\n if: needs.core-on-index.outputs.available == 'true'\n runs-on: ${{ matrix.os }}", 1)
|
||||
assert any("tests.yml" in p for p in problems_available(workflows))
|
||||
|
||||
|
||||
# ------------------------------------------------- core-on-index fails, never skips
|
||||
|
||||
|
||||
def problems_core_on_index(text: str) -> list:
|
||||
out = []
|
||||
if "FAIL core-on-index: the pinned {DIST} {pin} is not on the index. " not in text:
|
||||
out.append("core-on-index does not fail with `FAIL core-on-index: the pinned invisible-core <version> is not on the index`")
|
||||
if "Fix: wait for its publish to finish, or pin a published core. " not in text:
|
||||
out.append("the failure of core-on-index does not say how to fix it")
|
||||
if "Rule: ci-13 nothing counts as passed that did not pass" not in text:
|
||||
out.append("the failure of core-on-index does not name ci-13")
|
||||
unpublished = text.partition("if unpublished:")[2].partition("versions = data.get(")[0]
|
||||
if "sys.exit(0)" in unpublished or "die(" not in unpublished:
|
||||
out.append("a core that is not on the index at all does not end in a failure")
|
||||
if "sys.exit(0)" in text:
|
||||
out.append("core-on-index has a `sys.exit(0)`: a path that ends green without a verdict")
|
||||
return out
|
||||
|
||||
|
||||
def test_core_on_index_fails_when_the_pinned_core_is_not_on_the_index():
|
||||
assert problems_core_on_index((WORKFLOWS / "core-on-index.yml").read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_a_core_on_index_that_skips_during_the_window_is_refused():
|
||||
text = (WORKFLOWS / "core-on-index.yml").read_text(encoding="utf-8")
|
||||
skipping = text.replace(" die(f\"FAIL core-on-index: the pinned {DIST} {pin} is not on the index. \"\n f\"Fix: wait for its publish to finish, or pin a published core. \"\n f\"Rule: ci-13 nothing counts as passed that did not pass\")\n",
|
||||
" write(\"GITHUB_OUTPUT\", \"available=false\")\n sys.exit(0)\n", 1)
|
||||
assert skipping != text
|
||||
assert problems_core_on_index(skipping)
|
||||
assert problems_available({"core-on-index.yml": skipping})
|
||||
@@ -0,0 +1,225 @@
|
||||
"""The OS cursor is parked outside the browser window, and a gesture that records pointer events checks it.
|
||||
|
||||
A headed window that appears under the OS cursor gets a native ``WM_MOUSEMOVE`` for it, and the first native move of a process passes Gecko's filter: the page
|
||||
sees a ``mousemove`` with ``buttons=0`` at the cursor's place, in the middle of whatever the test records. On a GitHub Windows runner the cursor is at
|
||||
(512, 384) and the window covers (-8, -8) to (1928, 1040) of a 1920x1080 screen (``test_drag_motion.py::test_a_real_page_sees_a_drag_that_travelled`` saw
|
||||
``mousemove 512,299 buttons=0`` after the press). Nothing here launches a browser or touches the real cursor: the rectangles are the runner's, the system is a fake.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import _os_cursor
|
||||
from _os_cursor import (MARGIN, TheCursorCannotBeParked, TheCursorIsInside, cursor_is_outside, park, park_outside, require_outside)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
#: What a GitHub Windows runner shows while a headed browser is up.
|
||||
RUNNER_SCREEN = (0, 0, 1920, 1080)
|
||||
RUNNER_WINDOW = (-8, -8, 1928, 1040)
|
||||
RUNNER_CURSOR = (512, 384)
|
||||
|
||||
|
||||
def _free(point, windows, margin=MARGIN):
|
||||
return all(not (w[0] - margin <= point[0] < w[2] + margin and w[1] - margin <= point[1] < w[3] + margin) for w in windows)
|
||||
|
||||
|
||||
def _on_screen(point, screen):
|
||||
return screen[0] <= point[0] < screen[2] and screen[1] <= point[1] < screen[3]
|
||||
|
||||
|
||||
class _Desktop:
|
||||
"""The five answers of the desktop, with a cursor that obeys ``SetCursorPos`` unless ``obeys`` is False."""
|
||||
|
||||
def __init__(self, screen=RUNNER_SCREEN, windows=(RUNNER_WINDOW,), cursor=RUNNER_CURSOR, obeys=True):
|
||||
self._screen, self.windows, self.cursor, self.obeys = screen, list(windows), cursor, obeys
|
||||
self.asked = []
|
||||
|
||||
def screen(self):
|
||||
return self._screen
|
||||
|
||||
def windows_below(self, root_pid):
|
||||
return list(self.windows)
|
||||
|
||||
def cursor_position(self):
|
||||
return self.cursor
|
||||
|
||||
def set_cursor_position(self, x, y):
|
||||
self.asked.append((x, y))
|
||||
if self.obeys:
|
||||
self.cursor = (x, y)
|
||||
|
||||
|
||||
# ── the arrangement of the runner ────────────────────────────────────────────
|
||||
|
||||
def test_the_runners_cursor_is_inside_the_window_the_engine_opens():
|
||||
"""The arrangement that put a native move into a drag: the cursor on the runner is inside the window, so a window that appears under it is told."""
|
||||
assert cursor_is_outside([RUNNER_WINDOW], RUNNER_CURSOR) is False
|
||||
|
||||
|
||||
def test_a_parked_point_is_outside_the_runners_window_with_a_margin():
|
||||
point = park_outside([RUNNER_WINDOW], RUNNER_SCREEN)
|
||||
assert _on_screen(point, RUNNER_SCREEN)
|
||||
assert _free(point, [RUNNER_WINDOW])
|
||||
assert cursor_is_outside([RUNNER_WINDOW], point, MARGIN)
|
||||
|
||||
|
||||
def test_without_a_window_the_cursor_goes_to_the_bottom_right_corner():
|
||||
"""Before the browser starts there is no window to read: the corner where the engine puts none."""
|
||||
assert park_outside([], RUNNER_SCREEN) == (1919, 1079)
|
||||
|
||||
|
||||
def test_the_cursor_on_the_edge_of_a_window_is_inside_and_one_pixel_beyond_it_is_outside():
|
||||
window = (100, 100, 200, 200)
|
||||
assert not cursor_is_outside([window], (100, 100))
|
||||
assert not cursor_is_outside([window], (199, 199))
|
||||
assert cursor_is_outside([window], (200, 199))
|
||||
assert cursor_is_outside([window], (99, 150))
|
||||
|
||||
|
||||
def test_the_margin_widens_the_window_in_every_direction():
|
||||
window = (100, 100, 200, 200)
|
||||
assert not cursor_is_outside([window], (205, 150), margin=8)
|
||||
assert cursor_is_outside([window], (208, 150), margin=8)
|
||||
assert not cursor_is_outside([window], (150, 93), margin=8)
|
||||
|
||||
|
||||
# ── where the free point is ──────────────────────────────────────────────────
|
||||
|
||||
def test_a_window_on_the_corner_sends_the_cursor_to_another_one():
|
||||
window = (1000, 600, 1920, 1080)
|
||||
point = park_outside([window], RUNNER_SCREEN)
|
||||
assert _on_screen(point, RUNNER_SCREEN) and _free(point, [window])
|
||||
|
||||
|
||||
def test_a_window_that_covers_the_screen_has_no_free_point_and_says_so():
|
||||
with pytest.raises(TheCursorCannotBeParked) as caught:
|
||||
park_outside([(-8, -8, 1928, 1088)], RUNNER_SCREEN)
|
||||
message = str(caught.value)
|
||||
assert "Where:" in message and "What:" in message and "Fix:" in message
|
||||
assert "shrink the window" in message
|
||||
|
||||
|
||||
def test_a_window_that_leaves_less_than_the_margin_free_has_no_free_point():
|
||||
"""A strip of 4 pixels is free but the cursor would be 4 pixels from the page: not parked there."""
|
||||
with pytest.raises(TheCursorCannotBeParked):
|
||||
park_outside([(0, 0, 1920, 1076)], RUNNER_SCREEN)
|
||||
|
||||
|
||||
def test_a_strip_wider_than_the_margin_is_used():
|
||||
window = (0, 0, 1920, 1060)
|
||||
point = park_outside([window], RUNNER_SCREEN)
|
||||
assert _on_screen(point, RUNNER_SCREEN) and _free(point, [window])
|
||||
|
||||
|
||||
def test_two_monitors_leave_the_second_one_free():
|
||||
screen = (0, 0, 3840, 1080)
|
||||
point = park_outside([RUNNER_WINDOW], screen)
|
||||
assert _on_screen(point, screen) and _free(point, [RUNNER_WINDOW])
|
||||
assert point[0] > RUNNER_WINDOW[2]
|
||||
|
||||
|
||||
def test_a_virtual_screen_with_a_negative_origin_is_read_in_its_own_coordinates():
|
||||
"""A monitor left of and above the primary one: the virtual screen starts at a negative point and a window on the primary monitor covers part of it."""
|
||||
screen = (-1920, -200, 1920, 1080)
|
||||
point = park_outside([RUNNER_WINDOW], screen)
|
||||
assert _on_screen(point, screen) and _free(point, [RUNNER_WINDOW])
|
||||
|
||||
|
||||
def test_a_virtual_screen_with_a_negative_origin_and_a_window_on_every_monitor_but_the_strip():
|
||||
screen = (-1920, 0, 1920, 1080)
|
||||
windows = [(-1920, 0, 0, 1000), (0, 0, 1920, 1000)]
|
||||
point = park_outside(windows, screen)
|
||||
assert _on_screen(point, screen) and _free(point, windows)
|
||||
assert point[1] >= 1000 + MARGIN
|
||||
|
||||
|
||||
def test_several_windows_are_all_avoided():
|
||||
windows = [(0, 0, 900, 1080), (1000, 0, 1920, 500), (1000, 600, 1900, 1080)]
|
||||
point = park_outside(windows, RUNNER_SCREEN)
|
||||
assert _on_screen(point, RUNNER_SCREEN) and _free(point, windows)
|
||||
|
||||
|
||||
def test_an_empty_screen_is_refused_with_a_message():
|
||||
with pytest.raises(TheCursorCannotBeParked) as caught:
|
||||
park_outside([], (0, 0, 0, 0))
|
||||
assert "Fix:" in str(caught.value)
|
||||
|
||||
|
||||
# ── the system calls ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_park_moves_the_cursor_out_of_the_window_and_reads_it_back():
|
||||
desktop = _Desktop()
|
||||
assert not cursor_is_outside(desktop.windows, desktop.cursor)
|
||||
point = park(api=desktop)
|
||||
assert desktop.asked == [point] and desktop.cursor == point
|
||||
assert cursor_is_outside(desktop.windows, desktop.cursor, MARGIN)
|
||||
|
||||
|
||||
def test_park_fails_with_a_message_when_the_system_does_not_move_the_cursor():
|
||||
desktop = _Desktop(obeys=False)
|
||||
with pytest.raises(TheCursorCannotBeParked) as caught:
|
||||
park(api=desktop)
|
||||
message = str(caught.value)
|
||||
assert "Where:" in message and "What:" in message and "Fix:" in message
|
||||
assert "interactive desktop" in message
|
||||
|
||||
|
||||
def test_the_precondition_fails_on_the_runners_arrangement():
|
||||
"""The red of the e2e: the cursor at (512, 384) inside the window, nothing parked it."""
|
||||
with pytest.raises(TheCursorIsInside) as caught:
|
||||
require_outside(api=_Desktop())
|
||||
assert "(512, 384)" in str(caught.value)
|
||||
|
||||
|
||||
def test_the_precondition_passes_once_the_cursor_is_parked():
|
||||
desktop = _Desktop()
|
||||
park(api=desktop)
|
||||
require_outside(api=desktop)
|
||||
|
||||
|
||||
def test_the_precondition_looks_at_every_window_of_the_browsers():
|
||||
desktop = _Desktop(windows=[RUNNER_WINDOW, (400, 300, 700, 500)], cursor=(2000 - 100, 1079))
|
||||
require_outside(api=desktop)
|
||||
desktop.cursor = (500, 400)
|
||||
with pytest.raises(TheCursorIsInside):
|
||||
require_outside(api=desktop)
|
||||
|
||||
|
||||
# ── not Windows ──────────────────────────────────────────────────────────────
|
||||
|
||||
def test_without_windows_nothing_is_parked_and_every_precondition_holds(monkeypatch):
|
||||
monkeypatch.setattr(_os_cursor, "_is_windows", lambda: False)
|
||||
assert park() is None
|
||||
require_outside()
|
||||
assert cursor_is_outside([RUNNER_WINDOW]) is True
|
||||
assert _os_cursor.browser_windows() == []
|
||||
|
||||
|
||||
def test_on_the_runners_1920x1080_screen_the_strip_below_the_window_holds_the_cursor():
|
||||
"""The arrangement the Windows e2e jobs declare (e2e.yml: the runner's screen is set to 1920x1080, the largest mode its video device accepts, run
|
||||
45730213378): the window of a 1920x1080 identity, (-8, 0, 1928, 1040), leaves y 1040..1080 free, and the cursor is parked there."""
|
||||
window = (-8, 0, 1928, 1040)
|
||||
point = park_outside([window], (0, 0, 1920, 1080))
|
||||
assert point[1] >= 1040 + MARGIN and point[1] < 1080
|
||||
assert cursor_is_outside([window], point)
|
||||
|
||||
|
||||
def test_every_windows_e2e_job_declares_the_runners_screen_before_its_e2e():
|
||||
"""The step that sets the runner's screen (1024x768 by default, smaller than the window) is in every Windows job of e2e.yml, before its first `run:`
|
||||
step that starts pytest; a job added without it would park the cursor inside the window, and the gestures' precondition would say so only on Windows."""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
workflow = (pathlib.Path(__file__).resolve().parents[1] / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
jobs = re.split(r"\n (?=[a-z0-9-]+:\n)", workflow)
|
||||
windows = [j for j in jobs if re.search(r"^ runs-on: windows", j, re.M)]
|
||||
assert windows, "no Windows job found in e2e.yml: the check reads nothing"
|
||||
missing = []
|
||||
for job in windows:
|
||||
name = job.split(":", 1)[0].strip()
|
||||
step = job.find("The runner's screen is 1920x1080")
|
||||
pytest_at = min((m.start() for m in re.finditer(r"pytest|run_e2e", job)), default=-1)
|
||||
if step < 0 or (pytest_at >= 0 and step > pytest_at):
|
||||
missing.append(name)
|
||||
assert not missing, "these Windows jobs of e2e.yml start their e2e without declaring the runner's screen first: %s" % missing
|
||||
@@ -1,403 +0,0 @@
|
||||
"""The workflows are ready for a GitHub merge queue (rule ci-13, nothing counts as passed that did not pass).
|
||||
|
||||
The design: a pull request runs the fast set (tests.yml: unit and the rules jobs). The heavy e2e.yml and fakeweb.yml run in the merge queue run
|
||||
(`merge_group`), and that run decides. Each workflow that gates a merge has ONE verdict job, red on any needed job that is not `success`, skipped
|
||||
included (scripts/ci_gate.py, read from origin/main, WORKFLOW=tests|e2e|fakeweb picks its tables):
|
||||
|
||||
tests.yml the job `gate`
|
||||
e2e.yml the job named `e2e verdict`
|
||||
fakeweb.yml the job named `fakeweb verdict`
|
||||
|
||||
What is held here, on the files themselves:
|
||||
|
||||
* the three listen to `merge_group` (`checks_requested`); e2e.yml and fakeweb.yml do not listen to `pull_request`;
|
||||
* no `if:` of the three compares `github.event_name` with 'pull_request' without also allowing `merge_group`, and e2e.yml and fakeweb.yml read
|
||||
no field of the pull request: the base of a queue entry is `github.event.merge_group.base_sha`;
|
||||
* in a merge queue run the concurrency group is the ref of the entry and nothing is cancelled;
|
||||
* each verdict job waits for EVERY other job of its workflow, is `if: always()`, reads ci_gate.py from origin/main (and says so when it falls back),
|
||||
and names its WORKFLOW;
|
||||
* ci_gate.py, per workflow: `success` passes; `skipped`, `cancelled`, `failure` or a missing job is red; a job the table does not know is red;
|
||||
the table has an entry for every job the verdict job needs (and nothing else), parsed from the YAML; the jobs that may be skipped are exactly
|
||||
the ones that are conditional by design.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WORKFLOWS = ROOT / ".github" / "workflows"
|
||||
SCRIPT = ROOT / "scripts" / "ci_gate.py"
|
||||
RULE = "Rule: ci-13 nothing counts as passed that did not pass"
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("ci_gate_for_the_queue", SCRIPT)
|
||||
ci_gate = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(ci_gate)
|
||||
|
||||
# workflow file -> (WORKFLOW of ci_gate.py, the id of its verdict job, the name of that job)
|
||||
VERDICTS = {
|
||||
"tests.yml": ("tests", "gate", None),
|
||||
"e2e.yml": ("e2e", "verdict", "e2e verdict"),
|
||||
"fakeweb.yml": ("fakeweb", "verdict", "fakeweb verdict"),
|
||||
}
|
||||
QUEUE_ONLY = ("e2e.yml", "fakeweb.yml")
|
||||
|
||||
|
||||
def _text(name: str) -> str:
|
||||
return (WORKFLOWS / name).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _code(text: str) -> str:
|
||||
"""The text without its comment lines."""
|
||||
return "\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#"))
|
||||
|
||||
|
||||
def _triggers(text: str) -> list:
|
||||
found = re.search(r"^on:\s*\n(.*?)(?=^\S)", text, re.M | re.S)
|
||||
assert found, "no `on:` block"
|
||||
return re.findall(r"^ ([a-z_]+):", _code(found.group(1)), re.M)
|
||||
|
||||
|
||||
def _top_block(text: str, key: str) -> str:
|
||||
found = re.search(r"^%s:\s*\n(.*?)(?=^\S)" % re.escape(key), text, re.M | re.S)
|
||||
return found.group(1) if found else ""
|
||||
|
||||
|
||||
def _jobs(text: str) -> dict:
|
||||
"""job id -> its text, for the jobs of the file."""
|
||||
body = text.split("\njobs:\n", 1)[1]
|
||||
ids = list(re.finditer(r"^ ([A-Za-z0-9_-]+):\s*$", body, re.M))
|
||||
return {m.group(1): body[m.end(): ids[i + 1].start() if i + 1 < len(ids) else len(body)] for i, m in enumerate(ids)}
|
||||
|
||||
|
||||
def _needs(job_text: str) -> list:
|
||||
flow = re.search(r"^ needs: \[([^\]]*)\]\s*$", job_text, re.M)
|
||||
if flow:
|
||||
return [n.strip() for n in flow.group(1).split(",") if n.strip()]
|
||||
one = re.search(r"^ needs: ([A-Za-z0-9_-]+)\s*$", job_text, re.M)
|
||||
return [one.group(1)] if one else []
|
||||
|
||||
|
||||
def _ifs(text: str) -> list:
|
||||
"""(line number, condition) of every `if:` of the file, job or step."""
|
||||
return [(n, m.group(1)) for n, line in enumerate(text.splitlines(), 1)
|
||||
if (m := re.match(r"^\s+(?:- )?if: (.*)$", line)) and not line.lstrip().startswith("#")]
|
||||
|
||||
|
||||
def _needs_of_verdict(name: str) -> list:
|
||||
return _needs(_jobs(_text(name))[VERDICTS[name][1]])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ the triggers
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", sorted(VERDICTS))
|
||||
def test_every_workflow_with_a_verdict_listens_to_the_merge_queue(name):
|
||||
text = _text(name)
|
||||
assert "merge_group" in _triggers(text), "%s has a verdict job and does not listen to merge_group" % name
|
||||
assert re.search(r"^ merge_group:\s*\n types: \[checks_requested\]\s*$", text, re.M), "%s: merge_group without types: [checks_requested]" % name
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", QUEUE_ONLY)
|
||||
def test_the_heavy_workflows_do_not_run_on_the_pull_request(name):
|
||||
triggers = _triggers(_text(name))
|
||||
assert "pull_request" not in triggers and "pull_request_target" not in triggers, triggers
|
||||
assert "push" in triggers and "workflow_dispatch" in triggers, "push (main) and workflow_dispatch stay: %s" % triggers
|
||||
|
||||
|
||||
def test_the_fast_set_still_runs_on_the_pull_request_and_on_main():
|
||||
triggers = _triggers(_text("tests.yml"))
|
||||
assert {"push", "pull_request", "merge_group", "workflow_dispatch"} <= set(triggers), triggers
|
||||
assert re.search(r"^ push:\s*\n branches: \[main\]", _text("tests.yml"), re.M)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ the conditions
|
||||
|
||||
|
||||
def problems_conditions(name: str, text: str) -> list:
|
||||
out = []
|
||||
for number, cond in _ifs(text):
|
||||
if re.search(r"event_name\s*==\s*'pull_request'", cond) and "merge_group" not in cond:
|
||||
out.append("%s:%d `if: %s` runs on a pull request and not in the merge queue run" % (name, number, cond))
|
||||
if name in QUEUE_ONLY:
|
||||
for number, line in enumerate(_code(text).splitlines(), 1):
|
||||
if "github.event.pull_request" in line or "github.head_ref" in line or "github.base_ref" in line:
|
||||
out.append("%s: %s reads the pull request, which a queue run does not have (use github.event.merge_group.base_sha)" % (name, line.strip()))
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", sorted(VERDICTS))
|
||||
def test_no_condition_runs_on_the_pull_request_and_skips_the_merge_queue(name):
|
||||
assert problems_conditions(name, _text(name)) == []
|
||||
|
||||
|
||||
def test_every_step_that_reads_the_base_reads_the_one_of_the_queue_entry():
|
||||
for name in QUEUE_ONLY:
|
||||
text = _code(_text(name))
|
||||
assert text.count("BASE_SHA: ${{ github.event.merge_group.base_sha }}") == text.count("BASE_SHA:"), name
|
||||
e2e = _code(_text("e2e.yml"))
|
||||
assert e2e.count("BASE_SHA:") == 10 and len(re.findall(r"^\s+if: github\.event_name == 'merge_group'\s*$", e2e, re.M)) == 8
|
||||
assert "if: needs.changes.outputs.run == 'true' && github.event_name == 'merge_group' && inputs.only != 'windows-control-a'" in e2e
|
||||
|
||||
|
||||
def test_the_version_check_runs_in_the_merge_queue_run_too():
|
||||
version = _jobs(_text("tests.yml"))["version"]
|
||||
assert re.search(r"^ if: github\.event_name == 'pull_request' \|\| github\.event_name == 'merge_group'\s*$", version, re.M)
|
||||
|
||||
|
||||
def test_a_condition_that_skips_the_queue_is_refused():
|
||||
text = _text("e2e.yml").replace("if: github.event_name == 'merge_group'\n shell: bash", "if: github.event_name == 'pull_request'\n shell: bash", 1)
|
||||
assert problems_conditions("e2e.yml", text)
|
||||
assert problems_conditions("tests.yml", _text("tests.yml").replace("|| github.event_name == 'merge_group'", "", 1))
|
||||
assert problems_conditions("fakeweb.yml", _text("fakeweb.yml") + "\n - run: echo ${{ github.event.pull_request.base.sha }}\n")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ the concurrency
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", sorted(VERDICTS))
|
||||
def test_a_queue_run_is_grouped_on_its_ref_and_never_cancelled(name):
|
||||
block = _code(_top_block(_text(name), "concurrency"))
|
||||
group = re.search(r"^ group: (.*)$", block, re.M).group(1)
|
||||
cancel = re.search(r"^ cancel-in-progress: (.*)$", block, re.M).group(1).strip()
|
||||
assert "github.event_name == 'merge_group' && github.ref" in group, group
|
||||
assert "github.run_id" in group, "outside a queue run the group is unique to the run: %s" % group
|
||||
if name == "tests.yml":
|
||||
assert cancel == "${{ github.event_name == 'pull_request' }}", cancel # false in a queue run; a pull request keeps its behaviour
|
||||
assert "format('pr-{0}', github.event.pull_request.number)" in group
|
||||
else:
|
||||
assert cancel == "false", cancel
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ the verdict jobs
|
||||
|
||||
|
||||
def problems_verdict(name: str, text: str) -> list:
|
||||
workflow, job_id, job_name = VERDICTS[name]
|
||||
out = []
|
||||
jobs = _jobs(text)
|
||||
if job_id not in jobs:
|
||||
return ["%s has no job `%s`" % (name, job_id)]
|
||||
body = jobs[job_id]
|
||||
if job_name is None:
|
||||
if re.search(r"^ name:", body, re.M):
|
||||
out.append("%s: the verdict job `gate` has a name, and the branch protection reads the context `gate`" % name)
|
||||
elif not re.search(r"^ name: %s\s*$" % re.escape(job_name), body, re.M):
|
||||
out.append("%s: the verdict job is not named exactly `%s`" % (name, job_name))
|
||||
named = [i for i, b in jobs.items() if job_name and re.search(r"^ name: %s\s*$" % re.escape(job_name), b, re.M)]
|
||||
if job_name and named != [job_id]:
|
||||
out.append("%s: more than one job is named `%s`: %s" % (name, job_name, named))
|
||||
others = sorted(set(jobs) - {job_id})
|
||||
needs = _needs(body)
|
||||
if sorted(needs) != others:
|
||||
out.append("%s: the verdict job needs %s, not every other job of the workflow %s" % (name, sorted(needs), others))
|
||||
if not re.search(r"^ if: always\(\)\s*$", body, re.M):
|
||||
out.append("%s: the verdict job has no `if: always()`: a failed job would leave it skipped" % name)
|
||||
if "actions/checkout@" not in body:
|
||||
out.append("%s: the verdict job does not check out the repository" % name)
|
||||
if not re.search(r"^ +NEEDS: \$\{\{ toJSON\(needs\) \}\}\s*$", body, re.M):
|
||||
out.append("%s: the verdict job does not pass `toJSON(needs)`" % name)
|
||||
if not re.search(r"^ +EVENT_NAME: \$\{\{ github\.event_name \}\}\s*$", body, re.M):
|
||||
out.append("%s: the verdict job does not pass the event" % name)
|
||||
if not re.search(r"^ +WORKFLOW: %s\s*$" % workflow, body, re.M):
|
||||
out.append("%s: the verdict job does not set WORKFLOW: %s" % (name, workflow))
|
||||
if 'git show origin/main:scripts/ci_gate.py > "$RUNNER_TEMP/ci_gate.py"' not in body:
|
||||
out.append("%s: the verdict job does not read scripts/ci_gate.py from origin/main" % name)
|
||||
if "git fetch" not in body or "refs/heads/main:refs/remotes/origin/main" not in body:
|
||||
out.append("%s: the verdict job does not fetch main before it reads the judge" % name)
|
||||
if "ci_gate.py is not on origin/main yet: falling back to the copy of this branch" not in body:
|
||||
out.append("%s: the verdict job falls back to the branch copy without saying so" % name)
|
||||
if not re.search(r'^ +python3 "\$RUNNER_TEMP/ci_gate\.py"\s*$', body, re.M):
|
||||
out.append("%s: the verdict job does not run the copy it read from main" % name)
|
||||
if re.search(r"python3? +(\./)?scripts/ci_gate\.py", body):
|
||||
out.append("%s: the verdict job runs the script of the branch directly" % name)
|
||||
for line in body.splitlines():
|
||||
code = line.split("#", 1)[0]
|
||||
if re.search(r"failure\|cancelled|\bskipped\b|continue-on-error|needs\.[A-Za-z0-9_-]+\.result", code):
|
||||
out.append("%s: the verdict job names a result outside the script: %s" % (name, line.strip()))
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", sorted(VERDICTS))
|
||||
def test_each_verdict_job_waits_for_every_job_and_reads_the_judge_from_main(name):
|
||||
assert problems_verdict(name, _text(name)) == []
|
||||
|
||||
|
||||
def test_a_verdict_that_forgets_a_job_or_is_not_always_or_reads_the_branch_is_refused():
|
||||
text = _text("e2e.yml")
|
||||
assert any("not every other job" in p for p in problems_verdict("e2e.yml", text.replace("e2e-page-windows, ", "", 1)))
|
||||
assert any("no `if: always()`" in p for p in problems_verdict("fakeweb.yml", _text("fakeweb.yml").replace(" name: fakeweb verdict\n needs: [changes, core-on-index, linux-deps-fakeweb, walk]\n if: always()\n", " name: fakeweb verdict\n needs: [changes, core-on-index, linux-deps-fakeweb, walk]\n", 1)))
|
||||
assert any("origin/main" in p for p in problems_verdict("e2e.yml", text.replace('git show origin/main:scripts/ci_gate.py > "$RUNNER_TEMP/ci_gate.py"', "true", 1)))
|
||||
assert any("WORKFLOW" in p for p in problems_verdict("e2e.yml", text.replace("WORKFLOW: e2e\n", "", 1)))
|
||||
assert any("not named exactly" in p for p in problems_verdict("fakeweb.yml", _text("fakeweb.yml").replace("name: fakeweb verdict", "name: verdict", 1)))
|
||||
assert any("names a result" in p for p in problems_verdict("fakeweb.yml", _text("fakeweb.yml").replace('python3 "$RUNNER_TEMP/ci_gate.py"', 'python3 "$RUNNER_TEMP/ci_gate.py" || [ "${{ needs.walk.result }}" = skipped ]', 1)))
|
||||
|
||||
|
||||
def test_the_names_the_release_and_the_branch_protection_read_are_kept():
|
||||
e2e = _jobs(_text("e2e.yml"))["e2e"]
|
||||
assert re.search(r"^ name: e2e \(linux, xvfb\)\s*$", e2e, re.M), "scripts/e2e_is_green.py reads the Linux check of the push to main"
|
||||
assert "gate" in _jobs(_text("tests.yml"))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------ ci_gate.py, per workflow
|
||||
|
||||
|
||||
def _table(workflow: str) -> dict:
|
||||
return ci_gate.TABLES[workflow][1]
|
||||
|
||||
|
||||
def _all_green(workflow: str, touched: str = "true") -> dict:
|
||||
needs = {name: {"result": "success", "outputs": {}} for name in _table(workflow)}
|
||||
if workflow == "e2e":
|
||||
needs["e2e-page-final-touched"]["outputs"] = {"touched": touched}
|
||||
if touched != "true":
|
||||
for name in ci_gate.E2E_BY_OUTPUT:
|
||||
needs[name]["result"] = "skipped"
|
||||
return needs
|
||||
|
||||
|
||||
def _lines(workflow: str, needs: dict, event: str, only: str = "", changes_run: str = "true") -> list:
|
||||
return ci_gate.verdict(needs, event, workflow, only, changes_run)
|
||||
|
||||
|
||||
def _event_for(workflow: str) -> str:
|
||||
return "pull_request" if workflow == "tests" else "merge_group"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", ["tests", "e2e", "fakeweb"])
|
||||
def test_every_job_green_passes(workflow):
|
||||
assert _lines(workflow, _all_green(workflow), _event_for(workflow)) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", ["tests", "e2e", "fakeweb"])
|
||||
@pytest.mark.parametrize("result", ["skipped", "cancelled", "failure"])
|
||||
def test_a_needed_job_that_is_not_success_is_red(workflow, result):
|
||||
event = _event_for(workflow)
|
||||
label = ci_gate.TABLES[workflow][0]
|
||||
for job in sorted(_table(workflow)):
|
||||
if job in ci_gate.CONDITIONAL and workflow == "tests" or job in ci_gate.E2E_BY_OUTPUT or job in ci_gate.E2E_CONDITIONAL:
|
||||
continue # the conditional ones are tested below
|
||||
needs = _all_green(workflow)
|
||||
needs[job]["result"] = result
|
||||
lines = _lines(workflow, needs, event)
|
||||
assert any(line.startswith("FAIL %s: job %s is %s. Fix: " % (label, job, result)) and line.endswith(RULE) for line in lines), (job, lines)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", ["tests", "e2e", "fakeweb"])
|
||||
def test_a_job_that_is_missing_is_red(workflow):
|
||||
for job in sorted(_table(workflow)):
|
||||
needs = _all_green(workflow)
|
||||
del needs[job]
|
||||
assert any("job %s is missing" % job in line for line in _lines(workflow, needs, _event_for(workflow))), job
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", ["tests", "e2e", "fakeweb"])
|
||||
def test_a_job_the_table_does_not_know_is_red(workflow):
|
||||
needs = _all_green(workflow)
|
||||
needs["brand-new"] = {"result": "success", "outputs": {}}
|
||||
label = ci_gate.TABLES[workflow][0]
|
||||
assert any(line.startswith("FAIL %s: job brand-new is success" % label) for line in _lines(workflow, needs, _event_for(workflow)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", sorted(VERDICTS))
|
||||
def test_the_table_has_an_entry_for_every_job_the_verdict_needs_and_nothing_else(name):
|
||||
workflow = VERDICTS[name][0]
|
||||
needed = _needs_of_verdict(name)
|
||||
assert sorted(needed) == sorted(_table(workflow)), "%s: needs %s, table %s" % (name, sorted(needed), sorted(_table(workflow)))
|
||||
assert all(_table(workflow)[job].strip() for job in needed), "every entry says what to do"
|
||||
|
||||
|
||||
def test_version_runs_in_the_queue_and_on_a_pull_request_and_is_skipped_on_a_push():
|
||||
for event in ("pull_request", "merge_group"):
|
||||
assert ci_gate.CONDITIONAL["version"] and event in ci_gate.CONDITIONAL["version"]
|
||||
needs = _all_green("tests")
|
||||
needs["version"]["result"] = "skipped"
|
||||
assert any("job version is skipped" in line for line in _lines("tests", needs, event)), event
|
||||
needs = _all_green("tests")
|
||||
needs["version"]["result"] = "skipped"
|
||||
assert _lines("tests", needs, "push") == []
|
||||
needs["version"]["result"] = "failure"
|
||||
assert any("job version is failure" in line for line in _lines("tests", needs, "push"))
|
||||
|
||||
|
||||
def test_the_final_seed_shards_run_exactly_when_the_page_oracle_is_touched():
|
||||
for name in ci_gate.E2E_BY_OUTPUT:
|
||||
needs = _all_green("e2e", touched="true")
|
||||
needs[name]["result"] = "skipped"
|
||||
assert any("job %s is skipped" % name in line for line in _lines("e2e", needs, "merge_group")), "touched, and a shard did not run"
|
||||
needs = _all_green("e2e", touched="false")
|
||||
assert _lines("e2e", needs, "merge_group") == [], "not touched: the shards are skipped on purpose"
|
||||
needs[name]["result"] = "failure"
|
||||
assert any("job %s is failure" % name in line for line in _lines("e2e", needs, "merge_group"))
|
||||
needs = _all_green("e2e", touched="true")
|
||||
needs["e2e-page-final-touched"]["result"] = "skipped"
|
||||
assert any("job e2e-page-final-touched is skipped" in line for line in _lines("e2e", needs, "merge_group")), "the job that decides must run in the queue run"
|
||||
|
||||
|
||||
def test_the_dispatch_of_the_windows_job_alone_skips_what_it_leaves_out_and_nothing_else():
|
||||
needs = {name: {"result": "skipped", "outputs": {}} for name in ci_gate.E2E_FIX}
|
||||
for name in ("changes", "core-on-index", "e2e-windows-control-a"):
|
||||
needs[name]["result"] = "success"
|
||||
assert _lines("e2e", needs, "workflow_dispatch", "windows-control-a") == []
|
||||
assert any("job e2e-windows is skipped" in line for line in _lines("e2e", needs, "workflow_dispatch", "")), "a full run does not forgive a skipped job"
|
||||
needs["e2e-windows-control-a"]["result"] = "skipped"
|
||||
assert any("job e2e-windows-control-a is skipped" in line for line in _lines("e2e", needs, "workflow_dispatch", "windows-control-a"))
|
||||
|
||||
|
||||
def test_the_jobs_that_may_be_skipped_are_the_ones_the_workflow_says_it_skips():
|
||||
text = _text("e2e.yml")
|
||||
jobs = _jobs(text)
|
||||
only = {j for j, body in jobs.items() if re.search(r"^ if: .*inputs\.only != 'windows-control-a'", body, re.M)}
|
||||
by_output = {j for j, body in jobs.items() if re.search(r"^ if: needs\.changes\.outputs\.run == 'true' && needs\.[A-Za-z0-9_-]+\.outputs\.[a-z]+ == 'true'\s*$", body, re.M)}
|
||||
assert by_output == set(ci_gate.E2E_BY_OUTPUT), by_output
|
||||
assert set(ci_gate.E2E_NARROWED) - set(ci_gate.E2E_BY_OUTPUT) == only, (sorted(only), ci_gate.E2E_NARROWED)
|
||||
for job, (decider, output, value) in ci_gate.E2E_BY_OUTPUT.items():
|
||||
assert "needs.%s.outputs.%s == '%s'" % (decider, output, value) in jobs[job], job
|
||||
assert decider in _needs(jobs[job]) and "%s: ${{ steps.%s.outputs.%s }}" % (output, output, output) in jobs[decider]
|
||||
conditional = {j for j, body in jobs.items() if re.search(r"^ if: .*event_name", body, re.M)}
|
||||
assert conditional == set(ci_gate.E2E_CONDITIONAL), conditional
|
||||
assert set(_triggers(text)) >= {"merge_group"} and all("merge_group" in ci_gate.E2E_CONDITIONAL[j] for j in conditional)
|
||||
fake = _jobs(_text("fakeweb.yml"))
|
||||
assert all(re.search(r"^ if: needs\.changes\.outputs\.run == 'true'\s*$", body, re.M) for j, body in fake.items() if j not in ("verdict", "changes")), "a job of fakeweb.yml runs on `changes` and on nothing else"
|
||||
|
||||
|
||||
def test_the_conditional_jobs_of_tests_yml_are_the_ones_whose_if_reads_the_event():
|
||||
jobs = _jobs(_text("tests.yml"))
|
||||
conditional = {j for j, body in jobs.items() if re.search(r"^ if: .*event_name", body, re.M)}
|
||||
assert conditional == set(ci_gate.CONDITIONAL) == {"version"}, conditional
|
||||
|
||||
|
||||
def _run(workflow: str, needs: dict, event: str, only: str = "") -> subprocess.CompletedProcess:
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("NEEDS", "EVENT_NAME", "WORKFLOW", "INPUT_ONLY", "CHANGES_RUN")}
|
||||
env.update(NEEDS=json.dumps(needs), EVENT_NAME=event, INPUT_ONLY=only, CHANGES_RUN="true")
|
||||
if workflow:
|
||||
env["WORKFLOW"] = workflow
|
||||
return subprocess.run([sys.executable, str(SCRIPT)], env=env, capture_output=True, text=True, timeout=60)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workflow", ["tests", "e2e", "fakeweb"])
|
||||
def test_the_script_exits_0_on_green_and_1_with_the_verdict_job_named_on_a_skipped_job(workflow):
|
||||
done = _run(workflow, _all_green(workflow), _event_for(workflow))
|
||||
assert done.returncode == 0 and done.stdout.splitlines()[-1] == "ok", done.stdout
|
||||
needs = _all_green(workflow)
|
||||
first = sorted(j for j in _table(workflow) if j not in ci_gate.E2E_BY_OUTPUT and j not in ci_gate.E2E_CONDITIONAL and j != "version")[0]
|
||||
needs[first]["result"] = "skipped"
|
||||
done = _run(workflow, needs, _event_for(workflow))
|
||||
assert done.returncode == 1 and "FAIL %s: job %s is skipped. Fix: " % (ci_gate.TABLES[workflow][0], first) in done.stdout, done.stdout
|
||||
|
||||
|
||||
def test_the_default_workflow_is_tests_and_an_unknown_one_is_red():
|
||||
assert _run("", _all_green("tests"), "pull_request").returncode == 0
|
||||
done = _run("nope", _all_green("tests"), "pull_request")
|
||||
assert done.returncode == 1 and done.stdout.startswith("FAIL gate: WORKFLOW is 'nope'")
|
||||
done = _run("e2e", _all_green("tests"), "merge_group")
|
||||
assert done.returncode == 1, "the tables of another workflow are not forgiven"
|
||||
@@ -87,7 +87,7 @@ def slow(monkeypatch):
|
||||
return vd
|
||||
|
||||
|
||||
def test_a_second_browser_is_served_while_the_first_starts_its_display(slow):
|
||||
def test_a_second_browser_is_served_while_the_first_starts_its_display(slow, declared_engine):
|
||||
"""While the first browser's display start is in progress (blocked until the
|
||||
test lets it return), the loop answers a second browser. If the start ran on
|
||||
the loop, the loop would stand still inside it and the second browser could
|
||||
|
||||
@@ -16,7 +16,7 @@ from invisible_playwright import ensure_binary, get_default_stealth_prefs
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
def test_public_import_matches_direct_import():
|
||||
def test_public_import_matches_direct_import(lab_exit):
|
||||
"""The wrapper's re-export IS the core's function, not a copy of it."""
|
||||
from invisible_core.config import get_default_stealth_prefs as _core
|
||||
|
||||
|
||||
Reference in new issue
Block a user