Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58faefb458 | ||
|
|
a30e74c10b | ||
|
|
a90dadc204 | ||
|
|
210161d9b6 | ||
|
|
1542fede01 | ||
|
|
5426744bc6 | ||
|
|
64dc8d3476 | ||
|
|
bbf4019940 | ||
|
|
6200bc29ed | ||
|
|
b05741f538 | ||
|
|
620f969655 | ||
|
|
2f153c76ff | ||
|
|
fbceeafb65 | ||
|
|
b09d620930 | ||
|
|
776c00afe2 | ||
|
|
ba5b51cf91 | ||
|
|
6a60dcebb7 | ||
|
|
7db28e4611 | ||
|
|
f76240893e | ||
|
|
d5c0e410de | ||
|
|
a21e1decb9 | ||
|
|
1d564f5732 | ||
|
|
8c92c764b7 | ||
|
|
000fa7a3ad | ||
|
|
6a5b7e014a | ||
|
|
b78c5bb67c | ||
|
|
228576009b | ||
|
|
bc816cb1ae | ||
|
|
cbd9f5db5b | ||
|
|
fef0bc5ea7 | ||
|
|
2bc12eb80b | ||
|
|
ff2123ef58 | ||
|
|
5402da4d80 | ||
|
|
c23612e295 | ||
|
|
11b9e08b1a |
No files matched your search
@@ -22,6 +22,32 @@
|
||||
# Windows runner separates the two without asking anyone to stay off it
|
||||
# for six hours.
|
||||
#
|
||||
# SECOND HUNT, `hunt: release-triple`. Three kinds of jobs in parallel on
|
||||
# ubuntu-24.04, against the code of the ref it is dispatched on (a release
|
||||
# branch plus this file), for failures that show up once in many runs:
|
||||
#
|
||||
# suite the whole e2e suite exactly as e2e.yml runs it (same command, both
|
||||
# passes, four workers), K jobs of R consecutive runs, every run
|
||||
# recorded, none stopping at the first red. One more leg runs the
|
||||
# same command with the processes limited to ONE CPU (`taskset -c
|
||||
# 0`) and is reported on its own line, so its reds are not mixed
|
||||
# into the rate of the ordinary legs. `suite-tally` adds it all up.
|
||||
# webgl tests/test_fingerprint_consistency.py::test_webgl_getParameter_
|
||||
# deterministic, rounds of N pytest processes started together (four
|
||||
# browsers ask for a WebGL context at once, as in the parallel suite).
|
||||
# launch scripts/hunt_launch_close.py: launch, open a page, close, many
|
||||
# times, keeping the engine's own output of every cycle.
|
||||
#
|
||||
# popups (by name only: `all` does not include it) the two popup e2e files
|
||||
# alone, with the suite's parallel-pass options, ONE CPU (taskset -c
|
||||
# 0), on each commit of `popup_shas`: the workflow file comes from the
|
||||
# dispatch ref, the code under test from the commit.
|
||||
#
|
||||
# `which` chooses the hunts of one dispatch: all, suite, webgl, launch, popups or a
|
||||
# comma list (`webgl,launch`). The result of the run is red ONLY when a job
|
||||
# broke (install, fetch, a script error, a run with no verdict). A failure the
|
||||
# hunt caught is reported in the summaries and the job stays green.
|
||||
#
|
||||
# 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.
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@@ -30,6 +56,58 @@ name: e2e hunt
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
hunt:
|
||||
description: "suite-loop = the loop below until it catches a hang (one runner). release-triple = the suite x N, webgl x 52 and launch-close x 300 hunts in parallel jobs, on ubuntu-24.04."
|
||||
required: false
|
||||
default: "suite-loop"
|
||||
type: choice
|
||||
options:
|
||||
- suite-loop
|
||||
- release-triple
|
||||
which:
|
||||
description: "release-triple only: which hunts run. all | suite | webgl | launch | popups | a comma list such as webgl,launch. popups is never part of all"
|
||||
required: false
|
||||
default: "all"
|
||||
suite_jobs:
|
||||
description: "release-triple: parallel jobs of the suite hunt"
|
||||
required: false
|
||||
default: "6"
|
||||
suite_runs_each:
|
||||
description: "release-triple: consecutive full runs in each of those jobs (about 18-20 minutes each)"
|
||||
required: false
|
||||
default: "5"
|
||||
suite_onecpu_runs:
|
||||
description: "release-triple: runs of the extra suite job limited to ONE CPU (taskset -c 0), reported apart; 0 = no such job"
|
||||
required: false
|
||||
default: "2"
|
||||
webgl_rounds:
|
||||
description: "release-triple: rounds of the webgl hunt"
|
||||
required: false
|
||||
default: "13"
|
||||
webgl_procs:
|
||||
description: "release-triple: pytest processes started together in each round (13 x 4 = 52 runs)"
|
||||
required: false
|
||||
default: "4"
|
||||
launch_jobs:
|
||||
description: "release-triple: parallel jobs of the launch-close hunt"
|
||||
required: false
|
||||
default: "3"
|
||||
launch_cycles_each:
|
||||
description: "release-triple: launch-close cycles in each of those jobs (3 x 100 = 300)"
|
||||
required: false
|
||||
default: "100"
|
||||
popup_shas:
|
||||
description: "which=popups: commits or refs to test, comma separated (a90dadc,<new head>). The code under test is checked out from each; this file comes from the dispatch ref."
|
||||
required: false
|
||||
default: ""
|
||||
popup_jobs_each:
|
||||
description: "which=popups: parallel jobs for each commit"
|
||||
required: false
|
||||
default: "5"
|
||||
popup_runs_each:
|
||||
description: "which=popups: consecutive runs of the two popup files in each job (about 50 tests per run, one CPU)"
|
||||
required: false
|
||||
default: "2"
|
||||
runs:
|
||||
description: "How many runs at most (at 12% it takes ~18 for a 90% chance)"
|
||||
required: false
|
||||
@@ -61,6 +139,7 @@ env:
|
||||
jobs:
|
||||
hunt:
|
||||
name: hunt (${{ inputs.os }})
|
||||
if: inputs.hunt == 'suite-loop'
|
||||
runs-on: ${{ inputs.os }}
|
||||
# 18 runs of ~6 minutes plus install time. Deliberately generous: the
|
||||
# ceiling here must NEVER be the thing that stops the hunt, or we're back
|
||||
@@ -152,3 +231,426 @@ jobs:
|
||||
evidence/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# ───────────────────────────────────────────────────────────────────────────
|
||||
# hunt = release-triple. Everything below is skipped for `suite-loop`.
|
||||
# ───────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Decides which hunts run and how big their matrices are (the pure part is
|
||||
# scripts/hunt_report.py `plan`, tested in tests/test_e2e_hunt_triple.py).
|
||||
# A `which` that names no hunt FAILS here, before any runner is spent.
|
||||
plan:
|
||||
name: plan
|
||||
if: inputs.hunt == 'release-triple'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
suite: ${{ steps.plan.outputs.suite }}
|
||||
webgl: ${{ steps.plan.outputs.webgl }}
|
||||
launch: ${{ steps.plan.outputs.launch }}
|
||||
suite_matrix: ${{ steps.plan.outputs.suite_matrix }}
|
||||
launch_matrix: ${{ steps.plan.outputs.launch_matrix }}
|
||||
webgl_timeout: ${{ steps.plan.outputs.webgl_timeout }}
|
||||
popups: ${{ steps.plan.outputs.popups }}
|
||||
popup_matrix: ${{ steps.plan.outputs.popup_matrix }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
# Full history: `popup_shas` may name a short SHA or a branch, and it is
|
||||
# resolved to a full SHA here, once, before any runner is spent.
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 0 }
|
||||
- name: Plan
|
||||
id: plan
|
||||
env:
|
||||
POPUP_SHAS: ${{ inputs.popup_shas }}
|
||||
POPUP_JOBS_EACH: ${{ inputs.popup_jobs_each }}
|
||||
POPUP_RUNS_EACH: ${{ inputs.popup_runs_each }}
|
||||
WHICH: ${{ inputs.which }}
|
||||
SUITE_JOBS: ${{ inputs.suite_jobs }}
|
||||
SUITE_RUNS_EACH: ${{ inputs.suite_runs_each }}
|
||||
ONECPU_RUNS: ${{ inputs.suite_onecpu_runs }}
|
||||
WEBGL_ROUNDS: ${{ inputs.webgl_rounds }}
|
||||
WEBGL_PROCS: ${{ inputs.webgl_procs }}
|
||||
LAUNCH_JOBS: ${{ inputs.launch_jobs }}
|
||||
LAUNCH_CYCLES_EACH: ${{ inputs.launch_cycles_each }}
|
||||
run: |
|
||||
resolved=""
|
||||
IFS=',' read -ra items <<< "$POPUP_SHAS"
|
||||
for x in "${items[@]}"; do
|
||||
x="${x//[[:space:]]/}"
|
||||
if [ -z "$x" ]; then continue; fi
|
||||
sha=$(git rev-parse --verify --quiet "${x}^{commit}" || git rev-parse --verify --quiet "origin/${x}^{commit}" || true)
|
||||
if [ -z "$sha" ]; then
|
||||
echo "::error::popup_shas: cannot resolve '$x' to a commit"
|
||||
exit 2
|
||||
fi
|
||||
resolved="${resolved:+$resolved,}$sha"
|
||||
done
|
||||
python3 scripts/hunt_report.py plan --hunt release-triple --which "$WHICH" \
|
||||
--popup-shas "$resolved" --popup-jobs-each "$POPUP_JOBS_EACH" --popup-runs-each "$POPUP_RUNS_EACH" \
|
||||
--suite-jobs "$SUITE_JOBS" --suite-runs-each "$SUITE_RUNS_EACH" \
|
||||
--onecpu-runs "$ONECPU_RUNS" --webgl-rounds "$WEBGL_ROUNDS" \
|
||||
--webgl-procs "$WEBGL_PROCS" --launch-jobs "$LAUNCH_JOBS" \
|
||||
--launch-cycles-each "$LAUNCH_CYCLES_EACH"
|
||||
|
||||
# A. The whole suite, as e2e.yml runs it, again and again. Ordinary legs run
|
||||
# on every CPU of the runner; the `1-CPU` leg runs the same command under
|
||||
# `taskset -c 0` (the CPU affinity is inherited by xvfb, the four xdist
|
||||
# workers and every browser, and Firefox reads it as its CPU count). Every
|
||||
# run is recorded; nothing stops at the first red.
|
||||
suite:
|
||||
name: ${{ matrix.label }}
|
||||
needs: plan
|
||||
if: needs.plan.outputs.suite == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: ${{ matrix.timeout }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.plan.outputs.suite_matrix) }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
- name: System deps (xvfb + Firefox runtime libs)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
# Only the 1-CPU leg: the affinity really is one CPU, and xdist still
|
||||
# starts its four workers under it (collection runs on the workers).
|
||||
# A failure here is a broken job, not a caught failure.
|
||||
- name: Preflight of the 1-CPU leg
|
||||
if: matrix.taskset != ''
|
||||
run: |
|
||||
taskset -c 0 python -c "import os; print('affinity:', sorted(os.sched_getaffinity(0)))"
|
||||
taskset -c 0 xvfb-run -a python -m pytest -o addopts= -m e2e -n 4 --dist loadfile \
|
||||
--collect-only -q tests/test_fingerprint_consistency.py | tail -5
|
||||
- name: The suite, ${{ matrix.runs }} full runs, every run recorded
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
INVPW_TEST_WATCHDOG_FILE: evidence/e2e-watchdog.log
|
||||
RUNS: ${{ matrix.runs }}
|
||||
LABEL: ${{ matrix.label }}
|
||||
CPUS: ${{ matrix.cpus }}
|
||||
PRE: ${{ matrix.taskset }}
|
||||
run: |
|
||||
set -u
|
||||
mkdir -p evidence/runs
|
||||
for n in $(seq 1 "$RUNS"); do
|
||||
nn=$(printf '%02d' "$n")
|
||||
log="evidence/runs/run_${nn}.log"
|
||||
t0=$(date +%s)
|
||||
set +e
|
||||
# The command of e2e.yml, nothing added; $PRE is empty or `taskset -c 0`.
|
||||
$PRE xvfb-run -a python -u scripts/run_e2e.py "$FF" > "$log" 2>&1
|
||||
code=$?
|
||||
set -e
|
||||
dur=$(( $(date +%s) - t0 ))
|
||||
python scripts/hunt_report.py run-line --log "$log" --out "evidence/runs/run_${nn}.json" \
|
||||
--run "$n" --of "$RUNS" --label "$LABEL" --cpus "$CPUS" --exit "$code" --seconds "$dur"
|
||||
done
|
||||
# Red here = a run without a verdict (broken), never a failed test.
|
||||
- name: Summary of this job
|
||||
if: always()
|
||||
run: python scripts/hunt_report.py suite-summary evidence/runs
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: hunt-suite-${{ matrix.slug }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
evidence/runs
|
||||
evidence/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# What all the legs of A found, added up: the ordinary legs together (the
|
||||
# rate), the 1-CPU leg on its own line.
|
||||
suite-tally:
|
||||
name: suite-tally
|
||||
needs: [plan, suite]
|
||||
if: always() && needs.plan.outputs.suite == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
# Reading the artifacts of this run needs `actions: read`; nothing else is widened.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- name: Download the evidence of every leg
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
ATTEMPT: ${{ github.run_attempt }}
|
||||
run: |
|
||||
mkdir -p all
|
||||
gh run download "$GITHUB_RUN_ID" -R "$GITHUB_REPOSITORY" --pattern "hunt-suite-*-${ATTEMPT}" -D all
|
||||
ls -R all | head -60
|
||||
- name: Tally
|
||||
run: python3 scripts/hunt_report.py suite-tally all
|
||||
|
||||
# B. One test, under contention: `webgl_procs` pytest processes started
|
||||
# together, `webgl_rounds` times, one Xvfb for all of them (as the parallel
|
||||
# suite has). Each process has its own log; the assertion message, which says
|
||||
# why a context is null, is kept whole.
|
||||
webgl:
|
||||
name: webgl ${{ inputs.webgl_rounds }} rounds of ${{ inputs.webgl_procs }}
|
||||
needs: plan
|
||||
if: needs.plan.outputs.webgl == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: ${{ fromJSON(needs.plan.outputs.webgl_timeout) }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
- name: System deps (xvfb + Firefox runtime libs)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The webgl test, rounds of processes started together
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
ROUNDS: ${{ inputs.webgl_rounds }}
|
||||
PROCS: ${{ inputs.webgl_procs }}
|
||||
run: |
|
||||
set -u
|
||||
test_id="tests/test_fingerprint_consistency.py::test_webgl_getParameter_deterministic"
|
||||
mkdir -p evidence/webgl
|
||||
export INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF"
|
||||
Xvfb :99 -screen 0 1280x1024x24 -nolisten tcp > evidence/webgl/xvfb.log 2>&1 &
|
||||
xvfb_pid=$!
|
||||
trap 'kill "$xvfb_pid" 2>/dev/null || true' EXIT
|
||||
for _ in $(seq 1 50); do
|
||||
if [ -e /tmp/.X11-unix/X99 ]; then break; fi
|
||||
sleep 0.2
|
||||
done
|
||||
export DISPLAY=:99
|
||||
for r in $(seq 1 "$ROUNDS"); do
|
||||
rr=$(printf '%02d' "$r")
|
||||
pids=()
|
||||
for p in $(seq 1 "$PROCS"); do
|
||||
base="evidence/webgl/round_${rr}_proc_${p}"
|
||||
(
|
||||
set +e
|
||||
python -u -m pytest "$test_id" -o addopts= -p no:cacheprovider \
|
||||
--timeout 420 --timeout-method thread -v --tb=short \
|
||||
--basetemp "${RUNNER_TEMP}/webgl_${rr}_${p}" > "${base}.log" 2>&1
|
||||
echo $? > "${base}.exit"
|
||||
) &
|
||||
pids+=($!)
|
||||
done
|
||||
wait "${pids[@]}"
|
||||
for p in $(seq 1 "$PROCS"); do
|
||||
base="evidence/webgl/round_${rr}_proc_${p}"
|
||||
python scripts/hunt_report.py webgl-run --log "${base}.log" --out "${base}.json" \
|
||||
--round "$r" --proc "$p" --exit "$(cat "${base}.exit")" --test "$test_id"
|
||||
done
|
||||
done
|
||||
# Red here = a process without a verdict (skipped, killed), never a failed test.
|
||||
- name: Tally
|
||||
if: always()
|
||||
run: python scripts/hunt_report.py webgl-tally evidence/webgl
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: hunt-webgl-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: evidence/webgl
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# C. launch, open one page, close; the engine's output kept for each cycle.
|
||||
launch-close:
|
||||
name: launch-close #${{ matrix.job }} (${{ matrix.cycles }} cycles)
|
||||
needs: plan
|
||||
if: needs.plan.outputs.launch == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: ${{ matrix.timeout }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.plan.outputs.launch_matrix) }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
- name: System deps (xvfb + Firefox runtime libs)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
# The script ends 0 whatever the cycles did (caught); it ends red only if
|
||||
# it could not run (no binary, no psutil).
|
||||
- name: Launch and close, ${{ matrix.cycles }} cycles
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
CYCLES: ${{ matrix.cycles }}
|
||||
START: ${{ matrix.start }}
|
||||
JOB: ${{ matrix.job }}
|
||||
run: |
|
||||
xvfb-run -a python -u scripts/hunt_launch_close.py --binary "$FF" \
|
||||
--cycles "$CYCLES" --start "$START" --job "#$JOB" --out evidence/launch
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: hunt-launch-${{ matrix.job }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: evidence/launch
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# D. The two popup files, on ONE CPU, on each commit of `popup_shas`.
|
||||
# Two checkouts: the dispatch ref into hunt-tools/ (this workflow's scripts)
|
||||
# and the commit under test into code/ (installed, and the tests run from
|
||||
# it). The command is the suite's own entry, `scripts/run_e2e.py` of THAT
|
||||
# commit with `-n 4` (its default), so the pytest options of the parallel pass
|
||||
# (loadfile, reruns policy, deadline) are not copied here: they are the
|
||||
# commit's. The files named after the binary narrow both of its passes; the
|
||||
# second pass (wall_clock tests alone) finds nothing in these files and ends
|
||||
# with "nothing collected", which the entry does not count.
|
||||
popups:
|
||||
name: ${{ matrix.label }}
|
||||
needs: plan
|
||||
if: needs.plan.outputs.popups == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: ${{ matrix.timeout }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.plan.outputs.popup_matrix) }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1, path: hunt-tools }
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { ref: "${{ matrix.sha }}", fetch-depth: 1, path: code }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install the commit under test (+ Playwright ONLY as a system tool)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install "./code[dev]"
|
||||
python -m pip install "playwright==$(cat code/scripts/playwright_pin.txt)"
|
||||
- name: System deps (xvfb + Firefox runtime libs)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
# One CPU for real, and four xdist workers still start under it. A
|
||||
# failure here is a broken job, not a caught failure.
|
||||
- name: Preflight, one CPU and the workers
|
||||
run: |
|
||||
taskset -c 0 python -c "import os; print('affinity:', sorted(os.sched_getaffinity(0)))"
|
||||
cd code
|
||||
taskset -c 0 xvfb-run -a python -m pytest -o addopts= -m e2e -n 4 --dist loadfile \
|
||||
--collect-only -q tests/test_popup_destinations_e2e.py tests/test_popups_reach_the_client_e2e.py | tail -4
|
||||
- name: The popup files, ${{ matrix.runs }} runs in a row on one CPU
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
INVPW_TEST_WATCHDOG_FILE: ${{ github.workspace }}/evidence/e2e-watchdog.log
|
||||
RUNS: ${{ matrix.runs }}
|
||||
LABEL: ${{ matrix.label }}
|
||||
SHA: ${{ matrix.sha }}
|
||||
run: |
|
||||
set -u
|
||||
mkdir -p evidence/runs
|
||||
for n in $(seq 1 "$RUNS"); do
|
||||
nn=$(printf '%02d' "$n")
|
||||
log="evidence/runs/run_${nn}.log"
|
||||
t0=$(date +%s)
|
||||
set +e
|
||||
( cd code && taskset -c 0 xvfb-run -a python -u scripts/run_e2e.py "$FF" \
|
||||
tests/test_popup_destinations_e2e.py tests/test_popups_reach_the_client_e2e.py ) > "$log" 2>&1
|
||||
code=$?
|
||||
set -e
|
||||
dur=$(( $(date +%s) - t0 ))
|
||||
python hunt-tools/scripts/hunt_report.py run-line --log "$log" --out "evidence/runs/run_${nn}.json" \
|
||||
--run "$n" --of "$RUNS" --label "$LABEL" --cpus 1 --sha "$SHA" --exit "$code" --seconds "$dur"
|
||||
done
|
||||
# Red here = a run without a verdict (broken), never a failed test.
|
||||
- name: Summary of this job
|
||||
if: always()
|
||||
run: python hunt-tools/scripts/hunt_report.py suite-summary evidence/runs
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: hunt-popups-${{ matrix.slug }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
evidence/runs
|
||||
evidence/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# Per commit: runs, runs with a red, each failed test and its whole messages,
|
||||
# and each red run as "attachment / run.popups empty" or "other".
|
||||
popups-tally:
|
||||
name: popups-tally
|
||||
needs: [plan, popups]
|
||||
if: always() && needs.plan.outputs.popups == 'true'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- name: Download the evidence of every job
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
ATTEMPT: ${{ github.run_attempt }}
|
||||
run: |
|
||||
mkdir -p all
|
||||
gh run download "$GITHUB_RUN_ID" -R "$GITHUB_REPOSITORY" --pattern "hunt-popups-*-${ATTEMPT}" -D all
|
||||
ls -R all | head -60
|
||||
- name: Tally
|
||||
run: python3 scripts/hunt_report.py popups-tally all
|
||||
+26
-1
@@ -6,7 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.50.0] - 2026-11-11
|
||||
## [0.50.1] - 2026-11-11
|
||||
|
||||
0.50.0 was tagged and never published: its end-to-end gate was red on two tests that counted processes.
|
||||
0.50.1 is 0.50.0 with those tests corrected.
|
||||
|
||||
### Changed
|
||||
- Engine firefox-62 through invisible-core 62.63.0, which this version pins: firefox-61 plus Fission
|
||||
@@ -23,6 +26,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
iframe and of its page) run on that engine.
|
||||
|
||||
### Fixed
|
||||
- `goto(wait_until="networkidle")` arrives on a page that is reused for many addresses, and on a served browser whose
|
||||
context routes every request, as with a stock Firefox. Two causes, both ours. A route answered after the browser had
|
||||
already closed its request (a fetch the page aborted, an image it replaced, an iframe it removed, a beacon cancelled
|
||||
with its document) came back to the client as an error, which the client kept for the whole connection and raised on the
|
||||
next route command; that command was never sent, its request stayed held in the engine, and so on down the page. The
|
||||
server now takes such an answer as done, whatever wording the engine gives it ("Cannot find request", or "NS_BINDING_ABORTED"
|
||||
when the channel was cancelled while the answer was on its way), as Playwright's own server does. The same defect was found a month earlier by richardpowellus
|
||||
(#351), on the favicon of the page a `goto` had just left; his test is part of this release. And the core counted the requests in flight
|
||||
with one integer per page, never reset by a navigation, so one request whose end never arrived kept every later address
|
||||
from going idle (invisible-core 62.64.0 keeps them by request id, per document, and does not keep the requests of a
|
||||
frame that already left: a beacon sent at `pagehide` is announced after its frame is gone).
|
||||
- A `goto` sent right after `new_page` is no longer "interrupted by another navigation to about:blank" on a loaded machine. The page was
|
||||
handed to the caller as soon as its main frame was announced, while the engine had not yet committed the page's own initial
|
||||
`about:blank`; a navigation answered before that commit lost to it. The page is now handed over when the engine says it is
|
||||
ready (`Page.ready`), as Playwright's own page is (invisible-core 62.65.0, `Lifecycle.wait_for_page_ready`; a page closed before
|
||||
it was ready ends the wait with an error at once).
|
||||
- A launch that names no session (Playwright's own `BrowserType.launch` against the server) gets a
|
||||
session composed the way `InvisiblePlaywright()` composes one: prefs, environment and, behind a
|
||||
proxy, the egress the page reads as its WebRTC address. It used to come up with Mozilla's
|
||||
@@ -37,6 +56,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
(`geolocation`, `persistent-storage`, `push`, `notifications`, `screen-wake-lock`); any other name
|
||||
raises `Unknown permission`, as it does there, and a grant with no origin is a grant for every
|
||||
origin.
|
||||
- The end-to-end tests that count content processes count the ones that host a site, not every content
|
||||
process that is new. The engine keeps a pool of preallocated processes and refills it whenever it gets
|
||||
to it, so a refill landing between two reads looked like a process the test had caused (a same-site
|
||||
frame, a closed context with a service worker that never stops). Measured on firefox-62: a closed context
|
||||
leaves no process of its site. On Linux the process is named by the site it hosts; elsewhere these
|
||||
tests skip.
|
||||
|
||||
## [0.49.1] - 2026-11-10
|
||||
|
||||
|
||||
@@ -233,11 +233,11 @@ invisible-playwright version # wrapper, core and engine versions, and where the
|
||||
**If you would rather prompt than script.** This page is the engine, as a Python
|
||||
library. Two ways to use it without writing code, both one line: from an MCP client
|
||||
you already have (Claude Code, Claude Desktop, Cursor),
|
||||
`claude mcp add stealth -- uvx aihawk`, see
|
||||
[the MCP server page](https://github.com/feder-cr/AIHawk/wiki/mcp-server); or with an
|
||||
`claude mcp add stealth -- uvx invisible-playwright-mcp`, see
|
||||
[the MCP server page](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server); or with an
|
||||
interface and a model included, needing only an OpenRouter key,
|
||||
`uvx aihawk ui --openrouter-key sk-or-...`, see
|
||||
[AIHawk](https://github.com/feder-cr/AIHawk). Same engine underneath, and the second
|
||||
`uvx invisible-playwright-mcp ui --openrouter-key sk-or-...`, see
|
||||
[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp). Same engine underneath, and the second
|
||||
is a client of the first.
|
||||
|
||||
All of it reads better, and is searchable, in
|
||||
@@ -281,8 +281,8 @@ two around it are how most people reach it:
|
||||
|
||||
- **[invisible_core](https://github.com/feder-cr/invisible_core)** - seed to
|
||||
fingerprint to preferences, plus proxy and geolocation. This package pins it.
|
||||
- **[AIHawk](https://github.com/feder-cr/AIHawk)** - this engine as an MCP
|
||||
server (`uvx aihawk`, for any client that brings its own
|
||||
- **[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp)** - this engine as an MCP
|
||||
server (`uvx invisible-playwright-mcp`, for any client that brings its own
|
||||
model) and, in the same package, an interface with a model included, from
|
||||
one command. The interface is a client of the server, with no private path
|
||||
to the browser.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "AI agent retry loops trip rate limits, not fingerprints"
|
||||
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the AIHawk wiki."
|
||||
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the invisible_playwright_mcp wiki."
|
||||
parent: "AI Agents and Frameworks"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 17
|
||||
@@ -9,10 +9,10 @@ nav_order: 17
|
||||
|
||||
# AI agent retry loops trip rate limits, not fingerprints
|
||||
|
||||
This page moved to the AIHawk wiki, where the agent-experience content now
|
||||
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
|
||||
lives:
|
||||
|
||||
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/AIHawk/wiki/agent-retry-loops-rate-limits)**
|
||||
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/invisible_playwright_mcp/wiki/agent-retry-loops-rate-limits)**
|
||||
|
||||
The one-paragraph version: an agent that retries and re-plans multiplies its
|
||||
requests, and volume is scored server-side against your address and account.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Why AI browser agents have their own timing signal"
|
||||
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the AIHawk wiki."
|
||||
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the invisible_playwright_mcp wiki."
|
||||
parent: "AI Agents and Frameworks"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 10
|
||||
@@ -9,10 +9,10 @@ nav_order: 10
|
||||
|
||||
# Why AI browser agents have their own timing signal
|
||||
|
||||
This page moved to the AIHawk wiki, where the agent-experience content now
|
||||
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
|
||||
lives:
|
||||
|
||||
**[The timing signal AI agents give off](https://github.com/feder-cr/AIHawk/wiki/ai-agent-timing-signal)**
|
||||
**[The timing signal AI agents give off](https://github.com/feder-cr/invisible_playwright_mcp/wiki/ai-agent-timing-signal)**
|
||||
|
||||
The short version it still owes you here: a think-act loop pauses for model
|
||||
latency, and that pause repeats with a regularity no human produces. The
|
||||
|
||||
@@ -224,7 +224,7 @@ this whole page is about.
|
||||
one. Pick on the agent loop, then fix the machine, then consider the engine.
|
||||
|
||||
**Is there any agent route to an engine-level fingerprint?** Two, and they are not
|
||||
equivalent. `uvx aihawk` launches through the engine, so the
|
||||
equivalent. `uvx invisible-playwright-mcp` launches through the engine, so the
|
||||
seeded profile and the humanised pointer come with it. Microsoft's own Playwright
|
||||
MCP server takes a browser and an executable path, which runs the engine but
|
||||
carries no `firefox_user_prefs`, so every session on a given build shares one
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "browser-use gets detected: what you can and cannot change"
|
||||
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the AIHawk wiki."
|
||||
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the invisible_playwright_mcp wiki."
|
||||
parent: "AI Agents and Frameworks"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 2
|
||||
@@ -9,10 +9,10 @@ nav_order: 2
|
||||
|
||||
# browser-use gets detected: what you can and cannot change
|
||||
|
||||
This page moved to the AIHawk wiki, where the agent-experience content now
|
||||
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
|
||||
lives:
|
||||
|
||||
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/AIHawk/wiki/browser-use-getting-blocked)**
|
||||
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/invisible_playwright_mcp/wiki/browser-use-getting-blocked)**
|
||||
|
||||
The unchanged short answer: browser-use exposes a real set of levers
|
||||
(`executable_path`, `user_data_dir`, `proxy`, `headless`, `args`), all of
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Computer-use agents and browser fingerprint detection"
|
||||
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the AIHawk wiki."
|
||||
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the invisible_playwright_mcp wiki."
|
||||
parent: "AI Agents and Frameworks"
|
||||
grand_parent: "Guides"
|
||||
nav_order: 6
|
||||
@@ -9,10 +9,10 @@ nav_order: 6
|
||||
|
||||
# Computer-use agents and browser fingerprint detection
|
||||
|
||||
This page moved to the AIHawk wiki, retargeted at the question people
|
||||
This page moved to the invisible_playwright_mcp wiki, retargeted at the question people
|
||||
actually search:
|
||||
|
||||
**[Claude computer use detected as a bot](https://github.com/feder-cr/AIHawk/wiki/claude-computer-use-detected-as-bot)**
|
||||
**[Claude computer use detected as a bot](https://github.com/feder-cr/invisible_playwright_mcp/wiki/claude-computer-use-detected-as-bot)**
|
||||
|
||||
The core of it, kept here in brief: a coordinate-clicking agent never
|
||||
generates the DOM-automation tells, so `navigator.webdriver` advice mostly
|
||||
|
||||
@@ -20,7 +20,7 @@ Playwright, or not to touch Firefox, at all.
|
||||
These pages are for developers wiring an agent to this engine. The
|
||||
agent-experience side - what to run, which agent products compare how, what to
|
||||
check when an agent gets blocked - lives on the
|
||||
[AIHawk wiki](https://github.com/feder-cr/AIHawk/wiki), the agent built on this
|
||||
[invisible_playwright_mcp wiki](https://github.com/feder-cr/invisible_playwright_mcp/wiki), the agent built on this
|
||||
same engine.
|
||||
|
||||
## Framework integrations
|
||||
@@ -34,15 +34,15 @@ same engine.
|
||||
## Computer-use and screenshot agents
|
||||
|
||||
- [Back a computer-use agent with a real browser engine](back-computer-use-agent-real-browser.md) - implement the screenshot-and-click Computer interface over an invisible_playwright page, and its honest limits.
|
||||
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the AIHawk wiki; the page here points across.)
|
||||
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
|
||||
- [DOM-reading vs screenshot agents: which stealth helps](dom-reading-vs-screenshot-agents.md) - which stealth signal helps depends on whether the agent reads DOM or clicks pixels.
|
||||
|
||||
## How AI agents get detected
|
||||
|
||||
- [AI browser agents and stealth: what fits and what does not](ai-browser-agents-stealth.md) - most agents drive Chromium over CDP, so a stealth Firefox does not drop in.
|
||||
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the AIHawk wiki; the page here points across.)
|
||||
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the AIHawk wiki; the page here points across.)
|
||||
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the AIHawk wiki; the page here points across.)
|
||||
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
|
||||
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
|
||||
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
|
||||
- [Playwright 1.62 Ships MCP In the Box](playwright-162-built-in-mcp.md) - the MCP server and a new playwright-cli are now bundled into core, runnable via `npx playwright mcp` with no separate install.
|
||||
|
||||
## Running agents at scale and on servers
|
||||
|
||||
+2
-2
@@ -22,8 +22,8 @@ the thing it describes, and several of them record something we got wrong first.
|
||||
- **[Integrations](integrations/)** - running this inside Scrapy, Crawlee, Robot
|
||||
Framework, CodeceptJS, test runners and Playwright MCP, including which frameworks
|
||||
it does not fit and why.
|
||||
- **[The agent on top](https://github.com/feder-cr/AIHawk/wiki)** - this engine also
|
||||
drives [AIHawk](https://github.com/feder-cr/AIHawk), an AI agent you instruct in
|
||||
- **[The agent on top](https://github.com/feder-cr/invisible_playwright_mcp/wiki)** - this engine also
|
||||
drives [invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp), an AI agent you instruct in
|
||||
plain language; its wiki covers the agent layer the way this one covers the
|
||||
browser: comparisons, blocked agents, and task guides.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Using invisible_playwright with Microsoft's Playwright MCP"
|
||||
description: "There is a server for this engine, inside AIHawk: uvx aihawk. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
|
||||
description: "There is a server for this engine: uvx invisible-playwright-mcp. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
|
||||
parent: "Integrations"
|
||||
nav_order: 7
|
||||
---
|
||||
@@ -8,13 +8,12 @@ nav_order: 7
|
||||
# Using invisible_playwright with Microsoft's Playwright MCP
|
||||
|
||||
**There is a server for this engine:**
|
||||
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
|
||||
shipped inside AIHawk.
|
||||
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server).
|
||||
One line, and it carries the seeded profile and the humanised pointer that the
|
||||
route on this page cannot:
|
||||
|
||||
```bash
|
||||
claude mcp add stealth -- uvx aihawk
|
||||
claude mcp add stealth -- uvx invisible-playwright-mcp
|
||||
```
|
||||
|
||||
This page is for the other case: you are already committed to Microsoft's
|
||||
@@ -122,8 +121,8 @@ knowing before you trust the session.
|
||||
## Short answers to the questions that lead here
|
||||
|
||||
**Is there an MCP server for this project?** Yes:
|
||||
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
|
||||
`uvx aihawk`. It launches through the engine, so the seeded
|
||||
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server),
|
||||
`uvx invisible-playwright-mcp`. It launches through the engine, so the seeded
|
||||
profile and the humanised pointer come with it.
|
||||
|
||||
Microsoft's own `playwright-mcp` also accepts `--browser firefox` together with
|
||||
|
||||
@@ -189,8 +189,8 @@ supply a clean IP, human pacing, and session reuse for the layers a browser cann
|
||||
[how to test whether the browser itself is the problem](how-to-test-bot-detection.md), and
|
||||
[rate limiting your scraper so volume stops being the signal](how-to-rate-limit-your-scraper-playwright.md).
|
||||
If the traffic is produced by an AI agent rather than a script, the pacing and
|
||||
retry layers have their own failure modes, mapped on the AIHawk wiki:
|
||||
[why does my AI agent get blocked?](https://github.com/feder-cr/AIHawk/wiki/why-does-my-ai-agent-get-blocked)
|
||||
retry layers have their own failure modes, mapped on the invisible_playwright_mcp wiki:
|
||||
[why does my AI agent get blocked?](https://github.com/feder-cr/invisible_playwright_mcp/wiki/why-does-my-ai-agent-get-blocked)
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.50.0"
|
||||
version = "0.50.1"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
@@ -69,7 +69,7 @@ dependencies = [
|
||||
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
|
||||
# fails if one appears). What stays invisible to install-time machinery is the
|
||||
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
|
||||
"invisible_core==62.63.0",
|
||||
"invisible_core==62.65.0",
|
||||
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
|
||||
# client lives in src/invisible_playwright/_pw/ and its server in
|
||||
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Launch the browser, open one page, close everything - many times - and keep
|
||||
what the engine said each time.
|
||||
|
||||
python scripts/hunt_launch_close.py --binary <firefox> --cycles 100 --out evidence/launch
|
||||
|
||||
It exists to find where `BrowserType.launch: [Errno 32] Broken pipe` comes from. That
|
||||
message is a `BrokenPipeError` from the first write of the launch to a browser that has
|
||||
already exited: the launch gives no exit code and no output with it, so the reason the
|
||||
engine went away is lost unless somebody keeps the engine's output. This script keeps it.
|
||||
|
||||
Each cycle is a CHILD process (`--one`), so an exit status exists per cycle and a cycle
|
||||
cannot poison the next. The child:
|
||||
|
||||
* launches the way the tests do (`InvisiblePlaywright` as a context manager, the fetched
|
||||
binary, `humanize=False`), opens one page on about:blank and leaves the block;
|
||||
* records the engine's output. The engine's stdout and stderr are ONE pipe that the core
|
||||
reads with `invisible_core.juggler.connection.ProcessOutput` and keeps (last 200
|
||||
lines); the public API does not hand that object out, so the child records every
|
||||
instance that is created (a wrapper on its constructor, in this script, no product code
|
||||
is changed) and writes their kept lines to `engine.log` in its `finally`, also when the
|
||||
launch itself failed. If the core on the machine has no such class the child says so in
|
||||
`engine.log` and the cycle's record says `engine_captured: false`;
|
||||
* leaves its own stderr and stdout to the parent, which writes them to `stderr.log` and
|
||||
`stdout.log` (the launcher's logging and the traceback are there).
|
||||
|
||||
The parent then records: exit status, duration, whether `Broken pipe` (any case) appears in
|
||||
what was captured and in which file, and how many processes of the browser binary are left
|
||||
(they must be 0; leftovers are counted, then killed so one leak cannot cascade).
|
||||
|
||||
Caught failures (a cycle that fails) are the result; the script ends 0. It ends non-zero
|
||||
only when it could not run at all (no binary, no way to count processes).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
MARKER = "broken pipe"
|
||||
CONTEXT = 6 # lines kept on each side of a hit
|
||||
CYCLE_TIMEOUT_S = 240
|
||||
ENGINE_LOG = "engine.log"
|
||||
CAPTURED_HEADER = "=== engine output"
|
||||
|
||||
|
||||
# ── pure parts ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def find_marker(text: str, marker: str = MARKER, context: int = CONTEXT) -> list[str]:
|
||||
"""Every hit of `marker` (any case) with `context` lines on each side, whole.
|
||||
Hits whose windows touch are one excerpt."""
|
||||
lines = text.splitlines()
|
||||
hits = [i for i, line in enumerate(lines) if marker.lower() in line.lower()]
|
||||
out: list[str] = []
|
||||
start = end = None
|
||||
for i in hits:
|
||||
lo, hi = max(0, i - context), min(len(lines), i + context + 1)
|
||||
if start is not None and lo <= end:
|
||||
end = hi
|
||||
continue
|
||||
if start is not None:
|
||||
out.append("\n".join(lines[start:end]))
|
||||
start, end = lo, hi
|
||||
if start is not None:
|
||||
out.append("\n".join(lines[start:end]))
|
||||
return out
|
||||
|
||||
|
||||
def count_browser_processes(processes, binary: str) -> int:
|
||||
"""How many of `processes` (pairs of exe path and argv) are the browser `binary`
|
||||
or its children (content processes are the same executable)."""
|
||||
wanted = os.path.normcase(os.path.realpath(binary))
|
||||
n = 0
|
||||
for exe, argv in processes:
|
||||
first = argv[0] if argv else ""
|
||||
for candidate in (exe, first):
|
||||
if candidate and os.path.normcase(os.path.realpath(candidate)) == wanted:
|
||||
n += 1
|
||||
break
|
||||
return n
|
||||
|
||||
|
||||
def cycle_record(*, cycle: int, headless: bool, status, seconds: float, captured: dict,
|
||||
leftover: int, engine_captured: bool) -> dict:
|
||||
"""`captured` maps a file name to its text; `status` is the child's exit code, or
|
||||
'timeout'."""
|
||||
hits = {name: find_marker(text) for name, text in captured.items()}
|
||||
where = sorted(name for name, found in hits.items() if found)
|
||||
return {"cycle": cycle, "headless": headless, "status": status,
|
||||
"ok": status == 0 and leftover == 0, "seconds": round(seconds, 2),
|
||||
"broken_pipe": bool(where), "broken_pipe_in": where,
|
||||
"excerpts": {name: found for name, found in hits.items() if found},
|
||||
"leftover": leftover, "engine_captured": engine_captured}
|
||||
|
||||
|
||||
def tally(records: list[dict]) -> dict:
|
||||
return {
|
||||
"cycles": len(records),
|
||||
"failures": sum(1 for r in records if r["status"] != 0),
|
||||
"broken_pipe": sum(1 for r in records if r["broken_pipe"]),
|
||||
"leftover_cycles": sum(1 for r in records if r["leftover"] > 0),
|
||||
"leftover_processes": sum(max(0, r["leftover"]) for r in records),
|
||||
"engine_not_captured": sum(1 for r in records if not r["engine_captured"]),
|
||||
}
|
||||
|
||||
|
||||
def render_summary(records: list[dict], job: str = "") -> str:
|
||||
t = tally(records)
|
||||
out = ["### launch-close %s" % job, "",
|
||||
"Caught results (the job stays green): cycles that failed, `Broken pipe`, leftovers. "
|
||||
"Broken (the job ends red): the script could not run.", "",
|
||||
"| cycles | failed | with `Broken pipe` | cycles with leftover processes | engine output missing |",
|
||||
"|---|---|---|---|---|",
|
||||
"| %(cycles)d | %(failures)d | %(broken_pipe)d | %(leftover_cycles)d | %(engine_not_captured)d |" % t]
|
||||
bad = [r for r in records if r["status"] != 0 or r["leftover"] > 0 or r["broken_pipe"]]
|
||||
if bad:
|
||||
out += ["", "| cycle | headless | status | seconds | Broken pipe in | leftover |", "|---|---|---|---|---|---|"]
|
||||
for r in bad:
|
||||
out.append("| %d | %s | %s | %s | %s | %d |" % (
|
||||
r["cycle"], r["headless"], r["status"], r["seconds"],
|
||||
", ".join(r["broken_pipe_in"]) or "-", r["leftover"]))
|
||||
for r in records:
|
||||
for name, excerpts in r["excerpts"].items():
|
||||
for excerpt in excerpts:
|
||||
out += ["", "Cycle %d, `%s`, around `Broken pipe`:" % (r["cycle"], name), "", "```", excerpt, "```"]
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
# ── the child: one cycle ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _install_output_capture():
|
||||
"""Record every `ProcessOutput` the core creates. None when the core has none."""
|
||||
try:
|
||||
from invisible_core.juggler import connection
|
||||
except ImportError:
|
||||
return None
|
||||
cls = getattr(connection, "ProcessOutput", None)
|
||||
if cls is None:
|
||||
return None
|
||||
seen: list = []
|
||||
original = cls.__init__
|
||||
|
||||
def recording_init(self, *args, **kwargs):
|
||||
original(self, *args, **kwargs)
|
||||
seen.append(self)
|
||||
|
||||
cls.__init__ = recording_init
|
||||
return seen
|
||||
|
||||
|
||||
def _write_engine_log(path: Path, seen) -> None:
|
||||
parts: list[str] = []
|
||||
if seen is None:
|
||||
parts.append("(engine output NOT captured: invisible_core.juggler.connection.ProcessOutput not found)")
|
||||
elif not seen:
|
||||
parts.append("%s: none (no browser process was started by this cycle)" % CAPTURED_HEADER)
|
||||
for i, out in enumerate(seen or [], 1):
|
||||
try:
|
||||
out.settle()
|
||||
except Exception as exc: # noqa: BLE001 - the log must be written whatever happens
|
||||
parts.append("(settle failed: %r)" % (exc,))
|
||||
keep = getattr(out, "KEEP", 200)
|
||||
parts.append("%s %d of %d (last %d lines, stdout+stderr of the engine) ===" % (
|
||||
CAPTURED_HEADER, i, len(seen), keep))
|
||||
parts += out.tail(keep)
|
||||
path.write_text("\n".join(parts) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def run_one(binary: str, engine_log: Path, headless: bool) -> int:
|
||||
seen = _install_output_capture()
|
||||
try:
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, humanize=False,
|
||||
headless=headless) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
return 0
|
||||
except BaseException: # noqa: BLE001 - the traceback is the evidence
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
finally:
|
||||
_write_engine_log(engine_log, seen)
|
||||
|
||||
|
||||
# ── the parent: the loop ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _processes():
|
||||
import psutil
|
||||
for proc in psutil.process_iter(["exe", "cmdline", "pid"]):
|
||||
info = proc.info
|
||||
yield proc, (info.get("exe") or "", info.get("cmdline") or [])
|
||||
|
||||
|
||||
def _leftovers(binary: str) -> int:
|
||||
"""Browser processes alive now; they are killed after being counted."""
|
||||
deadline = time.monotonic() + 3.0 # the engine's tree takes a moment to go
|
||||
while True:
|
||||
alive = [proc for proc, (exe, argv) in _processes()
|
||||
if count_browser_processes([(exe, argv)], binary)]
|
||||
if not alive or time.monotonic() >= deadline:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
for proc in alive:
|
||||
try:
|
||||
proc.kill()
|
||||
except Exception: # noqa: BLE001 - already gone
|
||||
pass
|
||||
return len(alive)
|
||||
|
||||
|
||||
def _read(path: Path) -> str:
|
||||
try:
|
||||
return path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH"))
|
||||
ap.add_argument("--cycles", type=int, default=100)
|
||||
ap.add_argument("--start", type=int, default=1, help="number of the first cycle")
|
||||
ap.add_argument("--out", default="evidence/launch")
|
||||
ap.add_argument("--job", default="")
|
||||
ap.add_argument("--headless", choices=("yes", "no", "alternate"), default="alternate",
|
||||
help="the library's headless flag; alternate = odd cycles headed, even headless")
|
||||
ap.add_argument("--one", metavar="ENGINE_LOG", help="(internal) run one cycle in this process")
|
||||
args = ap.parse_args(argv)
|
||||
if not args.binary or not Path(args.binary).exists():
|
||||
print("hunt_launch_close: binary not found: %r" % args.binary, file=sys.stderr)
|
||||
return 2
|
||||
if args.one:
|
||||
return run_one(args.binary, Path(args.one), args.headless == "yes")
|
||||
try:
|
||||
import psutil # noqa: F401
|
||||
except ImportError:
|
||||
print("hunt_launch_close: psutil is needed to count leftover processes", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
out_dir = Path(args.out)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
records = []
|
||||
for cycle in range(args.start, args.start + args.cycles):
|
||||
headless = {"yes": True, "no": False}.get(args.headless, cycle % 2 == 0)
|
||||
d = out_dir / ("cycle_%04d" % cycle)
|
||||
d.mkdir(exist_ok=True)
|
||||
cmd = [sys.executable, "-u", str(Path(__file__).resolve()), "--binary", args.binary,
|
||||
"--headless", "yes" if headless else "no", "--one", str(d / ENGINE_LOG)]
|
||||
t0 = time.monotonic()
|
||||
with open(d / "stdout.log", "wb") as so, open(d / "stderr.log", "wb") as se:
|
||||
try:
|
||||
status = subprocess.run(cmd, stdout=so, stderr=se, timeout=CYCLE_TIMEOUT_S).returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
status = "timeout"
|
||||
seconds = time.monotonic() - t0
|
||||
leftover = _leftovers(args.binary)
|
||||
engine_text = _read(d / ENGINE_LOG)
|
||||
engine_captured = CAPTURED_HEADER in engine_text
|
||||
rec = cycle_record(cycle=cycle, headless=headless, status=status, seconds=seconds,
|
||||
captured={ENGINE_LOG: engine_text, "stderr.log": _read(d / "stderr.log"),
|
||||
"stdout.log": _read(d / "stdout.log")},
|
||||
leftover=leftover, engine_captured=engine_captured)
|
||||
(d / "record.json").write_text(json.dumps(rec, indent=1), encoding="utf-8")
|
||||
records.append(rec)
|
||||
print("cycle %d headless=%s status=%s %.1fs broken_pipe=%s leftover=%d engine_captured=%s" % (
|
||||
cycle, headless, status, seconds, "YES(%s)" % ",".join(rec["broken_pipe_in"]) if rec["broken_pipe"] else "no",
|
||||
leftover, engine_captured), flush=True)
|
||||
text = render_summary(records, args.job)
|
||||
(out_dir / "summary.md").write_text(text, encoding="utf-8")
|
||||
(out_dir / "summary.json").write_text(json.dumps(tally(records), indent=1), encoding="utf-8")
|
||||
print(text)
|
||||
summary = os.environ.get("GITHUB_STEP_SUMMARY")
|
||||
if summary:
|
||||
with open(summary, "a", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,519 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The pure parts of `.github/workflows/e2e-hunt.yml` (hunt = release-triple).
|
||||
|
||||
Standard library only: the plan job runs it before anything is installed.
|
||||
|
||||
python scripts/hunt_report.py plan --hunt H --which W ... # matrices for the workflow
|
||||
python scripts/hunt_report.py run-line --log L --out J ... # one full suite run -> one line + json
|
||||
python scripts/hunt_report.py suite-summary DIR # table of the runs one job made
|
||||
python scripts/hunt_report.py suite-tally DIR # all jobs, all runs, distinct messages
|
||||
python scripts/hunt_report.py popups-tally DIR # per commit: reds, messages, attachment vs other
|
||||
python scripts/hunt_report.py webgl-run --log L --out J ... # one pytest process -> pass/fail + message
|
||||
python scripts/hunt_report.py webgl-tally DIR # n failed of N, distinct reasons
|
||||
|
||||
What is a CAUGHT failure and what is not. A test that fails, in a run that ended
|
||||
with a pytest summary, is what the hunt looks for: it is recorded and the job
|
||||
stays green. A run that produced no verdict at all (the exit code is not 0 or 1,
|
||||
or there is no summary line, or the test was skipped) is a BROKEN run: the job
|
||||
ends red after it has recorded everything, because there the hunt itself did not
|
||||
work.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = ["classify_popup_failure", "popups_tally", "make_plan", "parse_pytest_log", "run_record", "suite_summary", "suite_tally",
|
||||
"webgl_record", "webgl_tally", "normalise"]
|
||||
|
||||
# ── the plan ────────────────────────────────────────────────────────────────
|
||||
|
||||
HUNTS = ("suite", "webgl", "launch")
|
||||
#: Chosen by name only: `all` does not include it, because it needs commits to test.
|
||||
EXPLICIT_ONLY = ("popups",)
|
||||
_POPUP_RUN_MIN = 45
|
||||
#: Minutes one full suite run may take; a run is 18-20 on four CPUs. The job
|
||||
#: ceiling must never be the thing that stops a hunt, so it is generous.
|
||||
_SUITE_RUN_MIN = 30
|
||||
_ONE_CPU_RUN_MIN = 100
|
||||
_MAX_JOB_MIN = 355
|
||||
|
||||
|
||||
def _which(which: str) -> set[str]:
|
||||
"""`all`, or a comma list of suite / webgl / launch. Anything else is an error."""
|
||||
names = {w.strip().lower() for w in which.split(",") if w.strip()}
|
||||
if not names:
|
||||
raise ValueError("`which` is empty: use all, suite, webgl, launch or a comma list")
|
||||
if "all" in names:
|
||||
names = set(HUNTS) | (names - {"all"})
|
||||
bad = sorted(names - set(HUNTS) - set(EXPLICIT_ONLY))
|
||||
if bad:
|
||||
raise ValueError("`which` names %s; the hunts are %s, popups (by name only), or all"
|
||||
% (bad, ", ".join(HUNTS)))
|
||||
return names
|
||||
|
||||
|
||||
def make_plan(*, which: str, suite_jobs: int, suite_runs_each: int, onecpu_runs: int,
|
||||
webgl_rounds: int, webgl_procs: int, launch_jobs: int,
|
||||
launch_cycles_each: int, popup_shas: str = "", popup_jobs_each: int = 5,
|
||||
popup_runs_each: int = 2) -> dict:
|
||||
"""What one dispatch runs: three flags and the matrices.
|
||||
|
||||
The suite matrix has `suite_jobs` ordinary legs of `suite_runs_each` runs, and one
|
||||
more leg, labelled, whose processes are limited to ONE CPU (`taskset -c 0`) for
|
||||
`onecpu_runs` runs: its reds are reported on their own line and never counted in
|
||||
the rate of the ordinary legs.
|
||||
"""
|
||||
names = _which(which)
|
||||
for key, value in (("suite_jobs", suite_jobs), ("suite_runs_each", suite_runs_each),
|
||||
("onecpu_runs", onecpu_runs), ("webgl_rounds", webgl_rounds),
|
||||
("webgl_procs", webgl_procs), ("launch_jobs", launch_jobs),
|
||||
("launch_cycles_each", launch_cycles_each)):
|
||||
if value < 0:
|
||||
raise ValueError("%s must not be negative" % key)
|
||||
legs = []
|
||||
for k in range(1, suite_jobs + 1):
|
||||
if suite_runs_each > 0:
|
||||
legs.append({"label": "suite x%d #%d" % (suite_runs_each, k), "slug": "suite-%d" % k,
|
||||
"runs": suite_runs_each, "cpus": "all", "taskset": "",
|
||||
"timeout": min(_MAX_JOB_MIN, suite_runs_each * _SUITE_RUN_MIN + 30)})
|
||||
if onecpu_runs > 0:
|
||||
legs.append({"label": "suite 1-CPU x%d" % onecpu_runs, "slug": "suite-1cpu",
|
||||
"runs": onecpu_runs, "cpus": "1", "taskset": "taskset -c 0",
|
||||
"timeout": min(_MAX_JOB_MIN, onecpu_runs * _ONE_CPU_RUN_MIN + 30)})
|
||||
launch_legs = [{"job": k, "cycles": launch_cycles_each,
|
||||
"start": (k - 1) * launch_cycles_each + 1,
|
||||
"timeout": min(_MAX_JOB_MIN, 60 + launch_cycles_each // 2)}
|
||||
for k in range(1, launch_jobs + 1)] if launch_cycles_each > 0 else []
|
||||
popup_legs = []
|
||||
if "popups" in names:
|
||||
shas = []
|
||||
for sha in popup_shas.split(","):
|
||||
sha = sha.strip()
|
||||
if sha and sha not in shas:
|
||||
shas.append(sha)
|
||||
if not shas:
|
||||
raise ValueError("`which` has popups but `popup_shas` names no commit")
|
||||
if popup_jobs_each <= 0 or popup_runs_each <= 0:
|
||||
raise ValueError("popup_jobs_each and popup_runs_each must be positive")
|
||||
for sha in shas:
|
||||
for k in range(1, popup_jobs_each + 1):
|
||||
popup_legs.append({"sha": sha, "short": sha[:7], "job": k, "runs": popup_runs_each,
|
||||
"label": "popups %s #%d x%d" % (sha[:7], k, popup_runs_each),
|
||||
"slug": "popups-%s-%d" % (sha[:7], k),
|
||||
"timeout": min(_MAX_JOB_MIN, popup_runs_each * _POPUP_RUN_MIN + 30)})
|
||||
run_suite = "suite" in names and bool(legs)
|
||||
run_webgl = "webgl" in names and webgl_rounds > 0 and webgl_procs > 0
|
||||
run_launch = "launch" in names and bool(launch_legs)
|
||||
return {
|
||||
"suite": str(run_suite).lower(),
|
||||
"webgl": str(run_webgl).lower(),
|
||||
"launch": str(run_launch).lower(),
|
||||
"suite_matrix": json.dumps(legs if run_suite else []),
|
||||
"launch_matrix": json.dumps(launch_legs if run_launch else []),
|
||||
"popups": str(bool(popup_legs)).lower(),
|
||||
"popup_matrix": json.dumps(popup_legs),
|
||||
"webgl_timeout": str(min(_MAX_JOB_MIN, 40 + webgl_rounds * 4)),
|
||||
}
|
||||
|
||||
|
||||
# ── reading a pytest log ────────────────────────────────────────────────────
|
||||
|
||||
_SUMMARY = re.compile(r"^=+ (?P<body>.+?) in (?P<secs>[\d.]+)s(?: \([\d:]+\))? =+$")
|
||||
_COUNT = re.compile(r"(\d+) (passed|failed|skipped|errors?|reruns?|xfailed|xpassed)")
|
||||
_RESULT = re.compile(r"^(FAILED|ERROR) (\S+)")
|
||||
_RERUN = re.compile(r"\bRERUN (\S+)")
|
||||
_SECTION = re.compile(r"^_{2,} (?P<name>.+?) _{2,}$")
|
||||
_BANNER = re.compile(r"^=+ (?P<name>.+?) =+$")
|
||||
|
||||
|
||||
def normalise(message: str) -> str:
|
||||
"""The key under which two failure messages are the same message: numbers
|
||||
(pids, ports, timings, addresses' digits) differ from run to run."""
|
||||
return re.sub(r"0x[0-9a-fA-F]+|\d+(?:\.\d+)?", "N", message)
|
||||
|
||||
|
||||
def _matches(test_id: str, section: str) -> bool:
|
||||
tail = test_id.split("::")[-1]
|
||||
return section == tail or section.endswith(tail)
|
||||
|
||||
|
||||
def parse_pytest_log(text: str) -> dict:
|
||||
"""Counts, failed ids and the whole failure messages of one run_e2e.py log.
|
||||
|
||||
A full run is two pytest invocations (the parallel pass, then the wall-clock
|
||||
tests alone): the counts are summed, and `summaries` says how many summary
|
||||
lines were found (0 = the run never reached a verdict).
|
||||
"""
|
||||
out = {"passed": 0, "failed": 0, "errors": 0, "skipped": 0, "rerun": 0, "seconds": 0.0,
|
||||
"summaries": 0, "failed_ids": [], "rerun_ids": [], "failures": {}}
|
||||
lines = text.splitlines()
|
||||
sections: list[tuple[str, list[str]]] = []
|
||||
in_failures = False
|
||||
short: dict[str, list[str]] = {}
|
||||
current_short = None
|
||||
in_short = False
|
||||
for line in lines:
|
||||
line = line.rstrip("\r")
|
||||
banner = _BANNER.match(line)
|
||||
if banner:
|
||||
name = banner.group("name")
|
||||
in_failures = name in ("FAILURES", "ERRORS")
|
||||
in_short = name == "short test summary info"
|
||||
current_short = None
|
||||
m = _SUMMARY.match(line)
|
||||
if m:
|
||||
out["summaries"] += 1
|
||||
out["seconds"] += float(m.group("secs"))
|
||||
for n, kind in _COUNT.findall(m.group("body")):
|
||||
n = int(n)
|
||||
if kind == "passed":
|
||||
out["passed"] += n
|
||||
elif kind == "failed":
|
||||
out["failed"] += n
|
||||
elif kind.startswith("error"):
|
||||
out["errors"] += n
|
||||
elif kind == "skipped":
|
||||
out["skipped"] += n
|
||||
elif kind.startswith("rerun"):
|
||||
out["rerun"] += n
|
||||
in_short = False
|
||||
continue
|
||||
rr = _RERUN.search(line)
|
||||
if rr and rr.group(1) not in out["rerun_ids"]:
|
||||
out["rerun_ids"].append(rr.group(1))
|
||||
if in_failures:
|
||||
sec = _SECTION.match(line)
|
||||
if sec:
|
||||
sections.append((sec.group("name"), []))
|
||||
elif sections:
|
||||
sections[-1][1].append(line)
|
||||
elif in_short:
|
||||
res = _RESULT.match(line)
|
||||
if res:
|
||||
test_id = res.group(2)
|
||||
if test_id not in out["failed_ids"]:
|
||||
out["failed_ids"].append(test_id)
|
||||
rest = line[res.end():]
|
||||
rest = rest[3:] if rest.startswith(" - ") else rest.strip()
|
||||
short[test_id] = [rest]
|
||||
current_short = test_id
|
||||
elif current_short is not None:
|
||||
short[current_short].append(line)
|
||||
for test_id in out["failed_ids"]:
|
||||
body = None
|
||||
for name, section in sections:
|
||||
if _matches(test_id, name):
|
||||
e_lines = [re.sub(r"^E {0,3}", "", s, count=1) for s in section if re.match(r"^E( |$)", s)]
|
||||
body = "\n".join(e_lines) if e_lines else "\n".join(section).strip()
|
||||
break
|
||||
if not body:
|
||||
body = "\n".join(short.get(test_id, [])).strip()
|
||||
out["failures"][test_id] = body
|
||||
return out
|
||||
|
||||
|
||||
# ── one suite run ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def run_record(log_text: str, *, run: int, of: int, label: str, cpus: str, exit_code: int,
|
||||
seconds: int, sha: str = "") -> dict:
|
||||
p = parse_pytest_log(log_text)
|
||||
ended = p["summaries"] > 0 and exit_code in (0, 1)
|
||||
if not ended:
|
||||
verdict = "no-verdict"
|
||||
elif exit_code == 0:
|
||||
verdict = "green"
|
||||
else:
|
||||
verdict = "red"
|
||||
return {"run": run, "of": of, "label": label, "cpus": cpus, "sha": sha, "exit": exit_code,
|
||||
"seconds": seconds, "verdict": verdict, **{k: p[k] for k in (
|
||||
"passed", "failed", "errors", "skipped", "rerun", "failed_ids", "rerun_ids",
|
||||
"failures")}}
|
||||
|
||||
|
||||
def run_line(rec: dict) -> str:
|
||||
ids = ",".join(rec["failed_ids"]) or "-"
|
||||
return ("run %d/%d [%s]: %s exit=%d passed=%d failed=%d errors=%d rerun=%d skipped=%d "
|
||||
"duration=%ds failed_ids=%s" % (
|
||||
rec["run"], rec["of"], rec["label"], rec["verdict"].upper(), rec["exit"],
|
||||
rec["passed"], rec["failed"], rec["errors"], rec["rerun"], rec["skipped"],
|
||||
rec["seconds"], ids))
|
||||
|
||||
|
||||
def _load(directory: Path, pattern: str) -> list[dict]:
|
||||
return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(directory.rglob(pattern))]
|
||||
|
||||
|
||||
def suite_summary(records: list[dict]) -> str:
|
||||
"""The step summary of one job: a table with one row per run."""
|
||||
if not records:
|
||||
return "### No run was recorded\n\nThe hunt did not produce a single run: this is a BROKEN job, not a caught failure.\n"
|
||||
first = records[0]
|
||||
rows = ["### %s" % first["label"], "",
|
||||
"| run | verdict | exit | passed | failed | rerun | skipped | duration | failed tests |",
|
||||
"|---|---|---|---|---|---|---|---|---|"]
|
||||
for r in records:
|
||||
ids = "<br>".join("`%s`" % i for i in r["failed_ids"]) or "-"
|
||||
rows.append("| %d/%d | %s | %d | %d | %d | %d | %d | %ds | %s |" % (
|
||||
r["run"], r["of"], r["verdict"], r["exit"], r["passed"], r["failed"] + r["errors"],
|
||||
r["rerun"], r["skipped"], r["seconds"], ids))
|
||||
broken = sum(1 for r in records if r["verdict"] == "no-verdict")
|
||||
rows += ["", "**Caught** (red runs, listed above): %d. **Broken** (no verdict, the job ends red): %d."
|
||||
% (sum(1 for r in records if r["verdict"] == "red"), broken)]
|
||||
return "\n".join(rows) + "\n"
|
||||
|
||||
|
||||
def _group_tally(records: list[dict]) -> list[str]:
|
||||
n = len(records)
|
||||
green = [r for r in records if r["verdict"] == "green"]
|
||||
red = [r for r in records if r["verdict"] == "red"]
|
||||
broken = [r for r in records if r["verdict"] == "no-verdict"]
|
||||
clean = [r for r in green if r["rerun"] == 0]
|
||||
out = ["runs total: %d" % n,
|
||||
"runs fully green: %d (of which with no rerun at all: %d)" % (len(green), len(clean)),
|
||||
"runs red (caught): %d" % len(red),
|
||||
"runs without a verdict (broken): %d" % len(broken)]
|
||||
per_test: dict[str, list[tuple[dict, str]]] = {}
|
||||
for r in records:
|
||||
for test_id in r["failed_ids"]:
|
||||
per_test.setdefault(test_id, []).append((r, r["failures"].get(test_id, "")))
|
||||
reran: dict[str, int] = {}
|
||||
for r in records:
|
||||
for test_id in r["rerun_ids"]:
|
||||
reran[test_id] = reran.get(test_id, 0) + 1
|
||||
if per_test:
|
||||
out.append("")
|
||||
out.append("tests that failed at least once:")
|
||||
for test_id, hits in sorted(per_test.items(), key=lambda kv: (-len(kv[1]), kv[0])):
|
||||
out.append("- %s: failed in %d of %d runs" % (test_id, len(hits), n))
|
||||
seen: dict[str, tuple[int, str]] = {}
|
||||
for _, msg in hits:
|
||||
key = normalise(msg)
|
||||
count, first_msg = seen.get(key, (0, msg))
|
||||
seen[key] = (count + 1, first_msg)
|
||||
for count, msg in seen.values():
|
||||
out.append(" message (seen %d time%s), whole:" % (count, "" if count == 1 else "s"))
|
||||
out += [" " + s for s in (msg.splitlines() or ["(empty)"])]
|
||||
if reran:
|
||||
out.append("")
|
||||
out.append("tests that were rerun at least once (passed on a rerun, or failed after it):")
|
||||
for test_id, count in sorted(reran.items(), key=lambda kv: (-kv[1], kv[0])):
|
||||
out.append("- %s: rerun in %d of %d runs" % (test_id, count, n))
|
||||
return out
|
||||
|
||||
|
||||
def suite_tally(records: list[dict]) -> str:
|
||||
"""Every run of every job: the ordinary legs together, the 1-CPU leg on its own line."""
|
||||
normal = [r for r in records if r.get("cpus") != "1"]
|
||||
onecpu = [r for r in records if r.get("cpus") == "1"]
|
||||
out = ["# Suite hunt tally", "",
|
||||
"Caught failures are the result of this hunt, not a failure of it. A run without a verdict is broken.",
|
||||
"", "## Ordinary jobs (all CPUs): the rate", "", "```"]
|
||||
out += _group_tally(normal) if normal else ["no run"]
|
||||
out += ["```", "", "## 1-CPU job (processes limited to one CPU): reported apart, not part of the rate above",
|
||||
"", "```"]
|
||||
out += _group_tally(onecpu) if onecpu else ["no run"]
|
||||
out += ["```"]
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
# ── the popups hunt ─────────────────────────────────────────────────────────
|
||||
|
||||
ATTACHMENT = "attachment / run.popups empty"
|
||||
|
||||
|
||||
def classify_popup_failure(test_id: str, message: str) -> str:
|
||||
"""`attachment`: the download event on the opener came before the `page` event, so the
|
||||
popup was never announced: the test's own text about it, or an empty `run.popups`.
|
||||
Anything else is `other`."""
|
||||
low = message.lower()
|
||||
if "stock announces the popup" in low or ".popups" in low:
|
||||
return "attachment"
|
||||
return "other"
|
||||
|
||||
|
||||
def popups_tally(records: list[dict]) -> str:
|
||||
"""Per commit: runs, runs with a red, each failed test and its whole messages, and one
|
||||
line per red run saying whether it is the attachment failure or something else."""
|
||||
shas: list[str] = []
|
||||
for r in records:
|
||||
if r.get("sha", "") not in shas:
|
||||
shas.append(r.get("sha", ""))
|
||||
out = ["# Popups hunt tally (ONE CPU: taskset -c 0)", "",
|
||||
"Caught failures are the result of the hunt, not a failure of it. A run without a verdict is broken."]
|
||||
for sha in shas:
|
||||
mine = [r for r in records if r.get("sha", "") == sha]
|
||||
reds = [r for r in mine if r["verdict"] == "red"]
|
||||
out += ["", "## commit %s" % (sha or "(unknown)"), "", "```",
|
||||
"runs total: %d" % len(mine),
|
||||
"runs with at least one red: %d" % len(reds)]
|
||||
out += _group_tally(mine)[1:]
|
||||
out += ["", "each red run:"]
|
||||
for r in sorted(reds, key=lambda r: (r["label"], r["run"])):
|
||||
kinds = {i: classify_popup_failure(i, r["failures"].get(i, "")) for i in r["failed_ids"]}
|
||||
kind = ATTACHMENT if kinds and set(kinds.values()) == {"attachment"} else "other"
|
||||
mixed = kind == "other" and "attachment" in kinds.values()
|
||||
note = " (also %d attachment)" % list(kinds.values()).count("attachment") if mixed else ""
|
||||
out.append("- %s run %d/%d: %s%s: %s" % (r["label"], r["run"], r["of"], kind, note,
|
||||
", ".join(r["failed_ids"]) or "-"))
|
||||
if not reds:
|
||||
out.append("- none")
|
||||
out.append("```")
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
# ── the webgl hunt ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def webgl_record(log_text: str, *, round_: int, proc: int, exit_code: int, test_id: str) -> dict:
|
||||
p = parse_pytest_log(log_text)
|
||||
if p["passed"] == 1 and p["failed"] == 0 and p["errors"] == 0 and exit_code == 0:
|
||||
status, message = "pass", ""
|
||||
elif p["failed"] >= 1 and p["summaries"] > 0:
|
||||
status = "fail"
|
||||
message = next(iter(p["failures"].values()), "") or "(no message)"
|
||||
else:
|
||||
status, message = "no-verdict", "exit=%d, summary lines=%d, skipped=%d" % (
|
||||
exit_code, p["summaries"], p["skipped"])
|
||||
return {"round": round_, "proc": proc, "exit": exit_code, "status": status,
|
||||
"message": message, "test": test_id}
|
||||
|
||||
|
||||
def webgl_tally(records: list[dict]) -> str:
|
||||
n = len(records)
|
||||
failed = [r for r in records if r["status"] == "fail"]
|
||||
broken = [r for r in records if r["status"] == "no-verdict"]
|
||||
out = ["runs: %d" % n, "passed: %d" % sum(1 for r in records if r["status"] == "pass"),
|
||||
"failed (caught): %d of %d" % (len(failed), n),
|
||||
"no verdict (broken): %d" % len(broken)]
|
||||
reasons: dict[str, list] = {}
|
||||
for r in failed:
|
||||
reasons.setdefault(normalise(r["message"]), []).append(r)
|
||||
if reasons:
|
||||
out += ["", "distinct reasons:"]
|
||||
for hits in sorted(reasons.values(), key=lambda h: -len(h)):
|
||||
where = ", ".join("round %d proc %d" % (h["round"], h["proc"]) for h in hits)
|
||||
out.append("- %d time%s (%s), whole message:" % (len(hits), "" if len(hits) == 1 else "s", where))
|
||||
out += [" " + s for s in hits[0]["message"].splitlines()]
|
||||
if broken:
|
||||
out += ["", "runs without a verdict:"]
|
||||
out += ["- round %d proc %d: %s" % (r["round"], r["proc"], r["message"]) for r in broken]
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
# ── command line ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _append(path: str | None, text: str) -> None:
|
||||
if path:
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
p = sub.add_parser("plan")
|
||||
p.add_argument("--hunt", default="release-triple")
|
||||
p.add_argument("--which", default="all")
|
||||
p.add_argument("--popup-shas", default="")
|
||||
p.add_argument("--popup-jobs-each", type=int, default=5)
|
||||
p.add_argument("--popup-runs-each", type=int, default=2)
|
||||
for name, default in (("suite-jobs", 6), ("suite-runs-each", 5), ("onecpu-runs", 2),
|
||||
("webgl-rounds", 13), ("webgl-procs", 4), ("launch-jobs", 3),
|
||||
("launch-cycles-each", 100)):
|
||||
p.add_argument("--" + name, type=int, default=default)
|
||||
p = sub.add_parser("run-line")
|
||||
p.add_argument("--log", required=True)
|
||||
p.add_argument("--out", required=True)
|
||||
p.add_argument("--run", type=int, required=True)
|
||||
p.add_argument("--of", type=int, required=True)
|
||||
p.add_argument("--label", required=True)
|
||||
p.add_argument("--cpus", default="all")
|
||||
p.add_argument("--sha", default="")
|
||||
p.add_argument("--exit", type=int, required=True, dest="exit_code")
|
||||
p.add_argument("--seconds", type=int, required=True)
|
||||
for name in ("suite-summary", "suite-tally", "popups-tally", "webgl-tally"):
|
||||
q = sub.add_parser(name)
|
||||
q.add_argument("dir")
|
||||
p = sub.add_parser("webgl-run")
|
||||
p.add_argument("--log", required=True)
|
||||
p.add_argument("--out", required=True)
|
||||
p.add_argument("--round", type=int, required=True, dest="round_")
|
||||
p.add_argument("--proc", type=int, required=True)
|
||||
p.add_argument("--exit", type=int, required=True, dest="exit_code")
|
||||
p.add_argument("--test", required=True)
|
||||
args = ap.parse_args(argv)
|
||||
summary = os.environ.get("GITHUB_STEP_SUMMARY")
|
||||
|
||||
if args.cmd == "plan":
|
||||
if args.hunt != "release-triple":
|
||||
print("plan: hunt=%s has no plan" % args.hunt, file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
plan = make_plan(which=args.which, suite_jobs=args.suite_jobs,
|
||||
suite_runs_each=args.suite_runs_each, onecpu_runs=args.onecpu_runs,
|
||||
webgl_rounds=args.webgl_rounds, webgl_procs=args.webgl_procs,
|
||||
launch_jobs=args.launch_jobs,
|
||||
launch_cycles_each=args.launch_cycles_each,
|
||||
popup_shas=args.popup_shas, popup_jobs_each=args.popup_jobs_each,
|
||||
popup_runs_each=args.popup_runs_each)
|
||||
except ValueError as exc:
|
||||
print("::error::%s" % exc)
|
||||
return 2
|
||||
text = "".join("%s=%s\n" % kv for kv in plan.items())
|
||||
sys.stdout.write(text)
|
||||
_append(os.environ.get("GITHUB_OUTPUT"), text)
|
||||
_append(summary, "### Plan\n\n```\n%s```\n" % text)
|
||||
return 0
|
||||
if args.cmd == "run-line":
|
||||
text = Path(args.log).read_text(encoding="utf-8", errors="replace")
|
||||
rec = run_record(text, run=args.run, of=args.of, label=args.label, cpus=args.cpus,
|
||||
exit_code=args.exit_code, seconds=args.seconds, sha=args.sha)
|
||||
Path(args.out).write_text(json.dumps(rec, indent=1), encoding="utf-8")
|
||||
print(run_line(rec))
|
||||
if rec["verdict"] == "no-verdict":
|
||||
print("::warning::%s: this run has no verdict (broken, not a caught failure)" % run_line(rec)[:80])
|
||||
return 0
|
||||
if args.cmd == "suite-summary":
|
||||
text = suite_summary(_load(Path(args.dir), "run_*.json"))
|
||||
sys.stdout.write(text)
|
||||
_append(summary, text)
|
||||
records = _load(Path(args.dir), "run_*.json")
|
||||
return 1 if (not records or any(r["verdict"] == "no-verdict" for r in records)) else 0
|
||||
if args.cmd == "suite-tally":
|
||||
records = _load(Path(args.dir), "run_*.json")
|
||||
text = suite_tally(records)
|
||||
sys.stdout.write(text)
|
||||
_append(summary, text)
|
||||
return 0 if records else 1
|
||||
if args.cmd == "popups-tally":
|
||||
records = _load(Path(args.dir), "run_*.json")
|
||||
text = popups_tally(records)
|
||||
sys.stdout.write(text)
|
||||
_append(summary, text)
|
||||
return 0 if records else 1
|
||||
if args.cmd == "webgl-run":
|
||||
text = Path(args.log).read_text(encoding="utf-8", errors="replace")
|
||||
rec = webgl_record(text, round_=args.round_, proc=args.proc, exit_code=args.exit_code,
|
||||
test_id=args.test)
|
||||
Path(args.out).write_text(json.dumps(rec, indent=1), encoding="utf-8")
|
||||
first = rec["message"].splitlines()[0] if rec["message"] else ""
|
||||
print("round %02d proc %d: %s %s" % (rec["round"], rec["proc"], rec["status"].upper(), first))
|
||||
return 0
|
||||
if args.cmd == "webgl-tally":
|
||||
records = _load(Path(args.dir), "round_*.json")
|
||||
text = webgl_tally(records)
|
||||
sys.stdout.write(text)
|
||||
_append(summary, "### webgl\n\n```\n%s```\n" % text)
|
||||
return 1 if (not records or any(r["status"] == "no-verdict" for r in records)) else 0
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -36,6 +36,7 @@ import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import collections
|
||||
import time
|
||||
import warnings
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
@@ -966,6 +967,16 @@ class FrameDispatcher(Dispatcher):
|
||||
#: closed, and a script that handles "detached" (an iframe a framework removed) never saw it.
|
||||
detached = False
|
||||
|
||||
def emit(self, method: str, params: Optional[Dict] = None) -> None:
|
||||
if method == "loadstate" and params and params.get("add") in ("domcontentloaded", "load"):
|
||||
page = self.page
|
||||
with page._announce_lock:
|
||||
if not page._announced:
|
||||
page._said_before_announcement.append((self, dict(params)))
|
||||
super().emit(method, params)
|
||||
return
|
||||
super().emit(method, params)
|
||||
|
||||
def detach(self) -> None:
|
||||
"""The frame left the page: its handles go (their frame is no more), the frame itself stays and refuses."""
|
||||
self.detached = True
|
||||
@@ -2477,7 +2488,23 @@ class RouteDispatcher(Dispatcher):
|
||||
# session they came back "Handler for does not implement method", the
|
||||
# held request was never released and the page hung on its first
|
||||
# request. Every route that ever reached a handler failed this way.
|
||||
result = self.request.page.send(command, params)
|
||||
# ⛔ THE ANSWER TO A REQUEST THE BROWSER HAS ALREADY CLOSED IS NOT AN ERROR. The page cancels requests while a route is
|
||||
# deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with its document): the engine takes
|
||||
# the request out of its held set at once, and the late `continue`/`abort`/`fulfill` meets "Cannot find request".
|
||||
# Stock Playwright sends these commands as may-fail and tells the client nothing (`sendMayFail`). Ours passed the
|
||||
# error up; the client kept it as the error of the whole connection and raised it on the NEXT route command,
|
||||
# which was never sent: its request stayed held in the engine, its handler failed too, and so on down the page
|
||||
# (measured on a real news page: six held requests in a row, one a beacon, networkidle never).
|
||||
# ⛔ EVERY protocol error of the three commands, not one wording of it. The engine says "Cannot find request" when
|
||||
# the request left its held set first, and "NS_BINDING_ABORTED [nsIInterceptedChannel.resetInterceptionWithURI]"
|
||||
# when the channel was cancelled while the answer was on its way: the same event, two messages. Stock's
|
||||
# `sendMayFail` swallows both, and a list of the wordings we have met would fail on the next one.
|
||||
try:
|
||||
result = self.request.page.send(command, params)
|
||||
except juggler.ProtocolError:
|
||||
result = None
|
||||
except juggler.TargetClosedError:
|
||||
result = None # the page went away: nothing is held any more
|
||||
self.dispose()
|
||||
return result
|
||||
|
||||
@@ -2534,6 +2561,73 @@ class RouteDispatcher(Dispatcher):
|
||||
|
||||
|
||||
# ── page ────────────────────────────────────────────────────────────────────
|
||||
class _Adoption:
|
||||
"""ONE ENGINE TARGET ON ITS WAY TO THE CLIENT: the single record of where it is, and the only thing an event about it may change.
|
||||
|
||||
attached - the engine said `Browser.attachedToTarget`; nothing is built yet
|
||||
building - the adoption thread is making the `PageDispatcher` (init scripts, replay, the main frame)
|
||||
waiting - the page is built and waits for the engine's `Page.ready` (a popup: for as long as the engine takes)
|
||||
announced - the client was told of the page (`page` event); it lives in the registries
|
||||
|
||||
and `gone`, set by the engine's `Browser.detachedFromTarget` AT ANY MOMENT, whatever the state.
|
||||
|
||||
⛔ THE INVARIANT, which `test_every_order_of_the_events_of_a_popup_gives_one_page_event` proves over EVERY order of attach, frame,
|
||||
commit, ready, detach and of the adoption's own steps: a target that was attached and is not a page a caller asked for gives the client
|
||||
EXACTLY ONE `page` event, at its ready or at its disappearance (and its close right after, if it disappeared), unless its context closed
|
||||
first. The adoption never decides alone that a target is lost: every wait it makes looks at `gone`, every command it sends that finds
|
||||
the session gone ends in the same place as a detach. This replaces four patches of the same race (a detach before the ready, during
|
||||
the build, between the build and the wait, and a command answered 'cannot find session').
|
||||
"""
|
||||
|
||||
__slots__ = ("target_id", "opener", "context_id", "requested", "state", "gone", "page", "session", "trace", "t0")
|
||||
|
||||
#: What the engine says about a target that the trace keeps (the events of its page's birth and of its disappearance).
|
||||
TRACED = ("Page.frameAttached", "Page.navigationStarted", "Page.navigationCommitted", "Page.navigationAborted",
|
||||
"Page.ready", "Page.frameDetached", "Browser.detachedFromTarget")
|
||||
|
||||
def __init__(self, target_id: str, opener: Optional["PageDispatcher"], context_id: Optional[str] = None,
|
||||
session: Optional[str] = None) -> None:
|
||||
self.target_id = target_id
|
||||
self.opener = opener
|
||||
self.context_id = context_id
|
||||
self.session = session
|
||||
#: ⛔ A SHORT TRACE OF THE TARGET, IN MEMORY: what the engine said and what the adoption did, with the milliseconds since the attach.
|
||||
#: It costs a list of at most 60 short strings per target in flight and nothing afterwards; it is written in the warning and in the
|
||||
#: error when a popup is not announced or is dropped, so that a red run on a machine nobody can look at explains itself (the order
|
||||
#: of the events is what decides the outcome of an adoption).
|
||||
self.t0 = time.monotonic()
|
||||
self.trace: List[str] = ["attached +0ms"]
|
||||
self.requested: Optional[bool] = None
|
||||
self.state = "attached"
|
||||
self.gone = False
|
||||
self.page: Optional["PageDispatcher"] = None
|
||||
|
||||
def note(self, what: str) -> None:
|
||||
if len(self.trace) < 60:
|
||||
self.trace.append("%s +%dms" % (what, int((time.monotonic() - self.t0) * 1000)))
|
||||
|
||||
def trace_text(self) -> str:
|
||||
return "events of the target: " + ", ".join(self.trace)
|
||||
|
||||
|
||||
def _with_trace(failure: BaseException, trace: str) -> BaseException:
|
||||
"""The same failure, its message followed by the trace of the target (the class is kept when it can be built from a message)."""
|
||||
if trace in str(failure) or "events of the target" in str(failure):
|
||||
return failure
|
||||
try:
|
||||
return type(failure)("%s [%s]" % (failure, trace))
|
||||
except Exception:
|
||||
return RuntimeError("%s [%s]" % (failure, trace))
|
||||
|
||||
|
||||
def _target_is_gone(error: BaseException) -> bool:
|
||||
"""Whether a failed command failed because the target or its session no longer exists (the engine closed the tab under it)."""
|
||||
if isinstance(error, juggler.TargetClosedError):
|
||||
return True
|
||||
text = str(error).lower()
|
||||
return "cannot find session" in text or "target closed" in text or "session closed" in text
|
||||
|
||||
|
||||
class PageDispatcher(Dispatcher):
|
||||
TYPE = "Page"
|
||||
#: No hand until `_build` gives it one: a page without it acts as the
|
||||
@@ -2587,8 +2681,10 @@ class PageDispatcher(Dispatcher):
|
||||
|
||||
def __init__(self, server, context: "BrowserContextDispatcher",
|
||||
session: str, target_id: str, number: int,
|
||||
opener: Optional["PageDispatcher"] = None) -> None:
|
||||
opener: Optional["PageDispatcher"] = None, is_gone=None) -> None:
|
||||
self.context = context
|
||||
#: Whether the engine has taken the target away (the adoption's record says so): every wait of the build looks at it.
|
||||
self._is_gone = is_gone or (lambda: False)
|
||||
#: True while `page.route()` holds this page's requests. The context
|
||||
#: keeps its own flag: a request is offered to the page's handlers
|
||||
#: first, and the client falls through to the context's.
|
||||
@@ -2642,6 +2738,14 @@ class PageDispatcher(Dispatcher):
|
||||
# replay.
|
||||
self._held: Optional[List] = []
|
||||
self._held_lock = threading.Lock()
|
||||
#: ⛔ THE `domcontentloaded` AND `load` OF A POPUP THAT ARE SAID BEFORE IT IS ANNOUNCED. The page is built at once and announced when
|
||||
#: the engine says Page.ready, which is also when its document commits, so the document may have loaded before the client hears
|
||||
#: of the page: a `page.on("load")` registered in the handler of the `page` event would never fire. Playwright's own page is
|
||||
#: reported after its ready and the listener hears the load. Those two states are said again right after the announcement, in
|
||||
#: their order (the first time they set the state the client reads, so `wait_for_load_state` returns at once).
|
||||
self._announce_lock = threading.RLock()
|
||||
self._announced = False
|
||||
self._said_before_announcement: List = []
|
||||
self.lifecycle = Lifecycle(conn, session)
|
||||
self.injected = InjectedScript(conn, session)
|
||||
conn.add_listener(self._route_juggler_event)
|
||||
@@ -2655,10 +2759,34 @@ class PageDispatcher(Dispatcher):
|
||||
self.injected.detach()
|
||||
raise
|
||||
|
||||
def _main_frame_unless_gone(self) -> str:
|
||||
"""The main frame id, waiting for the engine to announce it - for as long as the target exists. A tab that is closed before the
|
||||
engine announced its frame (a download's) never will: the wait ends at once and a frame of our own name keeps the object whole."""
|
||||
waited = 0.0
|
||||
while True:
|
||||
try:
|
||||
return self.lifecycle.wait_for_main_frame(timeout=0.1)
|
||||
except TimeoutError:
|
||||
waited += 0.1
|
||||
if self._is_gone():
|
||||
self.gone_while_building = True
|
||||
return "gone-" + str(self.target_id)
|
||||
if waited >= 20.0:
|
||||
raise
|
||||
|
||||
def _build(self, server, context: "BrowserContextDispatcher",
|
||||
session: str, conn, opener: Optional["PageDispatcher"]) -> None:
|
||||
"""The rest of the construction, under `__init__`'s cleanup."""
|
||||
self.injected.install()
|
||||
# ⛔ A TARGET THAT GOES AWAY WHILE ITS PAGE IS BEING INITIALIZED (a download's empty tab, closed by the engine within milliseconds)
|
||||
# makes the engine answer "cannot find session" to the command. That is the detach-before-ready case again, caught a step later:
|
||||
# the page is still built, flagged gone, and announced and closed as Playwright's is - not discarded with a warning.
|
||||
self.gone_while_building = False
|
||||
try:
|
||||
self.injected.install()
|
||||
except Exception as failure:
|
||||
if not _target_is_gone(failure):
|
||||
raise
|
||||
self.gone_while_building = True
|
||||
self.actions = context.browser.actions_for_page(
|
||||
session, self.lifecycle, self.injected, self.number)
|
||||
#: The viewport as the client was told it (the initializer's, then
|
||||
@@ -2713,10 +2841,18 @@ class PageDispatcher(Dispatcher):
|
||||
#: to answer after a reader's pause, see `dialogs.plan_answer_ms`.
|
||||
self._dialogs_open: Dict[str, Any] = {}
|
||||
self._dialogs_seen = 0
|
||||
self.main_frame_id = self.lifecycle.wait_for_main_frame(timeout=20.0)
|
||||
self.main_frame_id = self._main_frame_unless_gone()
|
||||
# ⛔ The Frame is created BEFORE the Page and adopted after: the Page
|
||||
# initializer has to name a mainFrame the client can already resolve.
|
||||
self.frame = FrameDispatcher(server, self, self.main_frame_id)
|
||||
# ⛔ WITH WHAT THE LIFECYCLE ALREADY KNOWS OF IT, as every other frame is made (`frame_for`): the initializer is a snapshot, and
|
||||
# a popup commits and loads on its own time - what it did between its attach and this line was heard by the lifecycle and by
|
||||
# nobody that tells the client.
|
||||
known = self.lifecycle.frame(self.main_frame_id)
|
||||
self.frame = FrameDispatcher(
|
||||
server, self, self.main_frame_id,
|
||||
url=getattr(known, "url", "") or "",
|
||||
name=getattr(known, "name", "") or "",
|
||||
load_states=sorted(getattr(known, "states", []) or []) or None)
|
||||
viewport = self.viewport_size
|
||||
# `pageNumber` is ours, not Playwright's: the number the page's
|
||||
# rhythms are drawn under (`pointer.py` and the actions' nonce read it
|
||||
@@ -2762,6 +2898,38 @@ class PageDispatcher(Dispatcher):
|
||||
|
||||
|
||||
|
||||
def wait_until_ready(self, timeout: float = 20.0) -> None:
|
||||
"""Return once the engine has said `Page.ready`; the caller announces the page to the client after it.
|
||||
|
||||
⛔ ANNOUNCED READY, BUT BUILT AT ONCE. Playwright's own page is reported as new on Page.ready (FFPage), and not before: the engine
|
||||
commits the page's initial about:blank after the frame is announced, and a `goto` sent before that commit is 'interrupted by
|
||||
another navigation to about:blank'. That is what the wait is for. It is NOT done inside the constructor, because the page has
|
||||
to exist while it waits: the first request of a popup opened by a link is held by a route (the context's, the served browser's)
|
||||
until the page's own routing answers it, and a popup whose commit waits for that answer never becomes ready if the page that
|
||||
would answer it is not built yet. Built, the page also follows the commit and the `load` that come with its own ready; built
|
||||
after them, the client would be told a frame of `about:blank` that is loaded already and never hears the `load`.
|
||||
"""
|
||||
self.lifecycle.wait_for_page_ready(timeout=timeout)
|
||||
|
||||
def announce(self, context: "BrowserContextDispatcher", replay: bool) -> None:
|
||||
"""Tell the client of the page (the context's `page` event) and, for a popup, say again the load states it reached before:
|
||||
under one lock, so a state said live in between waits for the ones that came first."""
|
||||
with self._announce_lock:
|
||||
context.emit("page", {"page": self.channel})
|
||||
earlier, self._said_before_announcement = self._said_before_announcement, []
|
||||
self._announced = True
|
||||
if replay:
|
||||
for frame, params in earlier:
|
||||
if not frame.detached:
|
||||
frame.emit("loadstate", params)
|
||||
|
||||
def settle_events(self) -> None:
|
||||
"""Return once every event the engine sent before this call has been handled: its reply comes after them, on one stream."""
|
||||
try:
|
||||
self.conn.send("Browser.getInfo", {}, timeout=5.0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _install_events(self) -> None:
|
||||
"""Turn Juggler events into protocol events.
|
||||
|
||||
@@ -4344,6 +4512,7 @@ class BrowserContextDispatcher(Dispatcher):
|
||||
# whose only context it is. `Browser.removeBrowserContext` on it
|
||||
# would make Juggler's `destroy()` unregister the default from its
|
||||
# maps and leave a browser that no command can address.
|
||||
self.browser.end_waits_of(self)
|
||||
for page in list(self.pages):
|
||||
try:
|
||||
page.announce_closed()
|
||||
@@ -4366,6 +4535,7 @@ class BrowserContextDispatcher(Dispatcher):
|
||||
# sets `is_closed()` and fires `page.on("close")` from that event, so
|
||||
# a page belonging to a closed context stayed "open" forever, and any
|
||||
# code waiting for it to close waited for good.
|
||||
self.browser.end_waits_of(self)
|
||||
for page in list(self.pages):
|
||||
try:
|
||||
page.announce_closed()
|
||||
@@ -4470,19 +4640,17 @@ class BrowserDispatcher(Dispatcher):
|
||||
# constructor has fully run.
|
||||
self._targets_lock = threading.Lock()
|
||||
self._page_targets: Dict[str, PageDispatcher] = {}
|
||||
#: Targets whose adoption thread is still building. `op_new_page`
|
||||
#: waits on these instead of building a second dispatcher.
|
||||
self._adopting: set = set()
|
||||
#: Every target between its attach and its announcement, by id, ONE record each (`_Adoption`): where it is (attached, building,
|
||||
#: waiting for its ready, announced), whether the engine took it away, its page, its opener. `op_new_page` waits on these
|
||||
#: instead of building a second dispatcher; a download of a tab not announced yet is attributed through it.
|
||||
self._adoptions: Dict[str, _Adoption] = {}
|
||||
#: The last 16 targets that were NOT announced (dropped with their context, or failed), with their trace: for whoever looks.
|
||||
self._dropped: "collections.deque" = collections.deque(maxlen=16)
|
||||
#: Adoption failures, by target. The `newPage` waiter re-raises (and
|
||||
#: pops) them; capped because a spontaneous popup nobody waits for
|
||||
#: must not grow this for the life of the browser.
|
||||
self._adopt_errors: Dict[str, Exception] = {}
|
||||
#: Targets detached BEFORE their adoption finished (a popup closed
|
||||
#: faster than it attached). The adoption still emits `page` first and
|
||||
#: the close right after, so the client always sees them in order.
|
||||
#: Ending the page - registries, session, listeners - is
|
||||
#: `announce_closed`'s job alone: see `_page_over`.
|
||||
self._detached_early: set = set()
|
||||
#: Ending the page - registries, session, listeners - is `announce_closed`'s job alone: see `_page_over`.
|
||||
#: ⛔ HOW A NEW TARGET LEARNS ITS PAGE NUMBER (see `_spawn_adoption`).
|
||||
#: `Browser.newPage` requests sent and not yet answered, by context;
|
||||
#: and the number each answered request named for its target, until
|
||||
@@ -4599,6 +4767,12 @@ class BrowserDispatcher(Dispatcher):
|
||||
self._pages_ready.wait(left)
|
||||
|
||||
def _route_browser_event(self, method: str, params: Dict, session) -> None:
|
||||
if session and method in _Adoption.TRACED:
|
||||
with self._targets_lock:
|
||||
for adoption in self._adoptions.values():
|
||||
if adoption.session == session:
|
||||
adoption.note(method.split(".", 1)[1])
|
||||
break
|
||||
if method == "Browser.attachedToTarget":
|
||||
info = params.get("targetInfo") or {}
|
||||
with self._sessions_ready:
|
||||
@@ -4688,10 +4862,10 @@ class BrowserDispatcher(Dispatcher):
|
||||
with self._targets_lock:
|
||||
if not self._adopt_enabled:
|
||||
return
|
||||
if target_id in self._page_targets or target_id in self._adopting:
|
||||
if target_id in self._page_targets or target_id in self._adoptions:
|
||||
return
|
||||
self._adopting.add(target_id)
|
||||
opener = self._page_targets.get(opener_id) if opener_id else None
|
||||
self._adoptions[target_id] = _Adoption(target_id, opener, browser_context_id, session_id)
|
||||
if opener is not None:
|
||||
opener.popups_opened += 1
|
||||
number: Optional[int] = popup_number(opener.number,
|
||||
@@ -4708,44 +4882,106 @@ class BrowserDispatcher(Dispatcher):
|
||||
daemon=True, name="invpw-adopt-%s" % target_id[:8])
|
||||
thread.start()
|
||||
|
||||
# ── the states of an adoption: the ONLY places a record changes state. Each is one method so that a test can stop the adoption thread
|
||||
# between any two of them and deliver an event of the engine there.
|
||||
def _enter_building(self, adoption: "_Adoption", requested: bool) -> None:
|
||||
with self._targets_lock:
|
||||
adoption.requested = requested
|
||||
adoption.state = "building"
|
||||
adoption.note("building")
|
||||
|
||||
def _enter_waiting(self, adoption: "_Adoption", page: "PageDispatcher") -> bool:
|
||||
"""The page is built and is registered as waiting for its ready. Returns whether the engine took the target away meanwhile - the
|
||||
detach that came before this line found no page to tell, and a wait now would be for ever."""
|
||||
with self._targets_lock:
|
||||
adoption.page = page
|
||||
adoption.state = "waiting"
|
||||
adoption.note("waiting" + (" (gone while building)" if page.gone_while_building else ""))
|
||||
return adoption.gone or page.gone_while_building
|
||||
|
||||
def _enter_announced(self, adoption: "_Adoption", page: "PageDispatcher", context: "BrowserContextDispatcher") -> bool:
|
||||
"""The client is told of the page, and the page is registered. Returns whether the engine took the target away before this
|
||||
point: the close is announced right after the page, so the client always sees the page before its close."""
|
||||
page.announce(context, replay=not adoption.requested)
|
||||
with self._targets_lock:
|
||||
adoption.state = "announced"
|
||||
adoption.note("announced" + (" (gone)" if adoption.gone else ""))
|
||||
gone = adoption.gone
|
||||
self._adoptions.pop(adoption.target_id, None)
|
||||
self._page_targets[adoption.target_id] = page
|
||||
context.pages.append(page)
|
||||
self._pages_ready.notify_all()
|
||||
return gone
|
||||
|
||||
def _adopt_target(self, target_id: str, session_id: Optional[str],
|
||||
browser_context_id: Optional[str],
|
||||
opener: Optional[PageDispatcher],
|
||||
number: Optional[int]) -> None:
|
||||
"""Build the `PageDispatcher` for one engine target, then announce it.
|
||||
"""Build the `PageDispatcher` for one engine target, then announce it, along the states of its `_Adoption`.
|
||||
|
||||
A popup goes through EXACTLY the same construction as a `newPage`
|
||||
page - lifecycle, injected script, buffered-event replay, cursor acts -
|
||||
so it behaves like any other page and carries no observable marker of
|
||||
how it was opened. Stealth is preserved by doing nothing special.
|
||||
|
||||
⛔ A PAGE A CALLER ASKED FOR (`Browser.newPage`) WAITS AT MOST 20 s FOR ITS Page.ready, AND FAILS LOUDLY; A POPUP WAITS AS LONG AS
|
||||
THE ENGINE TAKES, AND SAYS NOTHING. That is Playwright's own: its popup is reported on Page.ready and not before, with no limit - a
|
||||
destination that answers 204 or never answers gives no `page` event at all (measured, stock Playwright 1.62 and its Firefox: none in
|
||||
30 s), one that answers after 25 s gives it at 25 s. The wait ends when the target goes away or its context closes.
|
||||
"""
|
||||
with self._targets_lock:
|
||||
adoption = self._adoptions.get(target_id)
|
||||
page = None
|
||||
requested = number is None
|
||||
try:
|
||||
self._enter_building(adoption, requested)
|
||||
if number is None:
|
||||
number = self._number_of_requested(
|
||||
target_id, browser_context_id, timeout=60.0)
|
||||
session = session_id or self.session_for(target_id, timeout=20.0)
|
||||
context = self._context_for_popup(browser_context_id)
|
||||
page = PageDispatcher(self.server, context, session, target_id,
|
||||
number, opener=opener)
|
||||
# ⛔ `page` BEFORE the registration, on purpose. A detach racing
|
||||
# this build is recorded as early (see `_handle_detach`) and the
|
||||
# close is announced right after, so the client always sees the
|
||||
# page before its close - never a close for a page it has not met.
|
||||
context.emit("page", {"page": page.channel})
|
||||
with self._targets_lock:
|
||||
self._adopting.discard(target_id)
|
||||
self._page_targets[target_id] = page
|
||||
context.pages.append(page)
|
||||
early = target_id in self._detached_early
|
||||
if early:
|
||||
self._detached_early.discard(target_id)
|
||||
self._pages_ready.notify_all()
|
||||
if early:
|
||||
number, opener=opener, is_gone=lambda: adoption.gone)
|
||||
gone = self._enter_waiting(adoption, page)
|
||||
try:
|
||||
if not gone:
|
||||
page.wait_until_ready(timeout=20.0 if requested else None)
|
||||
except TimeoutError as late:
|
||||
raise TimeoutError("%s [%s]" % (late, adoption.trace_text())) from None
|
||||
except juggler.TargetClosedError:
|
||||
# Gone before it was ready (a download's empty tab, a popup the site closed at once): announced and closed right
|
||||
# after, as Playwright's is.
|
||||
gone = True
|
||||
if gone and not requested and context.disposed:
|
||||
# Its context closed while it waited for a ready that never came: it was never announced and is not now.
|
||||
page.announce_closed()
|
||||
with self._targets_lock:
|
||||
adoption.note("dropped: its context closed")
|
||||
self._dropped.append((target_id, adoption.trace_text()))
|
||||
self._adoptions.pop(target_id, None)
|
||||
self._pages_ready.notify_all()
|
||||
return
|
||||
# ⛔ THE EVENTS THAT COME WITH THE READY ARE APPLIED FIRST. The engine says Page.ready and, in the same turn, the commit of
|
||||
# the document that made the page ready: announced between the two, the page tells its client `about:blank` (3 of 4 popups
|
||||
# to a slow destination, measured) where Playwright's says the destination. A round trip to the engine comes back after
|
||||
# everything it sent before it.
|
||||
page.settle_events()
|
||||
# ⛔ `page` BEFORE the registration, on purpose: the client always sees the page before its close, never a close for a page it
|
||||
# has not met.
|
||||
if self._enter_announced(adoption, page, context):
|
||||
page.announce_closed()
|
||||
except Exception as failure:
|
||||
if page is not None:
|
||||
# Built and never announced (not ready in time): its listeners and its object on the client go.
|
||||
try:
|
||||
page.announce_closed()
|
||||
except Exception:
|
||||
pass
|
||||
with self._targets_lock:
|
||||
self._adopting.discard(target_id)
|
||||
self._detached_early.discard(target_id)
|
||||
trace = adoption.trace_text() if adoption is not None else "no record of the target"
|
||||
self._dropped.append((target_id, trace))
|
||||
self._adoptions.pop(target_id, None)
|
||||
failure = _with_trace(failure, trace)
|
||||
self._adopt_errors[target_id] = failure
|
||||
while len(self._adopt_errors) > 64:
|
||||
self._adopt_errors.pop(next(iter(self._adopt_errors)))
|
||||
@@ -4807,17 +5043,46 @@ class BrowserDispatcher(Dispatcher):
|
||||
"Browser.attachedToTarget for it" % (target_id, timeout))
|
||||
self._pages_ready.wait(left)
|
||||
|
||||
def end_waits_of(self, context: "BrowserContextDispatcher") -> None:
|
||||
"""A context is closing: every target of it still on its way to the client is taken away (`gone`, in whichever state it is) and
|
||||
the pages that already wait for a Page.ready that never came stop waiting."""
|
||||
with self._targets_lock:
|
||||
waiting = []
|
||||
for a in self._adoptions.values():
|
||||
if a.context_id == context.context_id:
|
||||
a.gone = True
|
||||
if a.state == "waiting" and a.page is not None:
|
||||
waiting.append(a.page)
|
||||
for page in waiting:
|
||||
try:
|
||||
page.lifecycle.detach()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _handle_detach(self, target_id: Optional[str],
|
||||
session_id: Optional[str]) -> None:
|
||||
"""The engine reports a target gone: an engine-side close (or a popup
|
||||
that died before it finished attaching). Never blocks the reader."""
|
||||
"""The engine reports a target gone: an engine-side close (or a popup that died before it finished attaching). Never blocks the
|
||||
reader.
|
||||
|
||||
A target still on its way to the client (attached, building or waiting for its ready) only gets `gone` set on its record, and a
|
||||
page that is already waiting is told: its wait ends. The adoption thread does the rest, in whichever state it is - there is no
|
||||
state in which this event is lost."""
|
||||
if not target_id:
|
||||
return
|
||||
waiting = None
|
||||
with self._targets_lock:
|
||||
adoption = self._adoptions.get(target_id)
|
||||
if adoption is not None:
|
||||
adoption.gone = True
|
||||
adoption.note("detach seen in state " + adoption.state)
|
||||
if adoption.state == "waiting":
|
||||
waiting = adoption.page
|
||||
page = self._page_targets.get(target_id)
|
||||
if page is None and target_id in self._adopting:
|
||||
self._detached_early.add(target_id)
|
||||
return
|
||||
if adoption is not None:
|
||||
if waiting is not None:
|
||||
# Built and waiting for its Page.ready: the wait ends now (TargetClosedError) and the adoption announces the page closed.
|
||||
waiting.lifecycle.detach()
|
||||
return
|
||||
if page is None:
|
||||
# A target that never became a page: only its buffered events
|
||||
# and its session entry are left to drop.
|
||||
@@ -5106,7 +5371,18 @@ class BrowserDispatcher(Dispatcher):
|
||||
def _on_download_created(self, params: Dict) -> None:
|
||||
context = next((c for c in self.contexts
|
||||
if c.context_id == params.get("browserContextId")), None)
|
||||
page = self._page_targets.get(params.get("pageTargetId"))
|
||||
target = params.get("pageTargetId")
|
||||
with self._targets_lock:
|
||||
announced = self._page_targets.get(target)
|
||||
adoption = self._adoptions.get(target)
|
||||
# The page whose frame the download came from: announced, or built and waiting for its Page.ready.
|
||||
page = announced or (adoption.page if adoption is not None else None)
|
||||
# ⛔ THE PAGE THE DOWNLOAD IS REPORTED ON. A download that starts in a new tab (a `target=_blank` link or a `window.open` to a
|
||||
# `Content-Disposition: attachment`) comes from a tab the client has not been told of: the tab waits for a Page.ready that never
|
||||
# comes and is closed by the engine at once. Playwright reports it on the OPENER in that case (ffBrowser._onDownloadCreated:
|
||||
# "if it's a new window download, report it on the pop-up's opener"); looking only among the announced pages, as this did,
|
||||
# lost the download altogether.
|
||||
origin = announced or (adoption.opener if adoption is not None else None)
|
||||
if context is None:
|
||||
return
|
||||
directory = self._downloads_dir(params.get("browserContextId"))
|
||||
@@ -5114,7 +5390,7 @@ class BrowserDispatcher(Dispatcher):
|
||||
os.path.join(directory, params["uuid"]))
|
||||
self._artifacts[params["uuid"]] = artifact
|
||||
early = self._finished_early.pop(params["uuid"], None)
|
||||
if page is not None:
|
||||
if page is not None or origin is not None:
|
||||
# ⛔ THE ENGINE ENDS A NAVIGATION THAT BECAME A DOWNLOAD WITH NO
|
||||
# EVENT AT ALL (no navigationCommitted, no navigationAborted), so
|
||||
# a `goto` or a click waiting on it waited out its timeout.
|
||||
@@ -5123,7 +5399,7 @@ class BrowserDispatcher(Dispatcher):
|
||||
# starting')); the lifecycle is fed the same abort. A frame whose
|
||||
# current navigation already committed is left alone: the
|
||||
# download came from a click or a script, not from a load.
|
||||
frame = page.lifecycle.frame(params.get("frameId"))
|
||||
frame = page.lifecycle.frame(params.get("frameId")) if page is not None else None
|
||||
if (frame is not None and frame.navigation
|
||||
and frame.navigation not in frame.aborted
|
||||
and not any(c[1] == frame.navigation
|
||||
@@ -5131,9 +5407,10 @@ class BrowserDispatcher(Dispatcher):
|
||||
page.lifecycle._on_event("Page.navigationAborted", {
|
||||
"frameId": frame.id, "navigationId": frame.navigation,
|
||||
"errorText": "Download is starting"})
|
||||
page.emit("download", {"url": params.get("url") or "",
|
||||
"suggestedFilename": params.get("suggestedFileName") or "",
|
||||
"artifact": artifact.channel})
|
||||
if origin is not None:
|
||||
origin.emit("download", {"url": params.get("url") or "",
|
||||
"suggestedFilename": params.get("suggestedFileName") or "",
|
||||
"artifact": artifact.channel})
|
||||
if early is not None:
|
||||
artifact.report_finished(early)
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Which of the engine's processes host a site: what the e2e tests that count processes read.
|
||||
|
||||
A content process is not a site's by being new. The engine keeps preallocated content processes
|
||||
(`dom.ipc.processPrelaunch.fission.number`, 3), hands one to a site when a site needs a process, and starts
|
||||
another to refill the pool whenever it gets to it, so a pid that appears between two reads is often that refill.
|
||||
On Linux the process says which it is: `ContentChild::SetProcessName` names it by its remote type with
|
||||
`prctl(PR_SET_NAME)` (ipc/glue/ProcessUtils_linux.cpp), "Isolated Web Co" once it hosts a site of strategy 1
|
||||
(`webIsolated=<site>`), "Web Content" while it is preallocated. Windows names no process
|
||||
(ProcessUtils_none.cpp): a test that counts sites skips there and says so.
|
||||
|
||||
Measured on firefox-62 (Linux): a cross-site frame renames one preallocated process and a new "Web Content"
|
||||
refills the pool; a same-site frame changes neither; a closed context leaves no "Isolated Web Co", while the
|
||||
pool of "Web Content" fills up behind it in about half the runs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
#: The name a content process of strategy 1 takes once it hosts a site (PR_SET_NAME keeps 15 characters of
|
||||
#: "Isolated Web Content"). A preallocated one is "Web Content" until a site is given to it.
|
||||
SITE_PROCESS_NAME = "Isolated Web Co"
|
||||
|
||||
|
||||
def site_pids(processes, engine_dir=None):
|
||||
"""The pids, among `processes` (psutil-like), of the content processes that host a site; with `engine_dir`,
|
||||
only those of the engine in that directory."""
|
||||
import psutil
|
||||
|
||||
pids = set()
|
||||
for proc in processes:
|
||||
try:
|
||||
if engine_dir is not None and not os.path.normcase(proc.exe()).startswith(os.path.normcase(engine_dir)):
|
||||
continue
|
||||
name, cmd = proc.name(), proc.cmdline()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in cmd and cmd and cmd[-1] == "tab" and name == SITE_PROCESS_NAME:
|
||||
pids.add(proc.pid)
|
||||
return pids
|
||||
|
||||
|
||||
def site_processes_below(root_pid, engine_dir=None):
|
||||
"""The pids of the processes below `root_pid` that host a site. Off Linux the test skips: no name says it."""
|
||||
import psutil
|
||||
|
||||
if not sys.platform.startswith("linux"):
|
||||
pytest.skip("only Linux names a content process by the site it hosts; %s names none" % sys.platform)
|
||||
try:
|
||||
children = psutil.Process(root_pid).children(recursive=True)
|
||||
except psutil.Error:
|
||||
return set()
|
||||
return site_pids(children, engine_dir)
|
||||
@@ -73,6 +73,8 @@ class ScriptedJuggler(EventListeners):
|
||||
self.dispatch_event("Runtime.executionContextCreated", {
|
||||
"executionContextId": "e%s%s" % (target, world),
|
||||
"auxData": {"frameId": "f" + target, "name": world}}, session)
|
||||
# the real engine says so once the page's initial about:blank is done; the page is handed over on it
|
||||
self.dispatch_event("Page.ready", {}, session)
|
||||
return {"targetId": target}
|
||||
if method == "Page.close":
|
||||
target = next(t for t, s in self.sessions.items() if s == session)
|
||||
|
||||
@@ -7,10 +7,13 @@ four such contexts left four more processes (8 web content processes at the end
|
||||
BrowserContext now waits a few seconds for the processes of its container once its pages are gone, and kills the
|
||||
ones that stay.
|
||||
|
||||
The test closes five such contexts in a row and counts the web content processes under the engine after each.
|
||||
The first context may add ONE process that is not the leak (the engine starts a spare content process when the
|
||||
first page takes one, and Linux keeps it), so the count after the fifth must not be above the count after the
|
||||
SECOND: a flat line from there on (on the old engine every context adds one: [4, 5, 6, 7, 8]).
|
||||
The test closes five such contexts in a row. While each page is open it counts the processes that host a site
|
||||
(at least one: the page's, or the count would prove nothing), and once `close` has answered it waits a few
|
||||
seconds for them to be gone: none may be left (on the old engine every context leaves its own, one more each
|
||||
time). Only the processes that host a site are counted (tests/_processes.py): the engine refills its pool of
|
||||
preallocated content processes behind a closed context, in about half the runs, and counting every content
|
||||
process read that refill as a leak ([2, 2, 2, 5, 5] on the e2e of the 0.50.0 commit, three "Web Content" and no
|
||||
site left). Off Linux the test skips: no other system names the process.
|
||||
|
||||
The engine that does it is not published when this file is written: `engine_at_least` makes the test wait for
|
||||
it, and on an older engine it is skipped, never passed.
|
||||
@@ -27,6 +30,7 @@ import pytest
|
||||
pytest.importorskip("websockets")
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
from _processes import site_processes_below # noqa: E402
|
||||
from _servers import LocalServer # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
@@ -59,24 +63,6 @@ def _serve():
|
||||
return server, "http://127.0.0.1:%d" % server.server_address[1]
|
||||
|
||||
|
||||
def _web_processes(root_pid):
|
||||
import psutil
|
||||
|
||||
found = set()
|
||||
try:
|
||||
children = psutil.Process(root_pid).children(recursive=True)
|
||||
except psutil.Error:
|
||||
return found
|
||||
for process in children:
|
||||
try:
|
||||
command = " ".join(process.cmdline())
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in command and command.rstrip().endswith(" tab"):
|
||||
found.add(process.pid)
|
||||
return found
|
||||
|
||||
|
||||
class _Client:
|
||||
"""The few calls of Playwright's protocol this test needs, over the served WebSocket."""
|
||||
|
||||
@@ -114,8 +100,11 @@ def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(f
|
||||
launched = launch_server(host="127.0.0.1", port=0, headless=True, virtual_display=False, humanize=False,
|
||||
seed=4266, binary_path=firefox_binary, launch_timeout_ms=180_000)
|
||||
|
||||
def sites():
|
||||
return site_processes_below(launched.process.pid)
|
||||
|
||||
async def drive():
|
||||
counts = []
|
||||
opened, left = [], []
|
||||
async with connect(launched.ws_endpoint, max_size=None) as ws:
|
||||
client = _Client(ws)
|
||||
await client.start()
|
||||
@@ -123,21 +112,18 @@ def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(f
|
||||
context, frame = await client.new_page()
|
||||
await client.call(frame, "goto", {"url": "%s/?i=%d" % (base, i), "waitUntil": "load", "timeout": 30000})
|
||||
await asyncio.sleep(1.0) # the worker is registered, its install loop is running
|
||||
await client.call(context, "close")
|
||||
deadline = time.time() + 10
|
||||
settled = None
|
||||
while time.time() < deadline: # the count after the close, once it stops moving
|
||||
now = _web_processes(launched.process.pid)
|
||||
if settled is not None and len(now) == settled:
|
||||
break
|
||||
settled = len(now)
|
||||
await asyncio.sleep(1.0)
|
||||
counts.append(len(_web_processes(launched.process.pid)))
|
||||
return counts
|
||||
opened.append(len(sites()))
|
||||
await client.call(context, "close") # the engine waits for the context's processes, then kills
|
||||
deadline = time.time() + 5
|
||||
while sites() and time.time() < deadline:
|
||||
await asyncio.sleep(0.25)
|
||||
left.append(len(sites()))
|
||||
return opened, left
|
||||
|
||||
try:
|
||||
counts = asyncio.run(drive())
|
||||
opened, left = asyncio.run(drive())
|
||||
finally:
|
||||
launched.close()
|
||||
server.shutdown()
|
||||
assert counts[4] <= counts[1], "web content processes after each closed context: %r" % (counts,)
|
||||
assert all(opened), "a page with no process for its site: the count proves nothing (%r)" % (opened,)
|
||||
assert left == [0] * 5, "processes of a site left after each closed context: %r" % (left,)
|
||||
@@ -51,11 +51,22 @@ class _SlowEngine(EventListeners):
|
||||
|
||||
|
||||
class _Page:
|
||||
def __init__(self, server, context, session, target_id, number, opener=None):
|
||||
def __init__(self, server, context, session, target_id, number, opener=None, is_gone=None):
|
||||
self.target_id = target_id
|
||||
self.number = number
|
||||
self.channel = {"guid": "page-" + target_id}
|
||||
|
||||
gone_while_building = False
|
||||
|
||||
def wait_until_ready(self, timeout=20.0):
|
||||
pass # the engine of this test says Page.ready at once
|
||||
|
||||
def settle_events(self):
|
||||
pass
|
||||
|
||||
def announce(self, context, replay):
|
||||
context.emit("page", {"page": self.channel})
|
||||
|
||||
def announce_closed(self):
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,484 @@
|
||||
"""A page is handed over to the client only once the engine says Page.ready.
|
||||
|
||||
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection (the one of the registry test) whose pages announce their
|
||||
frame at birth and say `Page.ready` only when the test tells them to, as the real engine does after its transient about:blank
|
||||
navigations.
|
||||
|
||||
⛔ THE KNOWN-BAD INPUT. The engine commits the page's initial about:blank AFTER it announces the frame; a `goto` sent in between is
|
||||
'interrupted by another navigation to about:blank'. A wrapper that hands the page over on the main frame alone (no wait for
|
||||
Page.ready) returns `new_page()` while the engine is still in that window; so does the adoption of a popup.
|
||||
|
||||
Known-bad: with the wait for Page.ready removed (a21e1de), the first two tests fail - the page is delivered before Page.ready; with
|
||||
the wait INSIDE the constructor (7db28e4..6a60dce), the last two fail - a popup opened by a link has its first request held by a
|
||||
route until its page answers, so a page that is only built once it is ready never becomes ready, and what the engine says between
|
||||
the commit and the ready (the commit itself, the `load`) is said to a page that does not exist yet and is lost; the client's popup
|
||||
then has no `load` to wait for. The page is BUILT at once and ANNOUNCED when ready.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler.server import FrameDispatcher, LocalUtilsDispatcher
|
||||
|
||||
from test_a_closed_context_leaves_nothing_in_the_registry import ScriptedJuggler
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
#: how long a page that must NOT be delivered yet is watched
|
||||
WATCH = 0.4
|
||||
|
||||
|
||||
class LateReadyJuggler(ScriptedJuggler):
|
||||
"""The engine of the registry test, except that Page.ready is held back until `say_ready(session)`."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.held = {}
|
||||
self.released = set()
|
||||
self.queued = []
|
||||
|
||||
def dispatch_event(self, method, params, session=None):
|
||||
if method == "Page.ready" and session not in self.released:
|
||||
self.held[session] = (method, params)
|
||||
return None
|
||||
return super().dispatch_event(method, params, session)
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30):
|
||||
if method == "Browser.getInfo":
|
||||
# a reply comes after everything the engine sent before it: the events queued as "sent with the ready" arrive first
|
||||
queued, self.queued = self.queued, []
|
||||
for event, event_params, event_session in queued:
|
||||
super().dispatch_event(event, event_params, event_session)
|
||||
return {}
|
||||
return super().send(method, params, session, timeout)
|
||||
|
||||
def say_ready(self, session):
|
||||
self.released = set(self.released) | {session}
|
||||
method, params = self.held.pop(session)
|
||||
super().dispatch_event(method, params, session)
|
||||
|
||||
def popup_born(self, opener_target, context_id, n):
|
||||
"""A target the opener opened: attached and framed, but not ready."""
|
||||
target, session = "p%d" % n, "ps%d" % n
|
||||
self.sessions[target] = session
|
||||
self.dispatch_event("Browser.attachedToTarget", {
|
||||
"sessionId": session,
|
||||
"targetInfo": {"targetId": target, "type": "page", "openerId": opener_target,
|
||||
"browserContextId": context_id}}, None)
|
||||
self.dispatch_event("Page.frameAttached", {"frameId": "f" + target, "parentFrameId": None}, session)
|
||||
for world in ("", "utility"):
|
||||
self.dispatch_event("Runtime.executionContextCreated", {
|
||||
"executionContextId": "e%s%s" % (target, world),
|
||||
"auxData": {"frameId": "f" + target, "name": world}}, session)
|
||||
self.dispatch_event("Page.ready", {}, session)
|
||||
return target, session
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def late_browser():
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = LateReadyJuggler()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
yield browser
|
||||
for session in list(conn.held):
|
||||
conn.say_ready(session)
|
||||
time.sleep(0.1)
|
||||
for context in list(browser.contexts):
|
||||
try:
|
||||
server.handle({"guid": context.guid, "method": "close", "params": {}})
|
||||
except Exception:
|
||||
pass
|
||||
server.shutdown()
|
||||
|
||||
|
||||
def _new_context(browser):
|
||||
server = browser.server
|
||||
return server.object(server.handle(
|
||||
{"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
|
||||
|
||||
def test_new_page_returns_only_after_page_ready(late_browser):
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
answer = {}
|
||||
|
||||
def new_page():
|
||||
answer["reply"] = server.handle(
|
||||
{"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
|
||||
worker = threading.Thread(target=new_page, daemon=True)
|
||||
worker.start()
|
||||
deadline = time.monotonic() + 5
|
||||
while not conn.held and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert conn.held, "the page was never born in the scripted engine"
|
||||
worker.join(WATCH)
|
||||
assert worker.is_alive() and "reply" not in answer, (
|
||||
"new_page() returned before the engine said Page.ready: the page would be handed over inside the window where a goto is "
|
||||
"interrupted by the engine's own about:blank")
|
||||
assert not context.pages, "the page was registered before it was ready"
|
||||
(session,) = conn.held
|
||||
conn.say_ready(session)
|
||||
worker.join(5)
|
||||
assert not worker.is_alive() and "reply" in answer, "new_page() did not return after Page.ready"
|
||||
assert len(context.pages) == 1
|
||||
|
||||
|
||||
def test_a_popup_is_announced_only_after_page_ready(late_browser):
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
# the opener: ready at once
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
assert len(context.pages) == 1
|
||||
opener_target = next(iter(conn.sessions))
|
||||
announced = []
|
||||
original = context.emit
|
||||
|
||||
def spy(event, params=None):
|
||||
if event == "page":
|
||||
announced.append(time.monotonic())
|
||||
return original(event, params)
|
||||
|
||||
context.emit = spy
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
time.sleep(WATCH)
|
||||
assert not announced and len(context.pages) == 1, (
|
||||
"the popup was announced before the engine said Page.ready for it")
|
||||
conn.say_ready(session)
|
||||
deadline = time.monotonic() + 5
|
||||
while not announced and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert announced, "the popup was never announced after Page.ready"
|
||||
assert len(context.pages) == 2
|
||||
|
||||
|
||||
def _unannounced_page(browser, session):
|
||||
return next(o for o in browser.server._objects.values()
|
||||
if o.TYPE == "Page" and getattr(o, "session", None) == session)
|
||||
|
||||
|
||||
def test_a_popup_exists_and_listens_while_it_waits_for_its_ready(late_browser):
|
||||
"""The first request of a popup opened by a link is held by a route until its page answers: the page must be built to answer."""
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
deadline = time.monotonic() + 5
|
||||
page = None
|
||||
while page is None and time.monotonic() < deadline:
|
||||
try:
|
||||
page = _unannounced_page(late_browser, session)
|
||||
except StopIteration:
|
||||
time.sleep(0.01)
|
||||
assert page is not None, "the popup was not built while the engine had not said Page.ready: nothing answers its first request"
|
||||
time.sleep(0.2)
|
||||
assert page._held is None, "the popup is built but does not listen: the events of its birth are held"
|
||||
assert len(context.pages) == 1, "and it was announced before it was ready"
|
||||
|
||||
|
||||
def test_what_a_popup_does_before_its_ready_reaches_its_frame(late_browser, monkeypatch):
|
||||
"""The engine says Page.ready at the commit of the popup's first document; the `load` follows at once. Both reach the client."""
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
said = []
|
||||
original = FrameDispatcher.emit
|
||||
|
||||
def spy(self, event, params=None):
|
||||
said.append((self.frame_id, event, params))
|
||||
return original(self, event, params)
|
||||
|
||||
monkeypatch.setattr(FrameDispatcher, "emit", spy)
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
frame_id = "f" + target
|
||||
url = "http://127.0.0.1/popup"
|
||||
conn.dispatch_event("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session)
|
||||
conn.dispatch_event("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session)
|
||||
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "DOMContentLoaded"}, session)
|
||||
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "load"}, session)
|
||||
conn.say_ready(session)
|
||||
deadline = time.monotonic() + 5
|
||||
while len(context.pages) < 2 and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert len(context.pages) == 2, "the popup was never announced"
|
||||
popup = context.pages[1]
|
||||
assert popup.frame.url == url, "the frame of the popup was told about:blank: its commit was said to a page that did not exist"
|
||||
heard = set(popup.frame.initializer["loadStates"])
|
||||
heard |= {params["add"] for fid, event, params in said
|
||||
if fid == frame_id and event == "loadstate" and params and "add" in params}
|
||||
assert "load" in heard, ("the client's frame never heard `load` of the popup (heard %s): wait_for_url(until=load) would wait for ever"
|
||||
% sorted(heard))
|
||||
|
||||
|
||||
def test_a_popup_waits_for_its_ready_without_a_limit_and_a_requested_page_for_twenty_seconds(late_browser, monkeypatch):
|
||||
"""Playwright's popup is reported on Page.ready with no limit (a destination that answers after 25 s gives the event at 25 s); the
|
||||
page a caller asked for waits 20 s and fails."""
|
||||
from invisible_playwright._juggler.server import PageDispatcher
|
||||
waited = []
|
||||
original = PageDispatcher.wait_until_ready
|
||||
|
||||
def spy(self, timeout=20.0):
|
||||
waited.append(timeout)
|
||||
return original(self, timeout)
|
||||
|
||||
monkeypatch.setattr(PageDispatcher, "wait_until_ready", spy)
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
conn.popup_born(opener_target, context.context_id, 1)
|
||||
deadline = time.monotonic() + 5
|
||||
while len(waited) < 2 and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert waited == [20.0, None], "a requested page waits 20 s, a popup without a limit: %r" % (waited,)
|
||||
|
||||
|
||||
def test_a_popup_that_never_gets_its_ready_ends_with_its_context_and_says_nothing(late_browser):
|
||||
"""204, a server that never answers: no ready, no `page` event, no warning; closing the context ends the wait."""
|
||||
import warnings
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
announced = []
|
||||
original = context.emit
|
||||
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
conn.popup_born(opener_target, context.context_id, 1)
|
||||
time.sleep(0.5)
|
||||
assert not announced, "a popup with no ready was announced"
|
||||
assert any(a.state == "waiting" for a in late_browser._adoptions.values()), "the popup is not waiting"
|
||||
server.handle({"guid": context.guid, "method": "close", "params": {}})
|
||||
deadline = time.monotonic() + 5
|
||||
while late_browser._adoptions and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert not late_browser._adoptions, "closing the context did not end the wait of the popup"
|
||||
time.sleep(0.2)
|
||||
assert not announced, "a popup of a closed context was announced"
|
||||
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
|
||||
|
||||
|
||||
def test_a_popup_is_announced_with_the_address_of_the_commit_that_came_with_its_ready(late_browser):
|
||||
"""The engine says Page.ready and, in the same turn, the commit of the document: the client is told the page after the commit, so
|
||||
the url it reads at the `page` event is the destination, as Playwright's is (3 of 4 popups said about:blank)."""
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
urls = []
|
||||
original = context.emit
|
||||
|
||||
def spy(event, params=None):
|
||||
if event == "page":
|
||||
page = next(o for o in server._objects.values() if o.TYPE == "Page" and o.channel == params["page"])
|
||||
urls.append(page.frame.url)
|
||||
return original(event, params)
|
||||
|
||||
context.emit = spy
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
frame_id = "f" + target
|
||||
url = "http://127.0.0.1/slow"
|
||||
deadline = time.monotonic() + 5
|
||||
while not any(o.TYPE == "Page" and getattr(o, "session", None) == session for o in server._objects.values()) and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
conn.queued.append(("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session))
|
||||
conn.queued.append(("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session))
|
||||
conn.say_ready(session) # the commit follows in the stream: it is delivered with the round trip that comes back after it
|
||||
deadline = time.monotonic() + 5
|
||||
while not urls and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert urls == [url], "the popup was announced with %r, not with the address of the commit that came with its ready" % (urls,)
|
||||
|
||||
|
||||
def test_a_download_started_by_a_popup_that_is_not_announced_is_reported_on_its_opener(late_browser):
|
||||
"""`<a target=_blank href=file>` with `Content-Disposition: attachment`: the new tab never gets a Page.ready and the engine closes it
|
||||
at once. Playwright reports the download on the OPENER (ffBrowser._onDownloadCreated); looking only among the announced pages
|
||||
lost it (no `download` event anywhere)."""
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
opener = next(o for o in server._objects.values() if o.TYPE == "Page" and o.target_id == opener_target)
|
||||
said = []
|
||||
original = opener.emit
|
||||
opener.emit = lambda event, params=None: (said.append((event, params)), original(event, params))[1]
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
deadline = time.monotonic() + 5
|
||||
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
conn.dispatch_event("Browser.downloadCreated", {
|
||||
"uuid": "u1", "browserContextId": context.context_id, "pageTargetId": target, "frameId": "f" + target,
|
||||
"url": "http://127.0.0.1/file", "suggestedFileName": "f.bin"}, None)
|
||||
downloads = [p for e, p in said if e == "download"]
|
||||
assert len(downloads) == 1, "the download of the popup was not reported on its opener: %r" % (said,)
|
||||
assert downloads[0]["suggestedFilename"] == "f.bin"
|
||||
|
||||
|
||||
def test_the_load_of_a_popup_said_before_its_announcement_is_said_again_right_after_it(late_browser, monkeypatch):
|
||||
"""A listener registered in the handler of the `page` event (`page.on("load")`) hears the load of a popup in Playwright, because the
|
||||
page is reported after its ready and the load follows. Here the document may have loaded before the client hears of the page: the
|
||||
two states are said again after the announcement, in order, and the first time they already set the state `wait_for_load_state`
|
||||
reads."""
|
||||
from invisible_playwright._juggler import dispatcher as base
|
||||
|
||||
trace = []
|
||||
original = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if method == "page":
|
||||
trace.append("page")
|
||||
elif getattr(self, "TYPE", "") == "Frame" and method == "loadstate" and params and "add" in params:
|
||||
trace.append(params["add"])
|
||||
return original(self, method, params)
|
||||
|
||||
monkeypatch.setattr(base.Dispatcher, "emit", spy)
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
deadline = time.monotonic() + 5
|
||||
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
frame_id, url = "f" + target, "http://127.0.0.1/slow"
|
||||
conn.dispatch_event("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session)
|
||||
conn.dispatch_event("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session)
|
||||
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "DOMContentLoaded"}, session)
|
||||
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "load"}, session)
|
||||
del trace[:] # what is said from here on: the ready, the announcement, the replay
|
||||
conn.say_ready(session)
|
||||
deadline = time.monotonic() + 5
|
||||
while trace.count("load") < 1 and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
time.sleep(0.2)
|
||||
assert "page" in trace, trace
|
||||
after = trace[trace.index("page") + 1:]
|
||||
assert after == ["domcontentloaded", "load"], "after the announcement the client heard %r" % (after,)
|
||||
|
||||
|
||||
def test_a_popup_whose_target_goes_away_while_its_page_is_being_built_is_announced_and_closed(late_browser, monkeypatch):
|
||||
"""A download's empty tab closes within milliseconds; on a loaded machine the page of the popup is still being built when the engine
|
||||
detaches it. That detach went by with nobody to tell, and the wait for a ready that never comes went on for ever: the popup was never
|
||||
announced (the full suite failed once on it)."""
|
||||
from invisible_playwright._juggler.server import PageDispatcher
|
||||
original_init = PageDispatcher.__init__
|
||||
|
||||
def slow_init(self, *args, **kwargs):
|
||||
time.sleep(0.4) # the build is slower than the detach
|
||||
return original_init(self, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(PageDispatcher, "__init__", slow_init)
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
monkeypatch.undo() # the opener is built at normal speed
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
monkeypatch.setattr(PageDispatcher, "__init__", slow_init)
|
||||
opener_target = next(iter(conn.sessions))
|
||||
announced, closed = [], []
|
||||
original = context.emit
|
||||
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None)
|
||||
deadline = time.monotonic() + 5
|
||||
while "page" not in announced and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert "page" in announced, "the popup that went away while its page was being built was never announced"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", ["Page.setInitScripts", "Browser.getInfo"])
|
||||
def test_a_command_of_the_adoption_that_finds_the_session_gone_announces_and_closes_the_popup(late_browser, command, monkeypatch):
|
||||
"""The tab goes away WHILE the adoption initializes it: the engine answers 'cannot find session' to a command of the adoption. Like a
|
||||
detach before the ready, that ends in the page announced and closed (Playwright's does), never in a discard with a warning: the
|
||||
download of a link into a new tab was lost one time in a hundred (independent run, quiet machine)."""
|
||||
import warnings
|
||||
from invisible_core.juggler.connection import ProtocolError
|
||||
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
original_send = conn.send
|
||||
|
||||
def send(method, params=None, session=None, timeout=30):
|
||||
if method == command and session not in (None, "s1"):
|
||||
raise ProtocolError('%s: ERROR: cannot find session with id "%s"' % (method, session))
|
||||
return original_send(method, params, session, timeout)
|
||||
|
||||
monkeypatch.setattr(conn, "send", send)
|
||||
announced = []
|
||||
original = context.emit
|
||||
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
if command == "Browser.getInfo":
|
||||
conn.say_ready(session) # this one is asked once the page is ready
|
||||
else:
|
||||
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None)
|
||||
deadline = time.monotonic() + 5
|
||||
while "page" not in announced and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
time.sleep(0.2)
|
||||
assert "page" in announced, "the popup whose session was gone was discarded instead of announced"
|
||||
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
|
||||
|
||||
|
||||
def test_a_popup_that_is_dropped_or_fails_leaves_the_trace_of_what_the_engine_said(late_browser, monkeypatch):
|
||||
"""The log of a red run on a machine nobody can look at does not say in which order the events came: the adoption keeps a short trace
|
||||
per target and writes it in the warning of a failed adoption and in the record of the dropped ones."""
|
||||
import warnings
|
||||
from invisible_playwright._juggler.server import PageDispatcher
|
||||
server, conn = late_browser.server, late_browser.conn
|
||||
context = _new_context(late_browser)
|
||||
conn.released = {"s1"}
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(iter(conn.sessions))
|
||||
# 1. dropped with its context
|
||||
target, session = conn.popup_born(opener_target, context.context_id, 1)
|
||||
deadline = time.monotonic() + 5
|
||||
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
server.handle({"guid": context.guid, "method": "close", "params": {}})
|
||||
deadline = time.monotonic() + 5
|
||||
while not late_browser._dropped and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert late_browser._dropped, "a popup dropped with its context left no trace"
|
||||
dropped_target, text = late_browser._dropped[-1]
|
||||
assert dropped_target == target
|
||||
for word in ("attached", "frameAttached", "building", "waiting", "dropped: its context closed"):
|
||||
assert word in text, "the trace of the dropped popup lacks %r: %s" % (word, text)
|
||||
# 2. a failed adoption writes it in its warning
|
||||
context2 = _new_context(late_browser)
|
||||
|
||||
def boom(self, *args, **kwargs):
|
||||
raise ValueError("boom")
|
||||
|
||||
conn.released = {"s1", "s2"}
|
||||
monkeypatch.setattr(PageDispatcher, "__init__", boom)
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
conn.popup_born(opener_target, context2.context_id, 2)
|
||||
deadline = time.monotonic() + 5
|
||||
while not [w for w in caught if "adoption" in str(w.message)] and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
messages = [str(w.message) for w in caught if "adoption" in str(w.message)]
|
||||
assert messages and "events of the target" in messages[0] and "attached" in messages[0], messages
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
"""A popup is reported on Page.ready, as Playwright's own is: with no limit, and with the destination's address already.
|
||||
|
||||
Measured against stock Playwright 1.62 and its Firefox (in-process, 2 runs of each, never in disagreement):
|
||||
* a destination that answers 204, or never answers: NO `page` event in 30 s (nothing commits, the engine never says Page.ready);
|
||||
* a destination that answers after 4 s: the event at 4.08 s, with `url` already the destination and `load` in the same millisecond.
|
||||
Here: the same two, in-process and through a served browser driven by a stock client, and a destination that answers after 25 s (the
|
||||
wrapper dropped a popup that was not ready in 20 s, with a warning); the address read at the `page` event is the destination.
|
||||
|
||||
Red on b09d620: the popup of the slow destination reads `about:blank` at the event (the commit comes in the same turn as the ready and
|
||||
was applied after the page was announced), and the one that answers after 25 s was dropped at 20 s.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
path, _, query = self.path.partition("?")
|
||||
if path == "/nocontent":
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
if path == "/slow":
|
||||
ms = int(query.split("ms=")[1].split("&")[0]) if "ms=" in query else 0
|
||||
time.sleep(ms / 1000.0)
|
||||
body = b"<!doctype html><html><head><title>slow</title></head><body>slow</body></html>"
|
||||
else:
|
||||
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
|
||||
b"<button id=open204 onclick=\"window.open('/nocontent','_blank')\">open</button>"
|
||||
b"<a id=link204 href=/nocontent target=_blank>link</a>"
|
||||
b"<button id=open1500 onclick=\"window.open('/slow?ms=1500','_blank')\">open</button>"
|
||||
b"<a id=link1500 href='/slow?ms=1500' target=_blank>link</a>"
|
||||
b"<button id=open25000 onclick=\"window.open('/slow?ms=25000','_blank')\">open</button>"
|
||||
b"</body></html>")
|
||||
try:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
except OSError: # the browser left before a slow answer
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site():
|
||||
srv = LocalServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def _stock_client(module):
|
||||
import importlib
|
||||
|
||||
try:
|
||||
return importlib.import_module(module)
|
||||
except ImportError as exc: # pragma: no cover - only in a broken environment
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc, pytrace=False)
|
||||
|
||||
|
||||
def _drive(mode, firefox_binary, body):
|
||||
"""Run body(context, page) in-process or through a served browser driven by a stock client."""
|
||||
if mode == "in-process":
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as b:
|
||||
ctx = b.new_context()
|
||||
body(ctx, ctx.new_page())
|
||||
ctx.close()
|
||||
return
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
body(ctx, ctx.new_page())
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
MODES = ["in-process", "served"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
@pytest.mark.parametrize("opener", ["#open204", "#link204"])
|
||||
def test_a_destination_that_commits_nothing_gives_no_popup_event(firefox_binary, site, mode, opener):
|
||||
def body(ctx, page):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
seen = []
|
||||
ctx.on("page", lambda p: seen.append(p))
|
||||
page.click(opener)
|
||||
time.sleep(6)
|
||||
assert not seen, "a popup whose destination commits nothing was reported (Playwright's is not)"
|
||||
assert len(ctx.pages) == 1
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
@pytest.mark.parametrize("opener", ["#open1500", "#link1500"])
|
||||
def test_a_slow_popup_is_reported_with_the_address_of_its_destination(firefox_binary, site, mode, opener):
|
||||
def body(ctx, page):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
with page.expect_popup(timeout=20000) as info:
|
||||
page.click(opener)
|
||||
assert info.value.url == site + "slow?ms=1500", "the popup was reported with %r" % info.value.url
|
||||
info.value.close()
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, mode):
|
||||
def body(ctx, page):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
t0 = time.monotonic()
|
||||
with page.expect_popup(timeout=45000) as info:
|
||||
page.click("#open25000")
|
||||
took = time.monotonic() - t0
|
||||
assert 24.0 < took < 40.0, "reported after %.1f s" % took
|
||||
assert info.value.url == site + "slow?ms=25000"
|
||||
info.value.close()
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", MODES)
|
||||
@pytest.mark.parametrize("opener", ["#open1500", "#link1500"])
|
||||
def test_a_listener_registered_in_the_page_handler_hears_the_load_of_the_popup(firefox_binary, site, mode, opener):
|
||||
"""Stock Playwright: `context.on("page", lambda p: p.on("load", ...))` fires for a popup that loads after the event (4 s and 25 s
|
||||
destinations); the popup is reported when its ready comes, which is when its document commits, so the load may be said before the
|
||||
client has the page. `wait_for_load_state` in the same handler returns at once."""
|
||||
def body(ctx, page):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
heard, waited = [], []
|
||||
|
||||
def on_page(popup):
|
||||
popup.on("load", lambda p: heard.append(time.monotonic()))
|
||||
t = time.monotonic()
|
||||
popup.wait_for_load_state("load", timeout=10000)
|
||||
waited.append(time.monotonic() - t)
|
||||
|
||||
ctx.on("page", on_page)
|
||||
with page.expect_popup(timeout=20000) as info:
|
||||
page.click(opener)
|
||||
deadline = time.monotonic() + 5
|
||||
while not heard and time.monotonic() < deadline:
|
||||
page.wait_for_timeout(50)
|
||||
assert heard, "the listener registered in the handler of the page event never heard the load of the popup"
|
||||
assert waited and waited[0] < 8.0, "wait_for_load_state in the handler took %r" % (waited,) # at once; the limit is the machine's
|
||||
info.value.close()
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
@@ -0,0 +1,136 @@
|
||||
"""A tab opened by a link (`target=_blank`, with or without `noopener`) or by `window.open` reaches the client, in-process and
|
||||
through a served browser driven by a stock Playwright client, with and without a context route holding the requests.
|
||||
|
||||
⛔ THE KNOWN-BAD INPUT. The page is handed to the client when the engine says `Page.ready`; the engine says it at the commit of the
|
||||
popup's first document. Waiting for it INSIDE the construction of the page (7db28e4..6a60dce) broke two ways, each found by a run:
|
||||
* the first request of a popup is held by the context's route until the page answers it, and a page that is built only once it is
|
||||
ready never answers: `adoption of target ... failed: the page was not ready in 20s` on the server, `Timeout 15000ms exceeded while
|
||||
waiting for event "page"` on the client (a stock client, a served browser, a route that continues every request);
|
||||
* in-process, the commit and the `load` that come with the ready were said to a page that did not exist: `popup.wait_for_url(url)`
|
||||
timed out on `load` (5 tests of test_popup_pages.py).
|
||||
The page is now BUILT at once and ANNOUNCED when ready.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
POPUP = b"<!doctype html><html><head><title>popup</title></head><body><h1>popup</h1></body></html>"
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
path = self.path.split("?")[0]
|
||||
if path == "/popup":
|
||||
body = POPUP
|
||||
else:
|
||||
# the same server by another NAME is another site: the document lands in another process (Fission)
|
||||
port = self.server.server_address[1]
|
||||
other = ("http://localhost:%d/popup" % port).encode()
|
||||
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
|
||||
b"<a id=link href=/popup target=_blank>link</a>"
|
||||
b"<a id=noopener href=/popup target=_blank rel=noopener>noopener</a>"
|
||||
b"<button id=open onclick=\"window.open('/popup','_blank')\">open</button>"
|
||||
b"<button id=open-noopener onclick=\"window.open('/popup','_blank','noopener')\">open</button>"
|
||||
b"<a id=xlink href=" + other + b" target=_blank>cross-site link</a>"
|
||||
b"<a id=xnoopener href=" + other + b" target=_blank rel=noopener>cross-site noopener</a>"
|
||||
b"<button id=xopen onclick=\"window.open('" + other + b"','_blank')\">open</button>"
|
||||
b"<button id=xopen-noopener onclick=\"window.open('" + other + b"','_blank','noopener')\">open</button>"
|
||||
b"</body></html>")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site():
|
||||
srv = LocalServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def _stock_client(module):
|
||||
"""The stock Playwright client, a pinned dev dependency: its absence is a broken environment, not a reason to skip."""
|
||||
import importlib
|
||||
|
||||
try:
|
||||
return importlib.import_module(module)
|
||||
except ImportError as exc: # pragma: no cover - only in a broken environment
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc, pytrace=False)
|
||||
|
||||
|
||||
OPENERS = ["#link", "#noopener", "#open", "#open-noopener", "#xlink", "#xnoopener", "#xopen", "#xopen-noopener"]
|
||||
|
||||
|
||||
def _router(delay_s):
|
||||
def route(route):
|
||||
time.sleep(delay_s) # a client that decides: the popup's first request waits for it
|
||||
route.continue_()
|
||||
return route
|
||||
|
||||
|
||||
def _check(page, popup_of, site, opener):
|
||||
page.goto(site, wait_until="load", timeout=30000)
|
||||
# The verdict is that the popup arrives, with its address and its load: how long it takes depends on the machine (a runner with four
|
||||
# workers took 2.0 s once), so no time limit here beyond a generous wait.
|
||||
with page.expect_popup(timeout=30000) as info:
|
||||
page.click(opener)
|
||||
popup = info.value
|
||||
popup.wait_for_load_state("load", timeout=5000)
|
||||
expected = (site.replace("127.0.0.1", "localhost") if opener.startswith("#x") else site) + "popup"
|
||||
assert popup.url == expected
|
||||
assert popup.title() == "popup"
|
||||
assert popup in page.context.pages
|
||||
popup.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routed", [False, True], ids=["plain", "routed"])
|
||||
@pytest.mark.parametrize("opener", OPENERS)
|
||||
def test_a_popup_reaches_an_in_process_client(firefox_binary, site, opener, routed):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as b:
|
||||
ctx = b.new_context()
|
||||
if routed:
|
||||
ctx.route("**/*", _router(0.05))
|
||||
page = ctx.new_page()
|
||||
_check(page, None, site, opener)
|
||||
ctx.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routed", [False, True], ids=["plain", "routed"])
|
||||
@pytest.mark.parametrize("opener", OPENERS)
|
||||
def test_a_popup_reaches_a_stock_client_of_a_served_browser(firefox_binary, site, opener, routed):
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright # a stock client, as production uses
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
if routed:
|
||||
ctx.route("**/*", _router(0.05))
|
||||
page = ctx.new_page()
|
||||
_check(page, None, site, opener)
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""The README and the docs name the MCP server's repository and command as they are now.
|
||||
|
||||
After the September renames, `github.com/feder-cr/AIHawk` stopped being the MCP
|
||||
server: GitHub sends a renamed name to whatever object carries it, and on
|
||||
2026-11-06 that is an unrelated repository. Thirteen links answered 200 with a
|
||||
page that was not the one promised, which no link checker reports. Seven places
|
||||
also said `uvx aihawk`, a command that does not exist; the command is
|
||||
`invisible-playwright-mcp`.
|
||||
|
||||
CHANGELOG.md keeps the old name on purpose (an entry says what was true then),
|
||||
and so does the fixture in scripts/sync_article_pixels.py, which is the deliberate
|
||||
wrong case. Neither is read here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OLD = ("github.com/feder-cr/AIHawk", "uvx aihawk")
|
||||
|
||||
|
||||
def pages():
|
||||
return [ROOT / "README.md", *sorted((ROOT / "docs").rglob("*.md"))]
|
||||
|
||||
|
||||
def test_no_page_links_the_old_repository_or_runs_the_old_command():
|
||||
found = ["%s:%d: %s" % (p.relative_to(ROOT), n, old)
|
||||
for p in pages()
|
||||
for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1)
|
||||
for old in OLD if old.lower() in line.lower()]
|
||||
assert not found, ("these name the MCP server by its old name, which now leads elsewhere: use "
|
||||
"github.com/feder-cr/invisible_playwright_mcp and `uvx invisible-playwright-mcp`:\n"
|
||||
+ "\n".join(found))
|
||||
@@ -0,0 +1,482 @@
|
||||
"""The release-triple hunt (`.github/workflows/e2e-hunt.yml`, scripts/hunt_report.py,
|
||||
scripts/hunt_launch_close.py): its pure parts and the shape of the workflow.
|
||||
|
||||
The hunt is only worth the runner time if (a) the suite it repeats is exactly the one
|
||||
`e2e.yml` runs, (b) every run is recorded and a caught failure does not turn the job red,
|
||||
and (c) the failure messages come out whole. The first is checked against the two workflow
|
||||
files, the other two on logs written the way pytest writes them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import hunt_launch_close as launch # noqa: E402
|
||||
import hunt_report as report # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
HUNT = (ROOT / ".github" / "workflows" / "e2e-hunt.yml").read_text(encoding="utf-8")
|
||||
E2E = (ROOT / ".github" / "workflows" / "e2e.yml").read_text(encoding="utf-8")
|
||||
|
||||
PLAN = dict(which="all", suite_jobs=6, suite_runs_each=5, onecpu_runs=2, webgl_rounds=13,
|
||||
webgl_procs=4, launch_jobs=3, launch_cycles_each=100)
|
||||
|
||||
# ── a log as run_e2e.py writes it: two pytest passes, a rerun, a failure with a long message ──
|
||||
LOG = """\
|
||||
[run_e2e] binary=/x/firefox
|
||||
tests/test_a.py::test_one PASSED [ 10%]
|
||||
[gw1] [ 18%] RERUN tests/test_b.py::test_flaky
|
||||
tests/test_b.py::test_flaky PASSED [ 20%]
|
||||
=================================== FAILURES ===================================
|
||||
__________________ test_popup[in-process-open] __________________
|
||||
[gw3] linux -- Python 3.11.18 /x/python
|
||||
tests/test_popup.py:169: in test_popup
|
||||
assert run.popups, "stock announces the popup"
|
||||
E AssertionError: stock announces the popup
|
||||
E order of events: click +0.00s, popup target +0.21s, ready never
|
||||
E assert []
|
||||
_____________ test_launch _____________
|
||||
tests/test_launch.py:215: in test_launch
|
||||
E invisible_playwright._pw._impl._errors.Error: BrowserType.launch: [Errno 32] Broken pipe
|
||||
=========================== short test summary info ============================
|
||||
FAILED tests/test_popup.py::test_popup[in-process-open] - AssertionError: stock announces the popup
|
||||
assert []
|
||||
FAILED tests/test_launch.py::test_launch - invisible_playwright._pw._impl._errors.Error: BrowserType.launch: [Errno 32] Broken pipe
|
||||
============ 2 failed, 640 passed, 32 skipped, 1 rerun in 1238.26s (0:20:38) ============
|
||||
[run_e2e] -m 'e2e and wall_clock', browsers at once: 1 (serial)
|
||||
=============== 20 passed, 1845 deselected in 110.29s (0:01:50) ================
|
||||
"""
|
||||
GREEN_LOG = """\
|
||||
=============== 640 passed, 32 skipped in 1000.00s (0:16:40) ================
|
||||
=============== 20 passed, 1845 deselected in 110.29s (0:01:50) ================
|
||||
"""
|
||||
|
||||
|
||||
def rec(log, *, run=1, exit_code=1, cpus="all", seconds=1300):
|
||||
return report.run_record(log, run=run, of=5, label="suite x5 #1", cpus=cpus,
|
||||
exit_code=exit_code, seconds=seconds)
|
||||
|
||||
|
||||
# ── the plan ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_all_plans_30_suite_runs_a_one_cpu_leg_3_launch_jobs_and_the_webgl_hunt():
|
||||
plan = report.make_plan(**PLAN)
|
||||
assert (plan["suite"], plan["webgl"], plan["launch"]) == ("true", "true", "true")
|
||||
legs = json.loads(plan["suite_matrix"])
|
||||
ordinary = [leg for leg in legs if leg["cpus"] == "all"]
|
||||
assert len(ordinary) == 6 and sum(leg["runs"] for leg in ordinary) == 30
|
||||
(one,) = [leg for leg in legs if leg["cpus"] == "1"]
|
||||
assert one["taskset"] == "taskset -c 0" and one["runs"] == 2 and "1-CPU" in one["label"]
|
||||
assert all(leg["taskset"] == "" for leg in ordinary)
|
||||
assert len({leg["slug"] for leg in legs}) == len(legs), "an artifact name per leg"
|
||||
launch_legs = json.loads(plan["launch_matrix"])
|
||||
assert [leg["cycles"] for leg in launch_legs] == [100, 100, 100]
|
||||
assert [leg["start"] for leg in launch_legs] == [1, 101, 201]
|
||||
|
||||
|
||||
def test_the_job_ceiling_follows_the_runs_and_is_never_the_limit_of_a_run():
|
||||
legs = json.loads(report.make_plan(**dict(PLAN, suite_runs_each=5))["suite_matrix"])
|
||||
assert legs[0]["timeout"] >= 5 * 25 + 30 # a run is 18-20 minutes
|
||||
assert legs[-1]["timeout"] > legs[0]["timeout"] # one CPU is slower
|
||||
assert all(leg["timeout"] <= 355 for leg in legs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("which, expected", [
|
||||
("suite", ("true", "false", "false")),
|
||||
("webgl,launch", ("false", "true", "true")),
|
||||
("webgl", ("false", "true", "false")),
|
||||
(" Launch , suite ", ("true", "false", "true")),
|
||||
("all", ("true", "true", "true")),
|
||||
])
|
||||
def test_which_chooses_the_hunts_of_one_dispatch(which, expected):
|
||||
plan = report.make_plan(**dict(PLAN, which=which))
|
||||
assert (plan["suite"], plan["webgl"], plan["launch"]) == expected
|
||||
if expected[0] == "false":
|
||||
assert plan["suite_matrix"] == "[]"
|
||||
if expected[2] == "false":
|
||||
assert plan["launch_matrix"] == "[]"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("which", ["", "suites", "webgl,nope", ","])
|
||||
def test_a_which_that_names_no_hunt_is_refused_before_any_runner_is_spent(which):
|
||||
with pytest.raises(ValueError):
|
||||
report.make_plan(**dict(PLAN, which=which))
|
||||
|
||||
|
||||
def test_zero_one_cpu_runs_drops_that_leg_only():
|
||||
legs = json.loads(report.make_plan(**dict(PLAN, onecpu_runs=0))["suite_matrix"])
|
||||
assert len(legs) == 6 and all(leg["cpus"] == "all" for leg in legs)
|
||||
|
||||
|
||||
# ── reading a log ────────────────────────────────────────────────────────────
|
||||
|
||||
def test_the_two_passes_are_added_and_the_failed_ids_are_named():
|
||||
p = report.parse_pytest_log(LOG)
|
||||
assert (p["passed"], p["failed"], p["skipped"], p["rerun"]) == (660, 2, 32, 1)
|
||||
assert p["summaries"] == 2
|
||||
assert p["failed_ids"] == ["tests/test_popup.py::test_popup[in-process-open]",
|
||||
"tests/test_launch.py::test_launch"]
|
||||
assert p["rerun_ids"] == ["tests/test_b.py::test_flaky"]
|
||||
|
||||
|
||||
def test_a_failure_message_is_kept_whole_with_its_order_of_events():
|
||||
p = report.parse_pytest_log(LOG)
|
||||
message = p["failures"]["tests/test_popup.py::test_popup[in-process-open]"]
|
||||
assert message.splitlines() == ["AssertionError: stock announces the popup",
|
||||
" order of events: click +0.00s, popup target +0.21s, ready never",
|
||||
"assert []"]
|
||||
assert "[Errno 32] Broken pipe" in p["failures"]["tests/test_launch.py::test_launch"]
|
||||
|
||||
|
||||
def test_a_message_missing_from_the_failures_section_falls_back_to_the_short_summary():
|
||||
log = ("=== short test summary info ===\n"
|
||||
"FAILED tests/t.py::test_x - AssertionError: boom\nassert 1 == 2\n"
|
||||
"=== 1 failed in 1.00s ===\n")
|
||||
p = report.parse_pytest_log(log)
|
||||
assert p["failures"]["tests/t.py::test_x"] == "AssertionError: boom\nassert 1 == 2"
|
||||
|
||||
|
||||
def test_digits_do_not_make_two_messages_different():
|
||||
assert report.normalise("pids [63248] -> [63248, 63386] at 0x7fcf60 in 2.5 s") == \
|
||||
report.normalise("pids [1] -> [1, 22] at 0xab in 31.25 s")
|
||||
|
||||
|
||||
# ── a run's verdict: caught or broken ────────────────────────────────────────
|
||||
|
||||
def test_a_red_run_with_a_summary_is_a_caught_failure():
|
||||
r = rec(LOG)
|
||||
assert r["verdict"] == "red" and r["failed"] == 2
|
||||
assert "tests/test_launch.py::test_launch" in report.run_line(r)
|
||||
|
||||
|
||||
def test_a_green_run_is_green_and_a_run_that_never_reached_a_summary_is_broken():
|
||||
assert rec(GREEN_LOG, exit_code=0)["verdict"] == "green"
|
||||
assert rec("Traceback: pip failed\n", exit_code=2)["verdict"] == "no-verdict"
|
||||
assert rec("no summary here\n", exit_code=1)["verdict"] == "no-verdict" # killed, not red
|
||||
assert rec(GREEN_LOG, exit_code=5)["verdict"] == "no-verdict" # nothing collected
|
||||
|
||||
|
||||
def test_the_job_summary_is_red_only_for_a_broken_run(tmp_path, monkeypatch):
|
||||
monkeypatch.delenv("GITHUB_STEP_SUMMARY", raising=False)
|
||||
(tmp_path / "run_01.json").write_text(json.dumps(rec(LOG, run=1)))
|
||||
assert report.main(["suite-summary", str(tmp_path)]) == 0
|
||||
(tmp_path / "run_02.json").write_text(json.dumps(rec("x", run=2, exit_code=2)))
|
||||
assert report.main(["suite-summary", str(tmp_path)]) == 1
|
||||
assert report.main(["suite-summary", str(tmp_path / "nothing")]) == 1
|
||||
|
||||
|
||||
# ── the tally ────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_the_tally_counts_runs_green_runs_and_each_test_with_one_whole_message_per_distinct_message():
|
||||
other = LOG.replace("+0.21s", "+9.99s") # same message but for its numbers
|
||||
different = LOG.replace("ready never", "ready +1.00s, dropped") # a message of its own
|
||||
records = [rec(LOG, run=1), rec(other, run=2), rec(different, run=3),
|
||||
rec(GREEN_LOG, run=4, exit_code=0), rec(GREEN_LOG, run=5, exit_code=0)]
|
||||
text = report.suite_tally(records)
|
||||
assert "runs total: 5" in text
|
||||
assert "runs fully green: 2" in text
|
||||
assert "tests/test_popup.py::test_popup[in-process-open]: failed in 3 of 5 runs" in text
|
||||
assert text.count("message (seen") == 2 + 1 # popup: 2 distinct; launch: 1
|
||||
assert "order of events: click +0.00s, popup target +0.21s, ready never" in text
|
||||
assert "ready +1.00s, dropped" in text
|
||||
assert "tests/test_b.py::test_flaky: rerun in 3 of 5 runs" in text
|
||||
|
||||
|
||||
def test_the_one_cpu_leg_is_on_its_own_line_and_is_not_in_the_rate():
|
||||
records = [rec(GREEN_LOG, run=1, exit_code=0), rec(GREEN_LOG, run=2, exit_code=0),
|
||||
rec(LOG, run=1, cpus="1"), rec(LOG, run=2, cpus="1")]
|
||||
text = report.suite_tally(records)
|
||||
ordinary, one_cpu = text.split("## 1-CPU job")
|
||||
assert "runs total: 2" in ordinary and "runs fully green: 2" in ordinary
|
||||
assert "test_popup" not in ordinary
|
||||
assert "runs total: 2" in one_cpu and "runs fully green: 0" in one_cpu
|
||||
assert "test_popup[in-process-open]: failed in 2 of 2 runs" in one_cpu
|
||||
|
||||
|
||||
# ── the webgl hunt ───────────────────────────────────────────────────────────
|
||||
|
||||
WEBGL_FAIL = """\
|
||||
=================================== FAILURES ===================================
|
||||
_________________ test_webgl_getParameter_deterministic _________________
|
||||
tests/test_fingerprint_consistency.py:386: in test_webgl_getParameter_deterministic
|
||||
E AssertionError: WebGL getParameter check failed: reason='gl null' webgl2=False errors=['Could not create a WebGL context, FEATURE_FAILURE_WEBGL_EXHAUSTED_DRIVERS'] round=None param=None
|
||||
E assert False
|
||||
=========================== short test summary info ============================
|
||||
FAILED tests/test_fingerprint_consistency.py::test_webgl_getParameter_deterministic - AssertionError
|
||||
============ 1 failed in 12.00s ============
|
||||
"""
|
||||
WEBGL_PASS = "tests/test_fingerprint_consistency.py::test_webgl_getParameter_deterministic PASSED\n=== 1 passed in 9.00s ===\n"
|
||||
TEST = "tests/test_fingerprint_consistency.py::test_webgl_getParameter_deterministic"
|
||||
|
||||
|
||||
def wrec(log, round_, proc, code):
|
||||
return report.webgl_record(log, round_=round_, proc=proc, exit_code=code, test_id=TEST)
|
||||
|
||||
|
||||
def test_a_webgl_process_is_pass_fail_with_the_whole_reason_or_no_verdict():
|
||||
assert wrec(WEBGL_PASS, 1, 1, 0)["status"] == "pass"
|
||||
failed = wrec(WEBGL_FAIL, 1, 2, 1)
|
||||
assert failed["status"] == "fail"
|
||||
assert "errors=['Could not create a WebGL context, FEATURE_FAILURE_WEBGL_EXHAUSTED_DRIVERS']" in failed["message"]
|
||||
skipped = wrec("=== 1 skipped in 0.1s ===\n", 1, 3, 0)
|
||||
assert skipped["status"] == "no-verdict"
|
||||
assert wrec("killed", 1, 4, 137)["status"] == "no-verdict"
|
||||
|
||||
|
||||
def test_the_webgl_tally_says_n_failed_of_n_and_groups_the_reasons():
|
||||
other = WEBGL_FAIL.replace("EXHAUSTED_DRIVERS", "EXHAUSTED_DRIVERS_2")
|
||||
records = [wrec(WEBGL_PASS, 1, 1, 0), wrec(WEBGL_FAIL, 1, 2, 1), wrec(WEBGL_FAIL, 2, 1, 1),
|
||||
wrec(other, 2, 2, 1)]
|
||||
text = report.webgl_tally(records)
|
||||
assert "runs: 4" in text and "failed (caught): 3 of 4" in text
|
||||
assert "2 times (round 1 proc 2, round 2 proc 1), whole message:" in text
|
||||
assert "1 time (round 2 proc 2)" in text
|
||||
assert "EXHAUSTED_DRIVERS_2" in text
|
||||
|
||||
|
||||
# ── scripts/hunt_launch_close.py ─────────────────────────────────────────────
|
||||
|
||||
ENGINE = "\n".join(["line %d" % i for i in range(1, 30)] + ["[Parent] write: BROKEN PIPE"]
|
||||
+ ["tail %d" % i for i in range(5)])
|
||||
|
||||
|
||||
def test_the_marker_is_found_in_any_case_with_its_lines_around_it_whole():
|
||||
(excerpt,) = launch.find_marker(ENGINE, context=2)
|
||||
assert excerpt.splitlines() == ["line 28", "line 29", "[Parent] write: BROKEN PIPE", "tail 0", "tail 1"]
|
||||
assert launch.find_marker("all quiet\nnothing\n") == []
|
||||
assert launch.find_marker("Error: [Errno 32] Broken pipe") != []
|
||||
|
||||
|
||||
def test_two_hits_close_together_are_one_excerpt_and_far_apart_are_two():
|
||||
near = "a\nbroken pipe\nb\nBroken Pipe\nc"
|
||||
assert len(launch.find_marker(near, context=2)) == 1
|
||||
far = "broken pipe\n" + "x\n" * 30 + "broken pipe"
|
||||
assert len(launch.find_marker(far, context=2)) == 2
|
||||
|
||||
|
||||
def test_browser_processes_are_counted_by_executable_not_by_name(tmp_path):
|
||||
binary = tmp_path / "firefox"
|
||||
binary.write_text("")
|
||||
other = tmp_path / "other"
|
||||
other.write_text("")
|
||||
processes = [(str(binary), ["firefox", "-contentproc"]), ("", [str(binary), "-no-remote"]),
|
||||
(str(other), [str(other)]), ("/usr/bin/python3", ["python3", "firefox"])]
|
||||
assert launch.count_browser_processes(processes, str(binary)) == 2
|
||||
assert launch.count_browser_processes([], str(binary)) == 0
|
||||
|
||||
|
||||
def _cycle(n, *, status=0, captured=None, leftover=0, engine_captured=True):
|
||||
return launch.cycle_record(cycle=n, headless=bool(n % 2), status=status, seconds=3.21,
|
||||
captured=captured or {"engine.log": "quiet", "stderr.log": ""},
|
||||
leftover=leftover, engine_captured=engine_captured)
|
||||
|
||||
|
||||
def test_a_cycle_with_the_marker_in_the_engine_log_says_where():
|
||||
r = _cycle(1, status=1, captured={"engine.log": ENGINE, "stderr.log": "Error: [Errno 32] Broken pipe"})
|
||||
assert r["broken_pipe"] and r["broken_pipe_in"] == ["engine.log", "stderr.log"]
|
||||
assert r["ok"] is False and set(r["excerpts"]) == {"engine.log", "stderr.log"}
|
||||
assert _cycle(2)["broken_pipe"] is False and _cycle(2)["ok"] is True
|
||||
|
||||
|
||||
def test_the_launch_tally_counts_cycles_failures_broken_pipes_and_leftovers():
|
||||
records = [_cycle(1), _cycle(2, status=1, captured={"engine.log": ENGINE}), _cycle(3, leftover=2),
|
||||
_cycle(4, status="timeout", engine_captured=False)]
|
||||
t = launch.tally(records)
|
||||
assert t == {"cycles": 4, "failures": 2, "broken_pipe": 1, "leftover_cycles": 1,
|
||||
"leftover_processes": 2, "engine_not_captured": 1}
|
||||
text = launch.render_summary(records, "#1")
|
||||
assert "[Parent] write: BROKEN PIPE" in text and "Cycle 2" in text
|
||||
|
||||
|
||||
def test_the_script_without_a_binary_ends_non_zero_and_does_not_run_cycles(tmp_path, capsys):
|
||||
assert launch.main(["--binary", str(tmp_path / "missing"), "--out", str(tmp_path)]) == 2
|
||||
assert "binary not found" in capsys.readouterr().err
|
||||
|
||||
|
||||
# ── the workflow ─────────────────────────────────────────────────────────────
|
||||
|
||||
def _job(name):
|
||||
m = re.search(r"^ %s:\n(.*?)(?=^ [A-Za-z0-9_-]+:\n|\Z)" % re.escape(name), HUNT, re.M | re.S)
|
||||
assert m, "job %s is missing from e2e-hunt.yml" % name
|
||||
return m.group(1)
|
||||
|
||||
|
||||
def test_the_three_hunts_and_the_tally_exist_and_the_old_loop_is_the_default():
|
||||
for name in ("plan", "suite", "suite-tally", "webgl", "launch-close"):
|
||||
_job(name)
|
||||
inputs = HUNT.split("permissions:")[0]
|
||||
assert re.search(r"hunt:\n(?:.*\n)*?\s+default: \"suite-loop\"\n(?:.*\n)*?\s+- release-triple", inputs)
|
||||
assert "if: inputs.hunt == 'suite-loop'" in _job("hunt")
|
||||
for name in ("plan",):
|
||||
assert "inputs.hunt == 'release-triple'" in _job(name)
|
||||
for name in ("which", "suite_jobs", "suite_runs_each", "suite_onecpu_runs", "webgl_rounds",
|
||||
"webgl_procs", "launch_jobs", "launch_cycles_each"):
|
||||
assert re.search(r"^ %s:\n" % name, HUNT, re.M), name
|
||||
|
||||
|
||||
def test_hunt_a_runs_the_command_of_e2e_yml():
|
||||
(ci_command,) = re.findall(r"^\s+run: (xvfb-run -a python -u scripts/run_e2e\.py \"\$FF\")$", E2E, re.M)
|
||||
suite = _job("suite")
|
||||
assert re.search(r"\$PRE %s > \"\$log\" 2>&1" % re.escape(ci_command), suite)
|
||||
assert not re.search(r"run_e2e\.py[^\n]*\s-n\b", suite), "the workers are the suite's own: four"
|
||||
assert re.search(r"\bseq 1 \"\$RUNS\"", suite) and "RUNS: ${{ matrix.runs }}" in suite
|
||||
# it never stops at the first red: the loop has no break and no exit on the code
|
||||
loop = suite.split("for n in")[1].split("done")[0]
|
||||
assert "break" not in loop and not re.search(r"(?m)^\s*exit", loop)
|
||||
|
||||
|
||||
def test_hunt_a_has_a_one_cpu_leg_that_is_taskset_zero_and_checks_the_workers_start():
|
||||
assert "PRE: ${{ matrix.taskset }}" in _job("suite")
|
||||
assert "taskset -c 0" in report.make_plan(**PLAN)["suite_matrix"]
|
||||
pre = re.search(r"Preflight of the 1-CPU leg\n\s+if: matrix\.taskset != ''\n(.*?)- name:", _job("suite"), re.S)
|
||||
assert pre and "taskset -c 0" in pre.group(1) and "-n 4" in pre.group(1)
|
||||
|
||||
|
||||
def test_hunt_b_runs_the_webgl_test_in_rounds_of_processes_started_together():
|
||||
webgl = _job("webgl")
|
||||
assert "tests/test_fingerprint_consistency.py::test_webgl_getParameter_deterministic" in webgl
|
||||
assert ") &\n" in webgl and 'wait "${pids[@]}"' in webgl
|
||||
assert "default: \"13\"" in HUNT and "default: \"4\"" in HUNT
|
||||
|
||||
|
||||
def test_hunt_c_runs_the_script_in_jobs_of_100_cycles():
|
||||
launch_job = _job("launch-close")
|
||||
assert "scripts/hunt_launch_close.py" in launch_job and (ROOT / "scripts" / "hunt_launch_close.py").exists()
|
||||
assert "--cycles \"$CYCLES\"" in launch_job
|
||||
assert re.search(r"launch_cycles_each:\n(?:.*\n)*?\s+default: \"100\"", HUNT)
|
||||
|
||||
|
||||
def test_every_job_that_makes_evidence_uploads_it_even_when_it_failed():
|
||||
for name in ("suite", "webgl", "launch-close"):
|
||||
job = _job(name)
|
||||
assert re.search(r"Upload the evidence\n\s+if: always\(\)\n\s+uses: actions/upload-artifact@", job), name
|
||||
assert "if: always() && needs.plan.outputs.suite == 'true'" in _job("suite-tally")
|
||||
|
||||
|
||||
def test_the_hunt_stays_on_ubuntu_24_04_read_only_and_cancels_its_predecessor():
|
||||
for name in ("plan", "suite", "suite-tally", "webgl", "launch-close"):
|
||||
assert "runs-on: ubuntu-24.04" in _job(name)
|
||||
assert re.search(r"^permissions:\n contents: read\n", HUNT, re.M)
|
||||
assert "group: ${{ github.workflow }}-${{ github.ref }}\n cancel-in-progress: true" in HUNT
|
||||
assert re.search(r"^env:\n GITHUB_TOKEN: \$\{\{ github\.token \}\}\n", HUNT, re.M)
|
||||
assert "contents: read\n actions: read" in _job("suite-tally")
|
||||
|
||||
|
||||
def test_every_action_is_pinned_by_a_sha_the_file_already_used():
|
||||
original = {"actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5",
|
||||
"actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065",
|
||||
"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02"}
|
||||
used = set(re.findall(r"uses: (\S+@\S+)", HUNT))
|
||||
assert used == original
|
||||
|
||||
|
||||
def test_a_caught_failure_does_not_make_a_job_red():
|
||||
suite = _job("suite")
|
||||
# the suite step records the exit code and goes on; only the summary step can be red
|
||||
assert "code=$?" in suite and "set -e\n" in suite
|
||||
assert "Red here = a run without a verdict" in suite
|
||||
assert "ends 0 whatever the cycles did" in _job("launch-close")
|
||||
|
||||
|
||||
def test_no_local_path_and_no_product_name_in_the_hunt_files():
|
||||
for text in (HUNT, (ROOT / "scripts" / "hunt_report.py").read_text(encoding="utf-8"),
|
||||
(ROOT / "scripts" / "hunt_launch_close.py").read_text(encoding="utf-8")):
|
||||
assert not re.search(r"[A-Za-z]:[\\/](?:Users|ff)\b|/Users/|C:\\\\", text)
|
||||
|
||||
|
||||
# ── the popups hunt (which=popups) ───────────────────────────────────────────
|
||||
|
||||
SHA_A = "a90dadc204ac2de807038531c3f03a80729328cf"
|
||||
SHA_B = "b" * 40
|
||||
ATTACH_LOG = LOG.replace("AssertionError: stock announces the popup",
|
||||
"AssertionError: stock announces the popup (its url is empty) before it closes")
|
||||
|
||||
|
||||
def test_popups_is_chosen_by_name_and_never_part_of_all():
|
||||
plan = report.make_plan(**dict(PLAN, popup_shas=SHA_A))
|
||||
assert plan["popups"] == "false" and plan["popup_matrix"] == "[]"
|
||||
plan = report.make_plan(**dict(PLAN, which="popups", popup_shas=SHA_A))
|
||||
assert (plan["suite"], plan["webgl"], plan["launch"], plan["popups"]) == ("false",) * 3 + ("true",)
|
||||
|
||||
|
||||
def test_popups_plans_jobs_for_every_sha_in_parallel_with_the_runs_each():
|
||||
plan = report.make_plan(**dict(PLAN, which="popups", popup_shas="%s, %s,%s" % (SHA_A, SHA_B, SHA_A),
|
||||
popup_jobs_each=5, popup_runs_each=2))
|
||||
legs = json.loads(plan["popup_matrix"])
|
||||
assert len(legs) == 10 and sum(leg["runs"] for leg in legs) == 20 # 10 runs per sha, a repeated sha once
|
||||
assert {leg["sha"] for leg in legs} == {SHA_A, SHA_B}
|
||||
assert len({leg["slug"] for leg in legs}) == 10
|
||||
assert all(leg["timeout"] >= 2 * 30 + 30 for leg in legs)
|
||||
|
||||
|
||||
def test_popups_can_run_together_with_another_hunt():
|
||||
plan = report.make_plan(**dict(PLAN, which="popups,webgl", popup_shas=SHA_A))
|
||||
assert (plan["popups"], plan["webgl"], plan["suite"]) == ("true", "true", "false")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kwargs", [dict(popup_shas=""), dict(popup_shas=" , "),
|
||||
dict(popup_shas=SHA_A, popup_jobs_each=0),
|
||||
dict(popup_shas=SHA_A, popup_runs_each=0)])
|
||||
def test_popups_without_a_commit_or_runs_is_refused_before_any_runner_is_spent(kwargs):
|
||||
with pytest.raises(ValueError):
|
||||
report.make_plan(**dict(PLAN, which="popups", **kwargs))
|
||||
|
||||
|
||||
def test_the_attachment_failure_is_told_from_the_others():
|
||||
attach = "AssertionError: stock announces the popup (its url is empty) before it closes\nassert []"
|
||||
assert report.classify_popup_failure("t", attach) == "attachment"
|
||||
assert report.classify_popup_failure("t", "assert []\n + where [] = <_Run object>.popups") == "attachment"
|
||||
assert report.classify_popup_failure("t", "Error: BrowserType.launch: [Errno 32] Broken pipe") == "other"
|
||||
assert report.classify_popup_failure("t", "") == "other"
|
||||
|
||||
|
||||
def _popup_rec(log, sha, run, label="popups aaaaaaa #1 x2", exit_code=1):
|
||||
return report.run_record(log, run=run, of=2, label=label, cpus="1", exit_code=exit_code,
|
||||
seconds=600, sha=sha)
|
||||
|
||||
|
||||
def test_the_popups_tally_is_per_commit_with_whole_messages_and_one_line_per_red_run():
|
||||
attachment_only = ATTACH_LOG.replace("FAILED tests/test_launch.py::test_launch", "PASSED x")
|
||||
records = [_popup_rec(attachment_only.replace("\n_____________ test_launch _____________", "\n"), SHA_A, 1),
|
||||
_popup_rec(LOG, SHA_A, 2),
|
||||
_popup_rec(GREEN_LOG, SHA_B, 1, label="popups bbbbbbb #1 x2", exit_code=0),
|
||||
_popup_rec(GREEN_LOG, SHA_B, 2, label="popups bbbbbbb #1 x2", exit_code=0)]
|
||||
text = report.popups_tally(records)
|
||||
first, second = text.split("## commit %s" % SHA_B)
|
||||
assert "runs total: 2" in first and "runs with at least one red: 2" in first
|
||||
assert "ready never" in first # the whole message, with its events
|
||||
assert "order of events: click +0.00s, popup target +0.21s" in first
|
||||
assert "run 2/2: other (also 1 attachment): " in first # the second red run has a launch failure too
|
||||
assert "run 1/2: " in first
|
||||
assert "runs total: 2" in second and "runs with at least one red: 0" in second and "- none" in second
|
||||
|
||||
|
||||
def test_a_run_with_only_the_attachment_failure_is_classified_as_that():
|
||||
log = ("=== FAILURES ===\n___ test_a ___\nE AssertionError: stock announces the popup (its url is empty)\n"
|
||||
"E assert []\n=== short test summary info ===\nFAILED tests/t.py::test_a - AssertionError\n"
|
||||
"=== 1 failed, 20 passed in 5.00s ===\n")
|
||||
text = report.popups_tally([_popup_rec(log, SHA_A, 1)])
|
||||
assert "run 1/2: attachment / run.popups empty: tests/t.py::test_a" in text
|
||||
|
||||
|
||||
def test_the_popups_job_checks_out_the_commit_but_takes_this_file_from_the_dispatch_ref():
|
||||
job = _job("popups")
|
||||
assert "ref: \"${{ matrix.sha }}\"" in job and "path: code" in job and "path: hunt-tools" in job
|
||||
assert "./code[dev]" in job and "hunt-tools/scripts/hunt_report.py" in job
|
||||
assert "tests/test_popup_destinations_e2e.py tests/test_popups_reach_the_client_e2e.py" in job
|
||||
# the suite's own entry (its options are the commit's), on one CPU, four workers, in a row
|
||||
assert re.search(r"taskset -c 0 xvfb-run -a python -u scripts/run_e2e\.py \"\$FF\"", job)
|
||||
assert not re.search(r"run_e2e\.py[^\n]*\s-n\b", job)
|
||||
assert "-n 4" in job.split("Preflight")[1].split("- name:")[0]
|
||||
assert re.search(r"Upload the evidence\n\s+if: always\(\)\n\s+uses: actions/upload-artifact@", job)
|
||||
assert "break" not in job and "--sha \"$SHA\"" in job
|
||||
assert "if: always() && needs.plan.outputs.popups == 'true'" in _job("popups-tally")
|
||||
assert "popup_shas" in HUNT.split("permissions:")[0]
|
||||
assert "origin/${x}^{commit}" in _job("plan") and "fetch-depth: 0" in _job("plan")
|
||||
@@ -0,0 +1,307 @@
|
||||
"""Every order in which the engine's events about a popup can reach the adoption gives the client exactly one `page` event.
|
||||
|
||||
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection, and the adoption thread stopped, one step at a time, at SIX
|
||||
points of its own (before it records itself as building, before it sends the init scripts, before it waits for the main frame, before it
|
||||
records itself as waiting, before it waits for the ready, before it announces) while the engine's events are delivered between the steps.
|
||||
|
||||
The events of a target that is not a page a caller asked for, as the engine sends them: ATTACH (always first), then FRAME (the main frame
|
||||
and its contexts), COMMIT (the initial about:blank), READY, and DETACH (the tab is closed: a download's empty tab, a popup the site closed)
|
||||
which can come after ANY prefix of the others and after which the engine answers "cannot find session" to every command about the
|
||||
session. For each of the prefixes that can occur, EVERY placement of its events among the eight moments of the adoption (parked at
|
||||
each of the six points, while it waits for the ready, after it) is run: 650 cases, none sampled.
|
||||
|
||||
The invariant (`_Adoption`): such a target gives the client exactly ONE `page` event, at its ready or at its disappearance, and when
|
||||
it disappeared its close right after, never before; no warning of a failed adoption; nothing left in the registry; the adoption thread
|
||||
ends. A target that gets neither a ready nor a detach gives no event and its wait ends with its context.
|
||||
|
||||
Why it exists: the same race was found four times by a run on a loaded machine, each time one step further along (a detach before the
|
||||
ready, during the build, between the build and the wait, and a command answered "cannot find session"); a fifth was this test's first
|
||||
find (a detach while the adoption waits for the main frame of a tab the engine never announced).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.juggler.connection import ProtocolError
|
||||
from invisible_playwright._juggler import dispatcher as base
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
from invisible_playwright._juggler.server import LocalUtilsDispatcher
|
||||
|
||||
from test_a_closed_context_leaves_nothing_in_the_registry import ScriptedJuggler
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
TARGET = "x1"
|
||||
SESSION = "xs1"
|
||||
FRAME = "fx1"
|
||||
#: where the adoption thread can be stopped, in the order it reaches them
|
||||
GATES = ["building", "init_scripts", "main_frame", "waiting", "ready_wait", "announce"]
|
||||
#: the moments an event can be delivered: parked at each gate, while it waits for the ready, parked at `announce`, after it is over
|
||||
MOMENTS = ["g0", "g1", "g2", "g3", "g4", "during_wait", "g5", "after"]
|
||||
|
||||
|
||||
class Engine(ScriptedJuggler):
|
||||
"""The scripted engine, which answers 'cannot find session' to a command about a session whose target it took away."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.gone_sessions = set()
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30):
|
||||
if session in self.gone_sessions:
|
||||
raise ProtocolError('%s: ERROR: cannot find session with id "%s"' % (method, session))
|
||||
return super().send(method, params, session, timeout)
|
||||
|
||||
def attach(self, opener_target, context_id):
|
||||
self.sessions[TARGET] = SESSION
|
||||
self.dispatch_event("Browser.attachedToTarget", {
|
||||
"sessionId": SESSION,
|
||||
"targetInfo": {"targetId": TARGET, "type": "page", "openerId": opener_target, "browserContextId": context_id}}, None)
|
||||
|
||||
def frame(self):
|
||||
self.dispatch_event("Page.frameAttached", {"frameId": FRAME, "parentFrameId": None}, SESSION)
|
||||
for world in ("", "utility"):
|
||||
self.dispatch_event("Runtime.executionContextCreated", {
|
||||
"executionContextId": "e%s" % world, "auxData": {"frameId": FRAME, "name": world}}, SESSION)
|
||||
|
||||
def commit(self):
|
||||
self.dispatch_event("Page.navigationStarted", {"frameId": FRAME, "navigationId": "n1", "url": "about:blank"}, SESSION)
|
||||
self.dispatch_event("Page.navigationCommitted", {"frameId": FRAME, "navigationId": "n1", "url": "about:blank", "name": ""}, SESSION)
|
||||
|
||||
def ready(self):
|
||||
self.dispatch_event("Page.ready", {}, SESSION)
|
||||
|
||||
def detach(self):
|
||||
self.gone_sessions.add(SESSION)
|
||||
self.dispatch_event("Browser.detachedFromTarget", {"targetId": TARGET, "sessionId": SESSION}, None)
|
||||
|
||||
|
||||
class Gates:
|
||||
"""Stops the adoption thread of the popup at each of the six points, until the test lets it pass."""
|
||||
|
||||
def __init__(self):
|
||||
self.reached = [threading.Event() for _ in GATES]
|
||||
self.release = [threading.Event() for _ in GATES]
|
||||
self.passed = set()
|
||||
|
||||
def pause(self, index):
|
||||
if threading.current_thread().name != "invpw-adopt-%s" % TARGET or index in self.passed:
|
||||
return
|
||||
self.passed.add(index)
|
||||
self.reached[index].set()
|
||||
self.release[index].wait(10)
|
||||
|
||||
def open_all(self):
|
||||
for event in self.release:
|
||||
event.set()
|
||||
|
||||
|
||||
def _thread():
|
||||
for t in threading.enumerate():
|
||||
if t.name == "invpw-adopt-%s" % TARGET:
|
||||
return t
|
||||
return None
|
||||
|
||||
|
||||
def _wait(condition, seconds=3.0):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if condition():
|
||||
return True
|
||||
time.sleep(0.002)
|
||||
return condition()
|
||||
|
||||
|
||||
def _install_gates(monkeypatch, gates):
|
||||
def gated(index, owner, name):
|
||||
original = getattr(owner, name)
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
gates.pause(index)
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(owner, name, wrapper)
|
||||
|
||||
gated(0, server_mod.BrowserDispatcher, "_enter_building")
|
||||
gated(1, server_mod.InjectedScript, "install")
|
||||
gated(2, server_mod.Lifecycle, "wait_for_main_frame")
|
||||
gated(3, server_mod.BrowserDispatcher, "_enter_waiting")
|
||||
gated(4, server_mod.PageDispatcher, "wait_until_ready")
|
||||
gated(5, server_mod.BrowserDispatcher, "_enter_announced")
|
||||
|
||||
|
||||
def _run(events, placement):
|
||||
"""One case: `events` (a prefix of frame, commit, ready, detach) delivered at the moments in `placement` (one per event)."""
|
||||
gates = Gates()
|
||||
trace = []
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext":
|
||||
trace.append("page")
|
||||
elif method == "close" and getattr(self, "TYPE", "") == "Page" and getattr(self, "target_id", None) == TARGET:
|
||||
trace.append("close")
|
||||
return original_emit(self, method, params)
|
||||
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(base.Dispatcher, "emit", spy)
|
||||
_install_gates(mp, gates)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = Engine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
# the opener, built with no gate (the gates only stop the popup's own thread)
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
del trace[:] # the opener's own page event is not the popup's
|
||||
|
||||
todo = list(zip(events, placement))
|
||||
delivered = set()
|
||||
|
||||
def deliver(moment):
|
||||
for event, where in list(todo):
|
||||
if where == moment:
|
||||
getattr(conn, event)()
|
||||
delivered.add(event)
|
||||
todo.remove((event, where))
|
||||
|
||||
def deliver_next():
|
||||
"""The adoption is blocked in a wait that only an event of the engine can end: the next one arrives now (that wait IS the
|
||||
moment it was placed at)."""
|
||||
if todo:
|
||||
event, _where = todo.pop(0)
|
||||
getattr(conn, event)()
|
||||
delivered.add(event)
|
||||
return True
|
||||
return False
|
||||
|
||||
def advance_until(condition, what, seconds=3.0):
|
||||
"""Wait for `condition`; while nothing moves for 0.1 s, deliver the next pending event."""
|
||||
end = time.monotonic() + seconds
|
||||
idle_since = time.monotonic()
|
||||
while time.monotonic() < end:
|
||||
if condition():
|
||||
return True
|
||||
if time.monotonic() - idle_since > 0.1:
|
||||
if deliver_next():
|
||||
idle_since = time.monotonic()
|
||||
else:
|
||||
idle_since = time.monotonic() + 1e9 # nothing left to deliver: just wait
|
||||
time.sleep(0.002)
|
||||
assert condition(), what
|
||||
return True
|
||||
|
||||
def parked(i):
|
||||
return gates.reached[i].is_set() or _thread() is None
|
||||
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
conn.attach(opener_target, context.context_id)
|
||||
assert gates.reached[0].wait(3), "the adoption thread never started"
|
||||
for i in range(5): # parked at gate i
|
||||
if i > 0:
|
||||
advance_until(lambda: parked(i) or any(gates.reached[j].is_set() for j in range(i + 1, 6)),
|
||||
"the adoption thread never reached %s" % GATES[i])
|
||||
deliver("g%d" % i)
|
||||
gates.release[i].set()
|
||||
# gate 4 is released: the thread is in (or about to be in) its wait for the ready
|
||||
deliver("during_wait")
|
||||
final_unblocked = "ready" in delivered or "detach" in delivered or any(e in ("ready", "detach") for e, _ in todo)
|
||||
if final_unblocked:
|
||||
advance_until(lambda: gates.reached[5].is_set() or _thread() is None, "the wait for the ready never ended")
|
||||
deliver("g5") # parked at the announcement (if it got there)
|
||||
gates.release[5].set()
|
||||
advance_until(lambda: _thread() is None, "the adoption thread never ended")
|
||||
deliver("after")
|
||||
while deliver_next(): # anything left arrives after it all
|
||||
pass
|
||||
else:
|
||||
while deliver_next():
|
||||
pass
|
||||
time.sleep(0.05)
|
||||
assert _thread() is not None or not trace, "a target with neither ready nor detach was announced"
|
||||
time.sleep(0.01)
|
||||
bad = [str(w.message) for w in caught if "adoption" in str(w.message)]
|
||||
return trace, bad, dict(server_state=len(browser._adoptions)), (browser, context, gates, conn)
|
||||
finally:
|
||||
gates.open_all()
|
||||
|
||||
|
||||
def _check(events, placement):
|
||||
trace, bad, state, (browser, context, gates, conn) = _run(events, placement)
|
||||
try:
|
||||
label = "events %s at %s" % (events, placement)
|
||||
problems = []
|
||||
disappears = "detach" in events
|
||||
if bad:
|
||||
problems.append("a warning of a failed adoption: %s" % bad)
|
||||
if "ready" in events or disappears:
|
||||
if trace.count("page") != 1:
|
||||
problems.append("%d page events" % trace.count("page"))
|
||||
if disappears:
|
||||
if trace.count("close") != 1:
|
||||
problems.append("%d close events" % trace.count("close"))
|
||||
elif "page" in trace and trace.index("page") > trace.index("close"):
|
||||
problems.append("the close came before the page")
|
||||
elif trace.count("close"):
|
||||
problems.append("a close for a page that did not disappear")
|
||||
if state["server_state"] != 0:
|
||||
problems.append("%d adoptions left in the registry" % state["server_state"])
|
||||
else:
|
||||
if trace:
|
||||
problems.append("events %r for a target with neither ready nor detach" % (trace,))
|
||||
# its context closes: the wait ends, still nothing announced
|
||||
browser.server.handle({"guid": context.guid, "method": "close", "params": {}})
|
||||
if not _wait(lambda: _thread() is None):
|
||||
problems.append("the wait did not end with its context")
|
||||
if trace.count("page"):
|
||||
problems.append("announced after its context closed")
|
||||
return label, problems
|
||||
finally:
|
||||
gates.open_all()
|
||||
try:
|
||||
browser.server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _placements(n, moments):
|
||||
"""Every way of putting n events, in order, on the given moments (the same moment allowed, the order kept)."""
|
||||
return itertools.combinations_with_replacement(range(len(moments)), n)
|
||||
|
||||
|
||||
SEQUENCES = {
|
||||
"frame_commit_ready": (["frame", "commit", "ready"], MOMENTS),
|
||||
"frame_commit_ready_detach": (["frame", "commit", "ready", "detach"], MOMENTS),
|
||||
"frame_commit_detach": (["frame", "commit", "detach"], MOMENTS),
|
||||
"frame_detach": (["frame", "detach"], MOMENTS),
|
||||
"detach": (["detach"], MOMENTS),
|
||||
# neither ready nor detach: nothing is announced; the events can only arrive while the adoption is alive
|
||||
"frame_commit": (["frame", "commit"], MOMENTS[:6]),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", sorted(SEQUENCES))
|
||||
def test_every_order_of_the_events_of_a_popup_gives_one_page_event(name):
|
||||
events, moments = SEQUENCES[name]
|
||||
failures = []
|
||||
count = 0
|
||||
for combo in _placements(len(events), moments):
|
||||
placement = [moments[i] for i in combo]
|
||||
count += 1
|
||||
try:
|
||||
label, problems = _check(events, placement)
|
||||
except AssertionError as e:
|
||||
label, problems = "events %s at %s" % (events, placement), [str(e)]
|
||||
if problems:
|
||||
failures.append("%s: %s" % (label, "; ".join(problems)))
|
||||
assert count > 0
|
||||
assert not failures, "%d of %d orders broke the invariant, e.g.:\n %s" % (len(failures), count, "\n ".join(failures[:12]))
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Every route command (continue, abort, fulfill, redirect) leaves through `RouteDispatcher._send`, and `_send` swallows the one
|
||||
error that is not an error: the request the browser has already closed.
|
||||
|
||||
Stock Playwright's server sends the three interception commands as may-fail. Here a new command that talked to the page
|
||||
directly (`self.request.page.send("Network....")`) would bring the old defect back: the client keeps an error for the whole
|
||||
connection and raises it on the next route command, which is then never sent (see
|
||||
`test_networkidle_through_a_served_browser_with_routes_e2e.py`). No browser: the source is read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
SERVER = pathlib.Path(__file__).resolve().parents[1] / "src" / "invisible_playwright" / "_juggler" / "server.py"
|
||||
|
||||
|
||||
def _route_dispatcher():
|
||||
tree = ast.parse(SERVER.read_text(encoding="utf-8"))
|
||||
return next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "RouteDispatcher")
|
||||
|
||||
|
||||
def _methods(cls):
|
||||
return {n.name: n for n in cls.body if isinstance(n, ast.FunctionDef)}
|
||||
|
||||
|
||||
def _sends_network_command(fn):
|
||||
"""The `page.send` / `conn.send` / `_send` calls of a function that name a Network.* command string."""
|
||||
out = []
|
||||
for node in ast.walk(fn):
|
||||
if isinstance(node, ast.Call):
|
||||
for arg in node.args[:1]:
|
||||
if isinstance(arg, ast.Constant) and isinstance(arg.value, str) and arg.value.startswith("Network."):
|
||||
out.append((getattr(node.func, "attr", getattr(node.func, "id", "?")), arg.value))
|
||||
return out
|
||||
|
||||
|
||||
def test_every_op_of_a_route_goes_through__send_and_nothing_else_talks_to_the_page():
|
||||
methods = _methods(_route_dispatcher())
|
||||
ops = {name: fn for name, fn in methods.items() if name.startswith("op_")}
|
||||
assert set(ops) >= {"op_abort", "op_continue", "op_fulfill", "op_redirect"}, sorted(ops)
|
||||
for name, fn in ops.items():
|
||||
sends = _sends_network_command(fn)
|
||||
assert sends, "%s sends no Network command at all: update this guard if it is a new kind" % name
|
||||
for via, command in sends:
|
||||
assert via == "_send", "%s sends %s through %s, not through RouteDispatcher._send" % (name, command, via)
|
||||
# and the only direct talk to the page in the class is _send's
|
||||
for name, fn in methods.items():
|
||||
if name in ops or name == "_send":
|
||||
continue
|
||||
assert not _sends_network_command(fn), "%s sends a Network command by itself" % name
|
||||
|
||||
|
||||
def test__send_answers_every_protocol_error_of_a_route_command_as_may_fail():
|
||||
"""Stock's `sendMayFail`: whatever the engine says about a request the page already closed ("Cannot find request",
|
||||
"NS_BINDING_ABORTED [nsIInterceptedChannel.resetInterceptionWithURI]", the next wording) is not the client's error."""
|
||||
send = _methods(_route_dispatcher())["_send"]
|
||||
handlers = [n for n in ast.walk(send) if isinstance(n, ast.ExceptHandler)]
|
||||
caught = {ast.unparse(h.type) for h in handlers if h.type is not None}
|
||||
assert caught == {"juggler.ProtocolError", "juggler.TargetClosedError"}, caught
|
||||
assert not any(isinstance(n, ast.Raise) for h in handlers for n in ast.walk(h)), \
|
||||
"an error of a route command must never reach the client: it would be raised on its NEXT route command"
|
||||
source = ast.get_source_segment(SERVER.read_text(encoding="utf-8"), send)
|
||||
assert source.index("self.dispose()") > source.index("except juggler.TargetClosedError"), \
|
||||
"the route is disposed after a swallowed error too"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("message", [
|
||||
'Network.resumeInterceptedRequest: Cannot find request "123"',
|
||||
"Network.resumeInterceptedRequest: Component returned failure code: 0x804b0002 (NS_BINDING_ABORTED) "
|
||||
"[nsIInterceptedChannel.resetInterceptionWithURI]",
|
||||
"Network.abortInterceptedRequest: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)",
|
||||
])
|
||||
def test_a_protocol_error_from_the_engine_is_not_the_clients_error(message):
|
||||
from invisible_playwright._juggler import server as srv
|
||||
|
||||
class Page:
|
||||
def send(self, command, params):
|
||||
raise srv.juggler.ProtocolError(message)
|
||||
|
||||
class Request:
|
||||
page = Page()
|
||||
request_id = "r1"
|
||||
|
||||
route = object.__new__(srv.RouteDispatcher)
|
||||
route.request, route.answered, route.dispose = Request(), False, lambda: None
|
||||
assert route._send("Network.resumeInterceptedRequest", {}) is None
|
||||
|
||||
|
||||
def test_the_stock_client_the_networkidle_e2e_drives_the_server_with_is_a_pinned_dev_dependency():
|
||||
"""That e2e fails (not skips) without the stock Playwright client, so CI must install it: the `dev` extra pins it to the
|
||||
version of scripts/playwright_pin.txt."""
|
||||
import tomllib
|
||||
|
||||
root = SERVER.parents[3]
|
||||
dev = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["optional-dependencies"]["dev"]
|
||||
pin = (root / "scripts" / "playwright_pin.txt").read_text(encoding="utf-8").strip()
|
||||
assert "playwright==%s" % pin in dev, dev
|
||||
@@ -354,10 +354,17 @@ def test_webgl_getParameter_deterministic(page):
|
||||
res = _ev(page, """() => {
|
||||
const norm = v => (ArrayBuffer.isView(v) ? Array.from(v) : v);
|
||||
const c = document.createElement('canvas');
|
||||
// The browser's own reason for a context it could not create (the event carries it; the page only
|
||||
// sees null otherwise). A null seen once in 31 runs of the e2e on a loaded runner said 'gl null' and
|
||||
// nothing else, which cannot be told from a missing GL, a refused library, an allocation that failed.
|
||||
const errors = [];
|
||||
c.addEventListener('webglcontextcreationerror', e => errors.push(e.statusMessage || ''), false);
|
||||
const gl = c.getContext('webgl');
|
||||
if (!gl) {
|
||||
return {ok: false, reason: 'gl null',
|
||||
webgl2: !!c.getContext('webgl2')};
|
||||
const c2 = document.createElement('canvas');
|
||||
c2.addEventListener('webglcontextcreationerror', e => errors.push('webgl2: ' + (e.statusMessage || '')), false);
|
||||
return {ok: false, reason: 'gl null', errors,
|
||||
webgl2: !!c2.getContext('webgl2')};
|
||||
}
|
||||
if (gl.isContextLost()) {
|
||||
return {ok: false, reason: 'context lost'};
|
||||
@@ -385,7 +392,7 @@ def test_webgl_getParameter_deterministic(page):
|
||||
}""")
|
||||
assert res["ok"], (
|
||||
f"WebGL getParameter check failed: reason={res.get('reason')!r} "
|
||||
f"webgl2={res.get('webgl2')!r} round={res.get('round')!r} "
|
||||
f"webgl2={res.get('webgl2')!r} errors={res.get('errors')!r} round={res.get('round')!r} "
|
||||
f"param={res.get('param')!r} first={res.get('first')!r} "
|
||||
f"ref={res.get('ref')!r}"
|
||||
)
|
||||
|
||||
@@ -21,9 +21,10 @@ test says what the product does not do yet and the step that makes it green:
|
||||
9 named world after the OOP frame step 1a + 2b
|
||||
10 console of the OOP frame step 1a
|
||||
|
||||
The oracle for "another process" is the engine's own processes below the test (`-contentproc ... tab`): a
|
||||
cross-site frame adds at least one, a same-site one adds none. The count is read after the browser is quiet
|
||||
(the engine pre-allocates a content process and replaces it when it is used).
|
||||
The oracle for "another process" is the set of the engine's processes that host a site, below the test
|
||||
(tests/_processes.py says how a site's process is told from a preallocated one): a cross-site frame adds at
|
||||
least one, a same-site one changes nothing. The set is read once it is quiet. Off Linux the two tests that
|
||||
count processes skip: no other system names the process.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -37,6 +38,7 @@ from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from _processes import site_processes_below
|
||||
from _servers import LocalServer
|
||||
|
||||
FISSION_ON = {
|
||||
@@ -125,30 +127,18 @@ def engine_dir(firefox_binary):
|
||||
return str(Path(firefox_binary).resolve().parent)
|
||||
|
||||
|
||||
def content_processes(engine_dir):
|
||||
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
|
||||
import psutil
|
||||
|
||||
pids = set()
|
||||
for child in psutil.Process(os.getpid()).children(recursive=True):
|
||||
try:
|
||||
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
|
||||
continue
|
||||
cmd = child.cmdline()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in cmd and cmd[-1] == "tab":
|
||||
pids.add(child.pid)
|
||||
return pids
|
||||
def site_processes(engine_dir):
|
||||
"""The pids of the engine's processes below this test that host a site (tests/_processes.py)."""
|
||||
return site_processes_below(os.getpid(), engine_dir)
|
||||
|
||||
|
||||
def quiet(engine_dir, seconds=3.0, limit=30.0):
|
||||
"""The set of content processes once it has not changed for `seconds`."""
|
||||
"""The set of the processes that host a site, once it has not changed for `seconds`."""
|
||||
end = time.time() + limit
|
||||
last, since = content_processes(engine_dir), time.time()
|
||||
last, since = site_processes(engine_dir), time.time()
|
||||
while time.time() < end:
|
||||
time.sleep(0.25)
|
||||
now = content_processes(engine_dir)
|
||||
now = site_processes(engine_dir)
|
||||
if now != last:
|
||||
last, since = now, time.time()
|
||||
elif time.time() - since >= seconds:
|
||||
@@ -173,6 +163,21 @@ def page(browser):
|
||||
return page
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page_without_a_pool(firefox_binary):
|
||||
"""A page of a browser that keeps NO preallocated content processes (`dom.ipc.processPrelaunch.fission.number` 0): a process of a
|
||||
site then appears only because a site needed one. The default pool hands a preallocated process to a site whenever it gets to it, so
|
||||
a test that counts the processes of the sites between two reads sees the hand-out of the pool as if the frame had asked for it."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True,
|
||||
extra_prefs=dict(FISSION_ON, **{"dom.ipc.processPrelaunch.fission.number": 0})) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.set_default_timeout(3000)
|
||||
page.set_default_navigation_timeout(20000)
|
||||
yield page
|
||||
|
||||
|
||||
def wait_for(page, predicate, seconds=8.0):
|
||||
"""Until `predicate()`, with the client's events being read: the sync client takes the engine's events
|
||||
only inside its own calls, so a plain sleep would never see a frame arrive."""
|
||||
@@ -218,18 +223,34 @@ def test_cross_site_iframe_gets_its_own_process(page, cross_site_loop, engine_di
|
||||
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" and r["host"] == "a.test" and
|
||||
r["query"]["path"] == ["/leaf"] for r in cross_site_loop["reports"]))
|
||||
after = quiet(engine_dir)
|
||||
assert len(after - before) >= 1, "no new content process: before %s, after %s" % (sorted(before), sorted(after))
|
||||
assert len(after - before) >= 1, "no new process for a site: before %s, after %s" % (sorted(before), sorted(after))
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_same_site_other_port_stays_in_process(page, cross_site_loop, engine_dir):
|
||||
"""Green today, the control: a frame of the page's own site adds no content process."""
|
||||
def test_same_site_other_port_stays_in_process(page_without_a_pool, cross_site_loop, engine_dir):
|
||||
"""Green today, the control: a frame of the page's own site adds no process for a site.
|
||||
|
||||
The browser here keeps NO preallocated processes (`page_without_a_pool`): with the default pool of three the count of the processes of
|
||||
the sites moved between two reads without the frame having asked for anything - a preallocated process handed to a site later than
|
||||
the first read ([63248] -> [63248, 63386] on a four-worker runner, the third time in a row that this control was red there for the
|
||||
pool and not for the frame: 5402da4, ff2123e, fef0bc5). The frame is in the page's own origin (`a.test/leaf` in `a.test/plain`).
|
||||
|
||||
The frame is put in the page that is already shown, not reached by a navigation of the top. A top-level
|
||||
navigation whose old document may enter the back-forward cache replaces the browsing context
|
||||
(`mReplaceBrowsingContext`, dom/ipc/ProcessIsolation.cpp), and the new one may land in another process of
|
||||
the same site (`dom.ipc.processCount.webIsolated` is 4): seen once on the e2e of #451, [10878] -> [10878,
|
||||
11208] after a.test/plain -> a.test/same-site, never in 87 local runs. That is the top's process, not the
|
||||
frame's; a frame of the page's site stays in the page's process."""
|
||||
page = page_without_a_pool
|
||||
page.goto(cross_site_loop["plain"])
|
||||
before = quiet(engine_dir)
|
||||
page.goto(cross_site_loop["same_site"], wait_until="load")
|
||||
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" for r in cross_site_loop["reports"]))
|
||||
assert len(before) >= 1, "the page of a site has no process of its own to compare with: %s" % sorted(before)
|
||||
page.evaluate("(u) => { const f = document.createElement('iframe'); f.id = 's'; f.src = u;"
|
||||
" document.body.appendChild(f); }", cross_site_loop["leaf"])
|
||||
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" and r["query"]["path"] == ["/leaf"]
|
||||
for r in cross_site_loop["reports"]))
|
||||
after = quiet(engine_dir)
|
||||
assert not (after - before), "a same-site frame started a process: %s" % sorted(after - before)
|
||||
assert after == before, "a same-site frame changed the processes of the sites: %s -> %s" % (sorted(before), sorted(after))
|
||||
|
||||
|
||||
# ── 3 .. 10: what the product does not do yet ──────────────────────────────────
|
||||
|
||||
@@ -113,23 +113,57 @@ def test_the_posix_pipe_carries_messages_both_ways(firefox_binary, served, first
|
||||
pass
|
||||
|
||||
|
||||
# A parent whose descriptor table has nothing on 3 and 4 and whose pipes land far from them launches a program that reads fd 3 and
|
||||
# answers on fd 4, the contract of the engine (`nsRemoteDebuggingPipe.cpp` hard-wires the two numbers), and says what else it holds.
|
||||
_SPAWN_PARENT = """
|
||||
import fcntl, os, sys
|
||||
from invisible_core.juggler import connection
|
||||
|
||||
for fd in range(3, 64):
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
real_pipe = os.pipe
|
||||
|
||||
|
||||
def far_pipe():
|
||||
r, w = real_pipe()
|
||||
r2, w2 = fcntl.fcntl(r, fcntl.F_DUPFD, 20), fcntl.fcntl(w, fcntl.F_DUPFD, 20)
|
||||
os.close(r)
|
||||
os.close(w)
|
||||
return r2, w2
|
||||
|
||||
|
||||
os.pipe = far_pipe
|
||||
engine = ("import os; d = os.read(3, 16); "
|
||||
"extra = [fd for fd in range(5, 40) if os.path.exists('/proc/self/fd/%d' % fd) or os.path.exists('/dev/fd/%d' % fd)]; "
|
||||
"os.write(4, b'pong:' + d + b':' + str(len(extra)).encode())")
|
||||
our_write, our_read, process = connection._spawn_posix(sys.executable, ["-c", engine], dict(os.environ))
|
||||
os.write(our_write, b"ping")
|
||||
sys.stdout.write(os.read(our_read, 64).decode())
|
||||
process.wait(timeout=10)
|
||||
"""
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_spawn_keeps_the_two_hardwired_descriptors():
|
||||
"""The keep list must name 3 and 4, and this is a check on the CODE.
|
||||
"""What the launch must do, executed: the child it starts finds the pipe on descriptors 3 (it reads) and 4 (it writes), and no
|
||||
descriptor of the parent above them.
|
||||
|
||||
⛔ Written as a source assertion on purpose. The behavioural test above
|
||||
needs a Linux Firefox; this one needs nothing, so the day somebody
|
||||
"simplifies" the keep list back to the two pipe ends the failure arrives on
|
||||
every POSIX machine in the unit suite rather than on the one person who has
|
||||
a Linux build.
|
||||
⛔ THIS ASSERTED THE TEXT OF THE CORE'S SOURCE and broke the day the core launched with `posix_spawn` and file actions instead of
|
||||
`pass_fds=(its_read, its_write, 3, 4)`: the behaviour did not change, the words did. It needs no Linux Firefox: the "engine" is a
|
||||
program that reads fd 3 and answers on fd 4, exactly the contract of `nsRemoteDebuggingPipe.cpp`. The day somebody changes the
|
||||
launch so that the browser starts with nothing on 4 (a live process whose first write gets EPIPE), this fails on every POSIX
|
||||
machine of the unit suite rather than on the one person who has a Linux build.
|
||||
"""
|
||||
import inspect
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from invisible_core.juggler import connection as conn
|
||||
|
||||
source = inspect.getsource(conn._spawn_posix)
|
||||
assert "pass_fds=(its_read, its_write, 3, 4)" in source, (
|
||||
"the spawn no longer keeps descriptors 3 and 4. CPython's close sweep "
|
||||
"runs AFTER preexec_fn, so the dup2'd descriptors are closed again "
|
||||
"before exec and the browser starts with nothing on 4 - a live process "
|
||||
"whose first write gets EPIPE.")
|
||||
done = subprocess.run([sys.executable, "-c", _SPAWN_PARENT], capture_output=True, text=True, timeout=60)
|
||||
assert done.returncode == 0, ("the launch failed: %s" % (done.stderr.strip().splitlines()[-1:],))
|
||||
assert done.stdout.startswith("pong:ping:"), (
|
||||
"the child did not find the pipe on descriptors 3 and 4: it read nothing on 3 or its answer on 4 never came (%r)"
|
||||
% done.stdout)
|
||||
assert done.stdout.rsplit(":", 1)[-1] == "0", (
|
||||
"the child holds descriptors above 4 that the parent opened: " + done.stdout)
|
||||
@@ -0,0 +1,288 @@
|
||||
"""`goto(wait_until="networkidle")` arrives on a served browser whose context routes every request, as a stock Firefox does.
|
||||
|
||||
The shape of a production client: `launch_server()`, a stock Playwright client that connects to it over the WebSocket, a context
|
||||
route on `**/*` that aborts images, fonts and media and continues the rest, and a page that sends a beacon (`sendBeacon`,
|
||||
a POST the page does not wait for) and asks for the same font twice. Measured on real news sites through such a client: the
|
||||
navigation committed, `load` came, and `networkidle` never did (timeout at 30 s on about one fetch in seven, firefox-61 and
|
||||
firefox-62 alike), while a stock Firefox and Chromium reached it on the same addresses.
|
||||
|
||||
Red until the server, the Juggler or the core's lifecycle ends every request a routed page opens.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
def _stock_client(module):
|
||||
"""The stock Playwright client, as production (tf-fetch) drives the served browser. It is a pinned dev dependency
|
||||
(`playwright==` in the `dev` extra), so its absence is a broken environment, not a reason to skip: a gate that skips
|
||||
in CI checks nothing."""
|
||||
import importlib
|
||||
|
||||
try:
|
||||
return importlib.import_module(module)
|
||||
except ImportError as exc: # pragma: no cover - only in a broken environment
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
|
||||
PAGE = b"""<!doctype html><html><head><meta charset=utf-8><title>routed</title>
|
||||
<link rel=stylesheet href=/style.css>
|
||||
<link rel=preload as=font type=font/woff2 href=/font.woff2 crossorigin>
|
||||
<style>@font-face{font-family:F2;src:url(/font.woff2) format('woff2')}</style>
|
||||
<script src=/app.js></script>
|
||||
</head><body style="font-family:F,F2"><p>text in the font</p>
|
||||
<img src=/pixel.png><img src=/photo.jpg>
|
||||
<script>
|
||||
addEventListener('load', () => {
|
||||
navigator.sendBeacon('/beacon', JSON.stringify({ev: 'load'}));
|
||||
fetch('/api/data').then(r => r.text());
|
||||
});
|
||||
</script></body></html>"""
|
||||
CSS = b"@font-face{font-family:F;src:url(/font.woff2) format('woff2')} p{color:#333}"
|
||||
JS = b"window.__app = 1;"
|
||||
# The other shapes a news page has: a frame of another site (another process with Fission) with its own routed
|
||||
# resources, a worker that fetches, a script reached through a redirect.
|
||||
EXTRA = {
|
||||
"beacon": b"",
|
||||
"oop_iframe": b"<iframe src='http://localhost:%(port)d/frame'></iframe>",
|
||||
"worker": b"<script>new Worker('/worker.js')</script>",
|
||||
"redirect": b"<script src=/moved.js></script><img src=/moved.png>",
|
||||
# What a slow remote client meets: the page cancels requests while the route is still deciding.
|
||||
"cancel_fetch": b"<script>for(let i=0;i<30;i++){const c=new AbortController();fetch('/api/data?i='+i,{signal:c.signal}).catch(()=>{});setTimeout(()=>c.abort(),i%7)}</script>",
|
||||
"cancel_img": b"<script>for(let i=0;i<30;i++){const m=new Image();m.src='/pixel.png?a='+i;m.src='/pixel.png?b='+i}</script><script src=/slow.js></script>",
|
||||
"cancel_iframe": b"<script>for(let i=0;i<6;i++){const f=document.createElement('iframe');f.src='/frame?i='+i;document.body.appendChild(f);setTimeout(()=>f.remove(),5*i)}</script>",
|
||||
"cancel_navigation": b"<script>history.pushState({},'','/spa');fetch('/api/data');setTimeout(()=>{history.pushState({},'','/spa2');fetch('/api/data?x=1')},10)</script><script src=/slow.js></script>",
|
||||
# Beacons the way ad and analytics scripts send them: to another origin, and while the document is being left.
|
||||
"cross_beacon": b"<script>for(let i=0;i<6;i++)navigator.sendBeacon('http://localhost:%(port)d/beacon?i='+i,JSON.stringify({i}))</script>",
|
||||
"unload_beacon": b"<script>addEventListener('pagehide',()=>{for(let i=0;i<4;i++)navigator.sendBeacon('/beacon?leave='+i,'x')});addEventListener('visibilitychange',()=>navigator.sendBeacon('/beacon?vis','x'))</script>",
|
||||
"keepalive": b"<script>for(let i=0;i<4;i++)fetch('/api/data?k='+i,{method:'POST',keepalive:true,body:'x'}).catch(()=>{})</script>",
|
||||
"many": b"<script>for(let i=0;i<50;i++){fetch('/api/data?i='+i).catch(()=>{});(new Image).src='/pixel.png?i='+i}</script>",
|
||||
}
|
||||
# kinds whose route handler is slow (ms). The sync client runs the handlers one after the other, so the page's 100 requests
|
||||
# of `many` take 100 x (delay + one round trip); an async client (below) answers them all at once, like a Go client does.
|
||||
SLOW_MS = {"cancel_fetch": 120, "cancel_img": 120, "cancel_iframe": 120, "cancel_navigation": 120, "many": 20}
|
||||
FRAME = b"""<!doctype html><title>frame</title><link rel=stylesheet href=/style.css><img src=/ad.png>
|
||||
<script src=/app.js></script><script>addEventListener('load',()=>{navigator.sendBeacon('/beacon','f');fetch('/api/data')})</script>"""
|
||||
WORKER = b"fetch('/api/data').then(r => r.text()); setTimeout(() => fetch('/api/data'), 200);"
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
hits: list = []
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, body, ctype, status=200):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
path = self.path.split("?")[0]
|
||||
_Handler.hits.append(("GET", path))
|
||||
if path == "/":
|
||||
kind = (self.path.split("kind=")[1].split("&")[0]) if "kind=" in self.path else "beacon"
|
||||
extra = EXTRA[kind] % {b"port": self.server.server_address[1]} if b"%(" in EXTRA[kind] else EXTRA[kind]
|
||||
self._send(PAGE.replace(b"</body>", extra + b"</body>"), "text/html; charset=utf-8")
|
||||
elif path == "/frame":
|
||||
self._send(FRAME, "text/html; charset=utf-8")
|
||||
elif path == "/slow.js":
|
||||
time.sleep(0.15)
|
||||
self._send(JS, "text/javascript")
|
||||
elif path == "/worker.js":
|
||||
self._send(WORKER, "text/javascript")
|
||||
elif path in ("/moved.js", "/moved.png"):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "/app.js" if path.endswith(".js") else "/pixel.png")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
elif path == "/style.css":
|
||||
self._send(CSS, "text/css")
|
||||
elif path == "/app.js":
|
||||
self._send(JS, "text/javascript")
|
||||
elif path == "/api/data":
|
||||
self._send(b'{"ok":1}', "application/json")
|
||||
else: # the font and the images: the route aborts them, they must not get here
|
||||
self._send(b"x", "application/octet-stream")
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
self.rfile.read(n)
|
||||
_Handler.hits.append(("POST", self.path))
|
||||
self._send(b"", "text/plain", 204)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site():
|
||||
_Handler.hits = []
|
||||
srv = LocalServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
BLOCKED = {"image", "font", "media"}
|
||||
ANSWER_ERRORS: list = []
|
||||
|
||||
|
||||
def _router(delay_s):
|
||||
def route(route):
|
||||
if delay_s:
|
||||
time.sleep(delay_s) # a client far away: the page can cancel the request before the answer arrives
|
||||
try:
|
||||
if route.request.resource_type in BLOCKED:
|
||||
route.abort("blockedbyclient")
|
||||
else:
|
||||
route.continue_()
|
||||
except Exception as e:
|
||||
if "Cannot find request" not in str(e) and "Target" not in str(e):
|
||||
raise
|
||||
ANSWER_ERRORS.append(str(e)[:120])
|
||||
return route
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", sorted(EXTRA))
|
||||
def test_networkidle_arrives_on_a_routed_page_through_a_served_browser(firefox_binary, site, kind):
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright # a stock client, as production uses
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
ANSWER_ERRORS.clear()
|
||||
ctx.route("**/*", _router(SLOW_MS.get(kind, 0) / 1000.0))
|
||||
page = ctx.new_page()
|
||||
for attempt in range(3): # fresh pages, the way a client fetches one address after another
|
||||
t0 = time.monotonic()
|
||||
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=20000)
|
||||
took = time.monotonic() - t0
|
||||
assert took < 15, "networkidle after %.1f s on attempt %d (answers to a closed request: %s)" % (
|
||||
took, attempt, ANSWER_ERRORS[:3])
|
||||
assert page.evaluate("window.__app") == 1
|
||||
assert ("POST", "/beacon") in _Handler.hits, _Handler.hits
|
||||
assert not any(path in ("/font.woff2", "/pixel.png", "/photo.jpg", "/ad.png") for _, path in _Handler.hits), _Handler.hits
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["many", "cancel_fetch", "cancel_img", "cancel_iframe", "cancel_navigation"])
|
||||
def test_networkidle_arrives_when_the_client_answers_all_requests_concurrently_and_slowly(firefox_binary, site, kind):
|
||||
"""An async client (the way a Go client answers: every route handler in its own task) that takes 300 ms to decide, so the
|
||||
page cancels, replaces or removes a request while its answer is still on the way."""
|
||||
import asyncio
|
||||
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
async_playwright = _stock_client("playwright.async_api").async_playwright
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
errors = []
|
||||
|
||||
async def run():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.firefox.connect(server.ws_endpoint)
|
||||
ctx = await browser.new_context()
|
||||
|
||||
async def route(r):
|
||||
await asyncio.sleep(0.3)
|
||||
try:
|
||||
if r.request.resource_type in BLOCKED:
|
||||
await r.abort("blockedbyclient")
|
||||
else:
|
||||
await r.continue_()
|
||||
except Exception as e:
|
||||
errors.append(str(e)[:140])
|
||||
|
||||
await ctx.route("**/*", route)
|
||||
page = await ctx.new_page()
|
||||
for attempt in range(3):
|
||||
t0 = time.monotonic()
|
||||
await page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
|
||||
assert time.monotonic() - t0 < 20, "networkidle after %.1f s on attempt %d" % (time.monotonic() - t0, attempt)
|
||||
await ctx.close()
|
||||
await browser.close()
|
||||
|
||||
try:
|
||||
asyncio.run(run())
|
||||
finally:
|
||||
server.close()
|
||||
# an answer to a request the browser had already closed is allowed to fail, but it must not leave the page waiting
|
||||
print("answers to a closed request:", errors[:3])
|
||||
|
||||
|
||||
def test_one_page_reused_for_many_addresses_reaches_networkidle_every_time(firefox_binary, site):
|
||||
"""tf-fetch's shape: ONE page for dozens of fetches. A request whose end never reaches the client (a beacon the
|
||||
page closes with its document, a request the browser cancelled while the route was deciding) must not hold the
|
||||
addresses that follow: the lifecycle's memory of requests in flight is per document, keyed by request id."""
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
ctx.route("**/*", _router(0.05))
|
||||
page = ctx.new_page()
|
||||
kinds = ["cancel_fetch", "cancel_img", "cancel_iframe", "beacon", "cancel_navigation", "oop_iframe"] * 2
|
||||
for n, kind in enumerate(kinds):
|
||||
t0 = time.monotonic()
|
||||
page.goto(site + "?kind=%s&n=%d" % (kind, n), wait_until="networkidle", timeout=20000)
|
||||
assert time.monotonic() - t0 < 15, "address %d (%s) reached networkidle after %.1f s" % (n, kind, time.monotonic() - t0)
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["cancel_fetch", "cancel_img", "cancel_iframe"])
|
||||
def test_a_plain_route_handler_is_not_poisoned_by_a_request_the_page_cancelled(firefox_binary, site, kind):
|
||||
"""The handler of a tf-fetch-like client is a plain function: continue_ or abort, no try. The page cancels requests
|
||||
while the (slow) route is deciding; the browser has already closed them, and the engine answers the late command with
|
||||
`Cannot find request`. Stock Playwright's server sends those commands as may-fail and tells the client nothing; ours
|
||||
passed the error up, the client kept it as the error of the connection and raised it on the NEXT route command, which
|
||||
was then never sent: the request stayed held in the engine, its handler failed too, and so on down the page (measured
|
||||
on a real news page: six held requests in a row, one a beacon, and networkidle never)."""
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
|
||||
def plain(route): # no try: the way a client is written
|
||||
time.sleep(0.12)
|
||||
if route.request.resource_type in BLOCKED:
|
||||
route.abort("blockedbyclient")
|
||||
else:
|
||||
route.continue_()
|
||||
|
||||
ctx.route("**/*", plain)
|
||||
page = ctx.new_page()
|
||||
for attempt in range(3):
|
||||
t0 = time.monotonic()
|
||||
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
|
||||
assert time.monotonic() - t0 < 20, "attempt %d: networkidle after %.1f s" % (attempt, time.monotonic() - t0)
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
@@ -230,13 +230,24 @@ class _Page:
|
||||
"""The `PageDispatcher` seen from the numbering: what it was given."""
|
||||
|
||||
def __init__(self, server, context, session, target_id, number,
|
||||
opener=None):
|
||||
opener=None, is_gone=None):
|
||||
self.target_id = target_id
|
||||
self.number = number
|
||||
self.opener = opener
|
||||
self.popups_opened = 0
|
||||
self.channel = {"guid": "page-" + target_id}
|
||||
|
||||
gone_while_building = False
|
||||
|
||||
def wait_until_ready(self, timeout=20.0):
|
||||
pass # the engine of this test says Page.ready at once
|
||||
|
||||
def settle_events(self):
|
||||
pass
|
||||
|
||||
def announce(self, context, replay):
|
||||
context.emit("page", {"page": self.channel})
|
||||
|
||||
def announce_closed(self):
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"""What a popup does depends on what its destination answers; the client must see what stock Firefox makes it see.
|
||||
|
||||
Reference: Playwright 1.62 with its own Firefox, measured (a `window.open(url)` from a click, and a clicked
|
||||
`<a target=_blank>`, destination on the opener's site, two repetitions each, 30 s observed unless said; the destination on
|
||||
another site gave the same):
|
||||
|
||||
* 204 No Content: NO `page` event at all (observed for 30 s). The popup is never announced.
|
||||
* a destination that never answers: NO `page` event (observed for 30 s).
|
||||
* a destination that answers a normal HTML page after N seconds: the `page` event arrives when the answer comes, N s after
|
||||
the click, with the destination as its url, and the load follows at once. There is no ceiling: with N = 25 the event
|
||||
came at about 25 s (checked by hand, the 25 s case is not run here; this file uses 4 s).
|
||||
* `Content-Disposition: attachment`: the `page` event arrives at once (url empty), a `download` event arrives on the
|
||||
OPENER (not on the popup) and the popup closes within about 10 ms.
|
||||
|
||||
Why it matters here: the page dispatcher announces a popup when the engine says it is ready (`Page.ready`), and gives up on
|
||||
one that never does after 20 s. A destination that answers late must still be announced when it answers, one that never
|
||||
becomes a page must not be announced, and a download started by a popup must reach the client on the opener like on stock.
|
||||
The waits for "no event" are bounded to 8 s here (stock was observed for 30 s).
|
||||
|
||||
Transports: the client of this wheel in the same process, and the stock Playwright client over `launch_server`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from test_popups_reach_the_client_e2e import browser # noqa: F401 (the two-transport fixture of the sibling file)
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SLOW_SECONDS = 4
|
||||
NO_EVENT_SECONDS = 8
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def _send(self, code, ctype, body=b"", extra=()):
|
||||
self.send_response(code)
|
||||
if ctype:
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
for key, value in extra:
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
port = self.server.server_address[1]
|
||||
try:
|
||||
if self.path.startswith("/main"):
|
||||
body = ""
|
||||
for d in "1234":
|
||||
url = "http://127.0.0.1:%d/d%s" % (port, d)
|
||||
body += ("<a id=link%s target=_blank href='%s'>a</a> "
|
||||
"<button id=open%s onclick=\"window.open('%s')\">w</button><br>") % (d, url, d, url)
|
||||
self._send(200, "text/html", ("<!doctype html><title>opener</title>" + body).encode())
|
||||
elif self.path.startswith("/d1"):
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
elif self.path.startswith("/d2"):
|
||||
time.sleep(SLOW_SECONDS)
|
||||
self._send(200, "text/html", b"<!doctype html><title>slow</title><p>slow page</p>")
|
||||
elif self.path.startswith("/d3"):
|
||||
time.sleep(NO_EVENT_SECONDS + 6) # longer than any wait of a test: it never answers in time
|
||||
self._send(200, "text/html", b"<!doctype html><title>late</title>")
|
||||
elif self.path.startswith("/d4"):
|
||||
self._send(200, "text/plain", b"hello attachment\n",
|
||||
[("Content-Disposition", 'attachment; filename="a.txt"')])
|
||||
else:
|
||||
self._send(404, "text/plain", b"not found")
|
||||
except (ConnectionError, TimeoutError, OSError):
|
||||
self.close_connection = True
|
||||
|
||||
|
||||
class _Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
srv = _Server(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield srv.server_address[1]
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
class _Run:
|
||||
"""One popup attempt: the opener page, what the context announced, what the opener downloaded."""
|
||||
|
||||
def __init__(self, launched, port, how, dest):
|
||||
self.context = launched.new_context(accept_downloads=True)
|
||||
self.opener = self.context.new_page()
|
||||
self.popups, self.downloads, self.arrived_at = [], [], None
|
||||
self.context.on("page", self._on_page)
|
||||
self.opener.on("download", lambda download: self.downloads.append(download))
|
||||
self.opener.goto("http://127.0.0.1:%d/main" % port)
|
||||
self.clicked = time.time()
|
||||
self.opener.click("#%s%s" % (how, dest))
|
||||
|
||||
def _on_page(self, page):
|
||||
self.popups.append(page)
|
||||
self.arrived_at = time.time() - self.clicked
|
||||
|
||||
def wait_until(self, predicate, seconds):
|
||||
end = time.time() + seconds
|
||||
while time.time() < end and not predicate():
|
||||
self.opener.wait_for_timeout(100) # the sync client reads the engine's events inside its calls
|
||||
return predicate()
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.context.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_a_204_is_never_announced(browser, site, how): # noqa: F811
|
||||
run = _Run(browser, site, how, "1")
|
||||
try:
|
||||
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
|
||||
"a 204 destination was announced as a page after %.1fs (stock gives no page event)" % run.arrived_at
|
||||
assert len(run.context.pages) == 1
|
||||
finally:
|
||||
run.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_a_server_that_never_answers_is_never_announced(browser, site, how): # noqa: F811
|
||||
run = _Run(browser, site, how, "3")
|
||||
try:
|
||||
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
|
||||
"an unanswered destination was announced as a page after %.1fs (stock gives no page event)" % run.arrived_at
|
||||
assert len(run.context.pages) == 1
|
||||
finally:
|
||||
run.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_a_slow_page_is_announced_when_it_answers(browser, site, how): # noqa: F811
|
||||
run = _Run(browser, site, how, "2")
|
||||
try:
|
||||
assert run.wait_until(lambda: run.popups, SLOW_SECONDS + 6), "the slow popup never arrived"
|
||||
assert run.arrived_at >= SLOW_SECONDS - 0.5, "announced after %.1fs, before the page answered" % run.arrived_at
|
||||
popup = run.popups[0]
|
||||
popup.wait_for_load_state("load", timeout=10000)
|
||||
assert popup.url == "http://127.0.0.1:%d/d2" % site
|
||||
assert popup.evaluate("document.title") == "slow"
|
||||
assert len(run.context.pages) == 2
|
||||
finally:
|
||||
run.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_an_attachment_reports_the_download_on_the_opener_and_closes(browser, site, how): # noqa: F811
|
||||
run = _Run(browser, site, how, "4")
|
||||
try:
|
||||
assert run.wait_until(lambda: run.downloads, 10), "no `download` event on the opener (stock gives one)"
|
||||
assert run.downloads[0].suggested_filename == "a.txt"
|
||||
assert run.popups, "stock announces the popup (its url is empty) before it closes"
|
||||
assert run.wait_until(lambda: run.popups[0].is_closed(), 10), "the popup of a download stays open"
|
||||
assert len(run.context.pages) == 1
|
||||
finally:
|
||||
run.close()
|
||||
@@ -0,0 +1,186 @@
|
||||
"""A popup reaches the client: the `page` event arrives, the new page is at its address and answers.
|
||||
|
||||
Why this file exists: the page dispatcher once waited for the engine's ready signal (`Page.ready`) before it handed a new
|
||||
page over. A popup whose first request goes through a context route (the shape of every production client: abort the
|
||||
images, continue the rest) was held behind a page that did not exist yet, the engine never said ready for it, the wait gave
|
||||
up after 20 s and the popup vanished: the client never got the `page` event. That was found by a user journey (a
|
||||
`target=_blank` link) and it is the same for a link and for `window.open`, to the page's own site and to another one.
|
||||
|
||||
The matrix: four ways to open a popup (a `target=_blank` link, the same link with `rel=noopener`, `window.open(url)` from a
|
||||
click, `window.open(url, '_blank', 'noopener')`) x the target on the opener's site (`127.0.0.1`) or on another site
|
||||
(`localhost`: another site for the engine, no pref needed) x with and without a context route x two transports: the client
|
||||
of this wheel in the same process, and the stock Playwright client over `launch_server` (the way the fake web does it).
|
||||
Each case: the `page` event arrives within 10 s, the page ends at the target address, answers an `evaluate`, and has an
|
||||
opener (`page.opener()`). Stock Firefox (Playwright 1.62) gives an opener in all four kinds, `noopener` included, so this is
|
||||
asserted for all four; if the engine ever returns None for a noopener kind the test says so.
|
||||
|
||||
One extra case proves that the other-site target is really in another process, so that the matrix cannot quietly become a
|
||||
same-site test: opening it adds a content process below the test; the same-site target does not.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
OWN, OTHER = "127.0.0.1", "localhost"
|
||||
KINDS = {
|
||||
"a-blank": "a1",
|
||||
"a-noopener": "a2",
|
||||
"open": "w1",
|
||||
"open-noopener": "w2",
|
||||
}
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
port = self.server.server_address[1]
|
||||
if self.path.startswith("/main"):
|
||||
body = ""
|
||||
for tag, host in (("s", OWN), ("o", OTHER)):
|
||||
url = "http://%s:%d/p" % (host, port)
|
||||
body += (
|
||||
"<a id=a1%s target=_blank href='%s'>a</a> "
|
||||
"<a id=a2%s target=_blank rel=noopener href='%s'>a</a> "
|
||||
"<button id=w1%s onclick=\"window.open('%s')\">w</button> "
|
||||
"<button id=w2%s onclick=\"window.open('%s','_blank','noopener')\">w</button><br>"
|
||||
) % (tag, url, tag, url, tag, url, tag, url)
|
||||
else:
|
||||
body = "<p>popup</p>"
|
||||
data = ("<!doctype html><title>t</title>" + body).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield srv.server_address[1]
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["in-process", "stock-client"])
|
||||
def browser(request, firefox_binary):
|
||||
"""One browser per transport for the whole file."""
|
||||
if request.param == "in-process":
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(binary_path=firefox_binary, headless=True) as b:
|
||||
yield b
|
||||
return
|
||||
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
|
||||
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
|
||||
except ImportError as exc:
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
b = p.firefox.connect(server.ws_endpoint)
|
||||
try:
|
||||
yield b
|
||||
finally:
|
||||
b.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def _route(context):
|
||||
context.route("**/*", lambda route: route.abort() if route.request.resource_type in ("image", "media")
|
||||
else route.continue_())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routed", [False, True], ids=["no-route", "route"])
|
||||
@pytest.mark.parametrize("target", ["same-site", "other-site"])
|
||||
@pytest.mark.parametrize("kind", sorted(KINDS))
|
||||
def test_a_popup_reaches_the_client(browser, site, kind, target, routed):
|
||||
host, tag = (OWN, "s") if target == "same-site" else (OTHER, "o")
|
||||
context = browser.new_context()
|
||||
try:
|
||||
if routed:
|
||||
_route(context)
|
||||
page = context.new_page()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
t0 = time.time()
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#%s%s" % (KINDS[kind], tag))
|
||||
popup = info.value
|
||||
arrived = time.time() - t0
|
||||
popup.wait_for_load_state("load", timeout=10000)
|
||||
assert popup.url == "http://%s:%d/p" % (host, site), "the popup is at %s" % popup.url
|
||||
assert popup.evaluate("document.title") == "t"
|
||||
assert popup.opener() is not None, "no opener (stock Firefox gives one for every kind)"
|
||||
assert arrived < 10
|
||||
finally:
|
||||
context.close()
|
||||
|
||||
|
||||
def _content_processes(engine_dir):
|
||||
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
|
||||
import psutil
|
||||
|
||||
pids = set()
|
||||
for child in psutil.Process(os.getpid()).children(recursive=True):
|
||||
try:
|
||||
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
|
||||
continue
|
||||
cmd = child.cmdline()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in cmd and cmd[-1] == "tab":
|
||||
pids.add(child.pid)
|
||||
return pids
|
||||
|
||||
|
||||
def _quiet(engine_dir, seconds=3.0, limit=30.0):
|
||||
"""The set of content processes once it has not changed for `seconds` (the engine keeps a spare one)."""
|
||||
end = time.time() + limit
|
||||
last, since = _content_processes(engine_dir), time.time()
|
||||
while time.time() < end:
|
||||
time.sleep(0.25)
|
||||
now = _content_processes(engine_dir)
|
||||
if now != last:
|
||||
last, since = now, time.time()
|
||||
elif time.time() - since >= seconds:
|
||||
break
|
||||
return last
|
||||
|
||||
|
||||
def test_the_other_site_popup_runs_in_another_process(browser, firefox_binary, site):
|
||||
"""The control of the matrix above: the popup to `localhost` adds a content process, the one to `127.0.0.1` does not."""
|
||||
engine_dir = str(Path(firefox_binary).resolve().parent)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
before = _quiet(engine_dir)
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#a1s")
|
||||
info.value.wait_for_load_state("load")
|
||||
same = _quiet(engine_dir)
|
||||
info.value.close()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
base = _quiet(engine_dir)
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#a1o")
|
||||
info.value.wait_for_load_state("load")
|
||||
other = _quiet(engine_dir)
|
||||
assert not (same - before), "a popup to the opener's own site started a process: %s" % sorted(same - before)
|
||||
assert len(other - base) >= 1, "the other-site popup added no content process: %s -> %s" % (
|
||||
sorted(base), sorted(other))
|
||||
@@ -0,0 +1,120 @@
|
||||
"""A route whose request the page has already abandoned is answered quietly.
|
||||
|
||||
Found and first fixed by richardpowellus (invisible_playwright #351); the test is his, adapted to the fix that swallows only
|
||||
"Cannot find request" and a closed target (the same `RouteDispatcher._send`).
|
||||
|
||||
The known-bad input, measured on 2026-10-14 with
|
||||
`page.route("**/*", lambda r: r.continue_())` and sixty sequential
|
||||
`page.goto(url, wait_until="load")` calls on a loopback page: 4-12 of them
|
||||
failed. Every failing `continue_` was the previous document's `/favicon.ico`,
|
||||
whose channel the next navigation had aborted while the route sat with the
|
||||
handler. The engine answered `Network.resumeInterceptedRequest` with
|
||||
NS_BINDING_ABORTED, the server raised it, and it came out of the caller's NEXT
|
||||
call (`Page.goto: Route.continue_: ...`, `Page.evaluate: Route.continue_: ...`)
|
||||
or left that goto waiting for a load that never came.
|
||||
|
||||
Playwright's own Firefox server sends all three interception answers with
|
||||
`sendMayFail`: a request that is gone has nothing left to answer.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import socket
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
PAGE = b"<!doctype html><html><body><form><textarea></textarea></form></body></html>"
|
||||
HELD = b"<!doctype html><html><body><img src='/held.png'></body></html>"
|
||||
|
||||
|
||||
def _serve():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
body = HELD if self.path.startswith("/held") and \
|
||||
not self.path.endswith(".png") else PAGE
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv, "http://127.0.0.1:%d" % port
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("answer", ["continue_", "fulfill", "abort"])
|
||||
def test_answering_a_route_the_next_navigation_aborted_does_not_raise(
|
||||
firefox_binary, answer):
|
||||
"""The image of a page the caller has navigated away from is still held
|
||||
by the handler; answering it afterwards neither raises nor poisons the
|
||||
caller's next call."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv, base = _serve()
|
||||
held = []
|
||||
|
||||
def handler(route):
|
||||
if route.request.url.endswith("/held.png"):
|
||||
held.append(route)
|
||||
else:
|
||||
route.continue_()
|
||||
|
||||
try:
|
||||
with InvisiblePlaywright(seed=4243, binary_path=firefox_binary,
|
||||
headless=True) as b:
|
||||
page = b.new_context().new_page()
|
||||
page.route("**/*", handler)
|
||||
page.goto(base + "/held", wait_until="commit", timeout=15000)
|
||||
for _ in range(100):
|
||||
if held:
|
||||
break
|
||||
page.wait_for_timeout(50)
|
||||
assert held, "the page's image never reached the handler"
|
||||
|
||||
page.goto(base + "/next", wait_until="load", timeout=15000)
|
||||
|
||||
route = held[0]
|
||||
if answer == "fulfill":
|
||||
route.fulfill(status=200, body="")
|
||||
else:
|
||||
getattr(route, answer)()
|
||||
assert page.evaluate("1 + 1") == 2
|
||||
assert page.url == base + "/next"
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_sequential_routed_gotos_neither_hang_nor_raise(firefox_binary):
|
||||
"""The measured case: every routed goto's favicon is still being
|
||||
continued when the next goto aborts it."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv, base = _serve()
|
||||
failures = []
|
||||
try:
|
||||
with InvisiblePlaywright(seed=4243, binary_path=firefox_binary,
|
||||
headless=True) as b:
|
||||
page = b.new_context().new_page()
|
||||
page.route("**/*", lambda r: r.continue_())
|
||||
for i in range(40):
|
||||
try:
|
||||
page.goto(f"{base}/p?{i % 2}", wait_until="load",
|
||||
timeout=8000)
|
||||
page.evaluate("1")
|
||||
except Exception as e: # noqa: BLE001 - the failure is the finding
|
||||
failures.append((i, type(e).__name__, str(e)[:200]))
|
||||
finally:
|
||||
srv.shutdown()
|
||||
assert not failures, failures
|
||||
@@ -0,0 +1,65 @@
|
||||
"""The e2e tests that count processes count the ones that host a site, not every new content process. No browser.
|
||||
|
||||
The engine keeps preallocated content processes and starts one to refill the pool after it hands one to a site,
|
||||
whenever it gets to it. The bench counted every `-contentproc ... tab` pid, so a refill that landed between its
|
||||
two reads was "a process the same-site frame started" (test_same_site_other_port_stays_in_process, red on the
|
||||
e2e of the commit of 0.50.0: `[13443]`). The processes below are the ones measured on firefox-62 (Linux):
|
||||
names and command lines as /proc gives them.
|
||||
"""
|
||||
import _processes
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ENGINE = "/cache/firefox-62/firefox"
|
||||
DIR = "/cache/firefox-62"
|
||||
|
||||
|
||||
class _Proc:
|
||||
def __init__(self, pid, name, kind, exe=ENGINE):
|
||||
self.pid, self._name, self._exe = pid, name, exe
|
||||
self._cmd = [exe, "-contentproc", "-isForBrowser", "-prefsLen", "1", "-parentBuildID", "20261111073531",
|
||||
"-appDir", DIR + "/browser", str(pid), kind]
|
||||
|
||||
def exe(self):
|
||||
return self._exe
|
||||
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
def cmdline(self):
|
||||
return self._cmd
|
||||
|
||||
|
||||
def _engine_at_plain():
|
||||
"""a.test/plain shown: one process for the site, three preallocated, and the engine's other children."""
|
||||
return [_Proc(184, "Socket Process", "socket"), _Proc(200, "WebExtensions", "tab"),
|
||||
_Proc(334, "Isolated Web Co", "tab"), _Proc(377, "Privileged Cont", "tab"),
|
||||
_Proc(433, "Web Content", "tab"), _Proc(438, "Web Content", "tab"), _Proc(460, "Web Content", "tab")]
|
||||
|
||||
|
||||
def test_a_preallocated_process_that_arrives_is_not_a_site():
|
||||
before = _processes.site_pids(_engine_at_plain(), DIR)
|
||||
after = _processes.site_pids(_engine_at_plain() + [_Proc(549, "Web Content", "tab")], DIR)
|
||||
assert before == after == {334}
|
||||
|
||||
|
||||
def test_a_preallocated_process_given_to_a_site_is_a_new_site_process():
|
||||
"""A cross-site frame: 433 leaves the pool for b.test (and is renamed), 549 refills the pool."""
|
||||
procs = [p for p in _engine_at_plain() if p.pid != 433]
|
||||
procs += [_Proc(433, "Isolated Web Co", "tab"), _Proc(549, "Web Content", "tab")]
|
||||
assert _processes.site_pids(procs, DIR) - _processes.site_pids(_engine_at_plain(), DIR) == {433}
|
||||
|
||||
|
||||
def test_a_process_of_another_firefox_is_not_counted():
|
||||
other = _Proc(900, "Isolated Web Co", "tab", exe="/usr/lib/firefox/firefox")
|
||||
assert _processes.site_pids(_engine_at_plain() + [other], DIR) == {334}
|
||||
|
||||
|
||||
def test_the_pool_refilled_behind_a_closed_context_is_not_a_process_left():
|
||||
"""After the fourth closed context of test_a_context_that_ends_leaves_no_process_e2e, as measured: three
|
||||
preallocated processes and no site. Counting every content process said 5 ([2, 2, 2, 5, 5])."""
|
||||
left = [_Proc(1219, "WebExtensions", "tab"), _Proc(1382, "Privileged Cont", "tab"),
|
||||
_Proc(1739, "Web Content", "tab"), _Proc(1744, "Web Content", "tab"), _Proc(1821, "Web Content", "tab")]
|
||||
assert _processes.site_pids(left) == set()
|
||||
assert _processes.site_pids(left + [_Proc(1900, "Isolated Web Co", "tab")]) == {1900}
|
||||
Reference in new issue
Block a user