Compare commits
261
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bc1ffa718 | ||
|
|
e84e17042c | ||
|
|
0f7f21baf5 | ||
|
|
3aa3b52385 | ||
|
|
d4f43cd05a | ||
|
|
6b1712ee9e | ||
|
|
14f96ff6b2 | ||
|
|
4eed1e9039 | ||
|
|
6ccf126bd0 | ||
|
|
b3c86ee051 | ||
|
|
af8ad55cda | ||
|
|
e7c64166ad | ||
|
|
b0fe8c9c51 | ||
|
|
ae7c869aeb | ||
|
|
f670c41672 | ||
|
|
76de860c31 | ||
|
|
e200968886 | ||
|
|
b04c50b0a9 | ||
|
|
481d97fcc2 | ||
|
|
6f02a21978 | ||
|
|
9e04f2cbd8 | ||
|
|
5807de97af | ||
|
|
6c298fcd41 | ||
|
|
5c94b0d281 | ||
|
|
7d8186fe6a | ||
|
|
3aff03c7cc | ||
|
|
4f510bfba0 | ||
|
|
425cf8319a | ||
|
|
b26b67494c | ||
|
|
7a572baf95 | ||
|
|
0328b23673 | ||
|
|
39b303923a | ||
|
|
e270bc7b4a | ||
|
|
fec3c9533c | ||
|
|
dae1d2c870 | ||
|
|
324246b343 | ||
|
|
1fda08f380 | ||
|
|
4d930e21c0 | ||
|
|
7ab22b0961 | ||
|
|
27b884ae87 | ||
|
|
279ff286c5 | ||
|
|
7d3dbfbf1c | ||
|
|
bab3a2b9d5 | ||
|
|
5dd2b21c67 | ||
|
|
eff2eb267a | ||
|
|
d154675deb | ||
|
|
518a65ed1a | ||
|
|
25c83d1570 | ||
|
|
b27a6fdf5b | ||
|
|
e8990bd58a | ||
|
|
118d013306 | ||
|
|
4f1a5feb17 | ||
|
|
dd4c623d2c | ||
|
|
c8554e9879 | ||
|
|
371c22957e | ||
|
|
c595296fc9 | ||
|
|
9579798b08 | ||
|
|
626532c3b9 | ||
|
|
8f2ea98928 | ||
|
|
3b13957547 | ||
|
|
717af6bcee | ||
|
|
30ee9e597c | ||
|
|
638c92af8a | ||
|
|
bee98fde71 | ||
|
|
fe04f3c206 | ||
|
|
27b3c7f2a7 | ||
|
|
ef3ba1c862 | ||
|
|
968e1533dd | ||
|
|
0e05823035 | ||
|
|
56b097fb8b | ||
|
|
f76363b1dd | ||
|
|
06f9fd4b5e | ||
|
|
274fdc2812 | ||
|
|
4a5a303d32 | ||
|
|
93911c52a3 | ||
|
|
ddc98493a2 | ||
|
|
e3f57b536f | ||
|
|
6b64ae5379 | ||
|
|
2017bd40b5 | ||
|
|
8599018164 | ||
|
|
450ff5a235 | ||
|
|
185d907ca7 | ||
|
|
71bd84b682 | ||
|
|
7a44cddede | ||
|
|
4c402557a4 | ||
|
|
50dc88522d | ||
|
|
f299dece11 | ||
|
|
6b94fbc1d0 | ||
|
|
5f44e8ff31 | ||
|
|
a6182819d7 | ||
|
|
809e7e32a0 | ||
|
|
4b439d4f8d | ||
|
|
1d417f6b3c | ||
|
|
fb7c4f49fd | ||
|
|
96fcd28e6d | ||
|
|
e1d4bf423f | ||
|
|
610b33834f | ||
|
|
ab15976bee | ||
|
|
22dfa2ba82 | ||
|
|
4ace173f0f | ||
|
|
a9ea8ed2df | ||
|
|
1c7adcbc4c | ||
|
|
f9dd033c87 | ||
|
|
9ee819b796 | ||
|
|
c6573986a1 | ||
|
|
b0824a3160 | ||
|
|
5f5222d754 | ||
|
|
763e086e4f | ||
|
|
95ad3c0e28 | ||
|
|
840a42ac6f | ||
|
|
70d9472d2d | ||
|
|
cc7597314c | ||
|
|
ea76d25ded | ||
|
|
2e230e7d36 | ||
|
|
873104fd8d | ||
|
|
32bd517d76 | ||
|
|
c41d60bcbb | ||
|
|
c1eb4879a0 | ||
|
|
8b0749ab02 | ||
|
|
68bb3220e6 | ||
|
|
0544eaa845 | ||
|
|
6f547766c4 | ||
|
|
e030714570 | ||
|
|
653f90c969 | ||
|
|
2801b94897 | ||
|
|
0f48b9e40e | ||
|
|
3c102d052a | ||
|
|
b7b2157d03 | ||
|
|
aceda29a40 | ||
|
|
4f767c19b8 | ||
|
|
394e0247a3 | ||
|
|
2c6b25ee08 | ||
|
|
1a3c80d660 | ||
|
|
4eda90b8a4 | ||
|
|
45fbe84b9f | ||
|
|
b579588a53 | ||
|
|
25c6ee06f6 | ||
|
|
86ea12a9bb | ||
|
|
bcee6f8966 | ||
|
|
e06ef0471e | ||
|
|
0cc57a56b7 | ||
|
|
aed3ef6858 | ||
|
|
7f6bc9c839 | ||
|
|
95b8cd93de | ||
|
|
287e5ae64c | ||
|
|
9aa734ba54 | ||
|
|
258a803f11 | ||
|
|
23eee4a1db | ||
|
|
c3b287fd8c | ||
|
|
e1aa41fbc8 | ||
|
|
038a90f945 | ||
|
|
1dc5ea2a3f | ||
|
|
dbd490f023 | ||
|
|
db0579faa9 | ||
|
|
0bbc3d1269 | ||
|
|
4385d5cfe9 | ||
|
|
85e0084a35 | ||
|
|
0a96b63b13 | ||
|
|
853e24e31b | ||
|
|
3084365415 | ||
|
|
dfb7507d58 | ||
|
|
5fa2cf4e84 | ||
|
|
ed5a26debf | ||
|
|
4da1d6204d | ||
|
|
d81c23ee83 | ||
|
|
6576bc18ad | ||
|
|
12ec4bb086 | ||
|
|
20dfb09179 | ||
|
|
c42977b108 | ||
|
|
61fb9fb901 | ||
|
|
719b632fc2 | ||
|
|
f953f575d5 | ||
|
|
a6eac7776f | ||
|
|
22843d256c | ||
|
|
7d7639da93 | ||
|
|
8cc5164019 | ||
|
|
f92d9f84f2 | ||
|
|
2901769330 | ||
|
|
edb63b670d | ||
|
|
4bb5b57ad7 | ||
|
|
c206d5981a | ||
|
|
8f5869d11a | ||
|
|
e8fbc9171a | ||
|
|
73f85763b2 | ||
|
|
4fe36b40ab | ||
|
|
f6aee7f595 | ||
|
|
6fc18b3d09 | ||
|
|
10c54bc1fc | ||
|
|
e11d7d0699 | ||
|
|
e42c1b1788 | ||
|
|
49fd6fc7c1 | ||
|
|
b6405aed5c | ||
|
|
bccaba8b8e | ||
|
|
584e7b4ef2 | ||
|
|
7477275f43 | ||
|
|
5dc9a8d0d8 | ||
|
|
106658e3b7 | ||
|
|
6a3b564e29 | ||
|
|
5f1d9526ec | ||
|
|
3e6ac4462c | ||
|
|
dc0bf4dcd3 | ||
|
|
deace90f7a | ||
|
|
d5ae243725 | ||
|
|
a82d3e40d7 | ||
|
|
0388d00f45 | ||
|
|
beca4a5856 | ||
|
|
b685183552 | ||
|
|
9878cad989 | ||
|
|
cebb7f8cb0 | ||
|
|
4aecaf0043 | ||
|
|
c09cf08c17 | ||
|
|
b9c9139695 | ||
|
|
52bffd7fe3 | ||
|
|
270e7a799d | ||
|
|
dd4e9b5d95 | ||
|
|
5c1f6a5cc4 | ||
|
|
57cfc78bb0 | ||
|
|
b763a8320c | ||
|
|
6a53aa2182 | ||
|
|
e384f731ac | ||
|
|
edab7112f6 | ||
|
|
91bccd23fa | ||
|
|
e82320fd52 | ||
|
|
b1091c9ebb | ||
|
|
7bb5ae076e | ||
|
|
36da827fa3 | ||
|
|
1dbf33ac0a | ||
|
|
6c73012fd4 | ||
|
|
4a6317ec41 | ||
|
|
e8ffdf8a2a | ||
|
|
08b32a8004 | ||
|
|
b231f61c4c | ||
|
|
cec6e28767 | ||
|
|
50dd052f4a | ||
|
|
9f2c21662e | ||
|
|
26e4fe6b1c | ||
|
|
c3bca774b6 | ||
|
|
7b8f1e70b2 | ||
|
|
1d3d149cb6 | ||
|
|
5ee935268a | ||
|
|
4416b088d7 | ||
|
|
8516470e95 | ||
|
|
f0c60c0f0c | ||
|
|
5994a6cfd8 | ||
|
|
e7f1c85225 | ||
|
|
5d3ac3bc7c | ||
|
|
39128592a4 | ||
|
|
a973088192 | ||
|
|
b2d424925a | ||
|
|
c489db7937 | ||
|
|
0706164f58 | ||
|
|
a09233152c | ||
|
|
7cd92712ab | ||
|
|
2be9b6046a | ||
|
|
c43d787ce9 | ||
|
|
f094102fab | ||
|
|
578763389d | ||
|
|
3a97b05708 | ||
|
|
5fda215266 | ||
|
|
b3eb6c3733 | ||
|
|
1d7204ffe6 |
No files matched your search
@@ -111,7 +111,14 @@ jobs:
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb
|
||||
# the fontconfig e2e trace the opens of the browser: strace is not in the runner image (setsid is, util-linux)
|
||||
sudo apt-get install -y strace
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
# The preloaded-intermediates list is a file of the repository (ci/intermediates.json, empty, the sha256 in ci/intermediates.pin.json): with
|
||||
# STEALTHFOX_INTERMEDIATES set the core neither downloads nor checks Mozilla's. BEFORE `fetch`, which makes the list present (it would download it).
|
||||
- name: The intermediates list (a fixed file of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_intermediates.py set --pin ci/intermediates.pin.json
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The protocol mirror agrees with the engine it is pinned to
|
||||
@@ -131,6 +138,8 @@ jobs:
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
|
||||
# test_release_e2e.py and test_upgrade_e2e.py (pip, uv, PyPI, the GitHub release) are NOT in this run or in the Windows legs below: tests/conftest.py leaves
|
||||
# them out of every run that does not name their file, and user-install.yml (the round after the publication) names it. tests/_post_publication.py.
|
||||
- name: Run the full e2e suite under a virtual display, without the root ones
|
||||
# PYTHONUNBUFFERED, and it is not a nicety. Without it Python block-buffers
|
||||
# stdout when it is a pipe, and this step printed NOTHING for 39 minutes
|
||||
@@ -272,6 +281,32 @@ jobs:
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# The junit of every pass of the run (scripts/run_e2e.py writes one per pass, e2e-junit-*.xml, in the directory of the watchdog file) and of the two
|
||||
# steps above that run alone (root, sandbox): what a red is read from, kept whether the run is green or red.
|
||||
- name: Upload the junit of the run
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: e2e-junit-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
${{ runner.temp }}/e2e-junit-*.xml
|
||||
${{ runner.temp }}/root-e2e.xml
|
||||
${{ runner.temp }}/sandbox-e2e.xml
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# What the tests that measure save for a reader (the boxes of tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py:
|
||||
# the two PNG files, the screenshot and a result.json per case), under RUNNER_TEMP/invpw-evidence, whether the run is green or red. Nothing there
|
||||
# when no such test ran (an engine older than firefox-66 skips it), which is not a warning.
|
||||
- name: Upload what the tests saved
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: invpw-evidence-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: ${{ runner.temp }}/invpw-evidence
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
# ``Control+A`` selects all in a field, on the PUBLISHED engine and the core this package pins, on Windows, where the keyboard of a real
|
||||
# user is: the shortcut letter used to reach the browser as Control+Shift+A (invisible-core 63.66.0 fixes it). The e2e is red on the
|
||||
# keyboard that held Shift for the capital A (tests/test_control_a_selects_all_in_a_field_e2e.py: 5 ways to press it x an <input> and a
|
||||
@@ -296,6 +331,11 @@ jobs:
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
# The intermediates list of the repository (ci/intermediates.json, empty): with STEALTHFOX_INTERMEDIATES set the core asks Mozilla for nothing.
|
||||
# BEFORE `fetch`, which makes the list present (it would download it).
|
||||
- name: The intermediates list (a fixed file of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_intermediates.py set --pin ci/intermediates.pin.json
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The keyboard shortcut selects all (the browser opens on the runner's desktop, as in e2e-hunt.yml)
|
||||
@@ -331,6 +371,11 @@ jobs:
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
# The preloaded-intermediates list is a file of the repository (ci/intermediates.json, empty, the sha256 in ci/intermediates.pin.json): with
|
||||
# STEALTHFOX_INTERMEDIATES set the core neither downloads nor checks Mozilla's. BEFORE `fetch`, which makes the list present (it would download it).
|
||||
- name: The intermediates list (a fixed file of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_intermediates.py set --pin ci/intermediates.pin.json
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
# The GeoIP database made by the repository, as on the Linux run (no download, the same bytes every run).
|
||||
@@ -379,3 +424,19 @@ jobs:
|
||||
path: ${{ runner.temp }}/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
- name: Upload the junit of the run
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: e2e-junit-windows-${{ matrix.part }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: ${{ runner.temp }}/e2e-junit-*.xml
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
- name: Upload what the tests saved
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: invpw-evidence-windows-${{ matrix.part }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: ${{ runner.temp }}/invpw-evidence
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
@@ -164,7 +164,7 @@ jobs:
|
||||
echo "::notice::invisible-core $WANT is on the index"
|
||||
|
||||
- name: install the package and its dev extras
|
||||
# Its own step, BEFORE the arming below: install_hooks.py imports
|
||||
# Its own step, BEFORE the arming below: `python -m invisible_core.hooks install` imports
|
||||
# invisible_core, and the first version of this file installed inside the
|
||||
# suite step, so the arming ran against a runner that had nothing
|
||||
# installed and died on ModuleNotFoundError. ci.yml has had this order
|
||||
@@ -188,7 +188,7 @@ jobs:
|
||||
|
||||
- name: arm the pre-push gates
|
||||
# The suite asserts core.hooksPath is set and a fresh checkout has none.
|
||||
run: python scripts/install_hooks.py
|
||||
run: python -m invisible_core.hooks install
|
||||
|
||||
- name: the suite
|
||||
# A tag push does not trigger the ordinary test workflow, which runs on
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
# real-sites.yml - on real pages, does the published wrapper get the same outcome as stock Firefox driven by stock Playwright, on the same machine, in the same window of time?
|
||||
#
|
||||
# ONE QUESTION. It does not measure the quality of an address or a percentage of blocks: a GitHub runner has a datacenter address and no proxy is used. Where stock Firefox
|
||||
# is blocked as well, the cell carries no information and is written as such. It is red only where stock gets through and the wrapper does not.
|
||||
#
|
||||
# WHAT RUNS (per system, Linux under Xvfb with a window, and Windows; in a job everything in a row, one browser at a time):
|
||||
# 1. two clean venvs: `invisible-playwright==<the version the index serves now>`, and Playwright at scripts/playwright_pin.txt with its Firefox;
|
||||
# 2. the pass of stock over the whole list (scripts/run_real_sites.py), then the pass of ours;
|
||||
# 3. only for the cells that differ in the first pass: two more passes of those sites, stock, ours, stock, ours;
|
||||
# 4. the judge (scripts/judge_real_sites.py): the table, three numbers, the exit code. Its rule is in its own docstring and tests/test_real_sites_judge.py.
|
||||
# The cells (JSON) and the summary are the artifacts of the run. The same conditions for both browsers: a window, one viewport, no proxy, the language of the runner.
|
||||
#
|
||||
# WHEN (never by hand, except to run a whole round again):
|
||||
# * `workflow_run` of publish.yml, completed with success: the round after a publication, on the packages that just went out;
|
||||
# * `push` to main and `pull_request` that touch the five files below: the round proves itself, on the packages published at that moment;
|
||||
# * `workflow_dispatch`: to run a whole round again.
|
||||
#
|
||||
# VERSION. After a publication the version is the tag of the publish run (`head_branch` without its `v`); a run that is not of a `v*` tag makes the plan red. The other
|
||||
# events read the version the index serves now.
|
||||
#
|
||||
# WHY PER PUSH. The admission judges a list when the list changes; the round measures at every push. A push that does not touch tests/realsites/sites.json does not run the
|
||||
# admission again, or every push of the pull request would resample the real sites and could go red for a reason that is nobody's change. The plan decides it per push:
|
||||
# a push is compared with the head it replaced; if that compare cannot be made (a forced push, no `before`, an API error) the admission runs, in doubt measure.
|
||||
#
|
||||
# ADMISSION. A push to a pull request that changes tests/realsites/sites.json runs the admission AND the round (14 jobs: the plan, 2 of the round, 10 passes of the admission and
|
||||
# its report). The admission is stock alone, five passes per site and per system (a job per pass, so that a list of thirty sites stays inside the limit of a job). It is
|
||||
# red only for a defect of the list, never for the luck of one site: an invalid list (a `min_informative` in the file is one), a pass that is missing, a site never good in
|
||||
# any pass of a system that is not of the class protetta (a wrong marker, or a fixed block), more than 4 protetta, more than 20 sites. A site good in some passes stays,
|
||||
# and the report gives its count per system ("4 of 5 on linux"): every real site has a rare failure on the side of stock, five passes cannot tell it from instability,
|
||||
# and in the round it only removes information from that cell. The minimum of information is not sampled and is not in the file: the judge asks for half the sites,
|
||||
# rounded up. Where stock does not find the marker, its cell in the artifact also holds the status, the title and the first 40 element ids of the page, to fix the marker
|
||||
# in the same pull request; the judge ignores them.
|
||||
#
|
||||
# TOKEN. The token of the workflow is in three steps and nowhere else: the plan and the report of the admission (they call `gh`) and the install and fetch of the
|
||||
# round (the engine is downloaded from GitHub; that step launches no browser). A step that runs the passes never sees it.
|
||||
#
|
||||
# No click and no handling of a consent wall anywhere: both browsers see what the page shows.
|
||||
|
||||
name: real-sites
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [publish]
|
||||
types: [completed]
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- tests/realsites/sites.json
|
||||
- scripts/run_real_sites.py
|
||||
- scripts/judge_real_sites.py
|
||||
- tests/test_real_sites_judge.py
|
||||
- .github/workflows/real-sites.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- tests/realsites/sites.json
|
||||
- scripts/run_real_sites.py
|
||||
- scripts/judge_real_sites.py
|
||||
- tests/test_real_sites_judge.py
|
||||
- .github/workflows/real-sites.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
env:
|
||||
PYTHONUTF8: "1"
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
# Whether this run also admits a list, and the version of the package it tests, read ONCE so that both systems test the same one.
|
||||
plan:
|
||||
name: plan
|
||||
if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
admission: ${{ steps.plan.outputs.admission }}
|
||||
version: ${{ steps.plan.outputs.version }}
|
||||
steps:
|
||||
- id: plan
|
||||
shell: bash
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
REPO: ${{ github.repository }}
|
||||
ACTION: ${{ github.event.action }}
|
||||
BEFORE: ${{ github.event.before }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
admission=$(python3 - <<'PY'
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
LIST = "tests/realsites/sites.json"
|
||||
ZEROS = "0" * 40
|
||||
|
||||
|
||||
def gh_files(endpoint, jq):
|
||||
done = subprocess.run(["gh", "api", endpoint, "--paginate", "--jq", jq], capture_output=True, text=True, check=True)
|
||||
return done.stdout.split()
|
||||
|
||||
|
||||
def decide(event, action, before, head, repo, pr, files_of):
|
||||
"""Does this run admit the list? Only when this push changes it. A push (synchronize) is compared with the head it replaced; a pull request that is
|
||||
opened or reopened is judged on all its files. A compare that cannot be made (a forced push, no `before`, an API error) runs the admission: in doubt, measure."""
|
||||
if event != "pull_request":
|
||||
return False
|
||||
if action == "synchronize":
|
||||
if not before or before == ZEROS or not head:
|
||||
return True
|
||||
endpoint, jq = "repos/%s/compare/%s...%s" % (repo, before, head), ".files[].filename"
|
||||
else:
|
||||
endpoint, jq = "repos/%s/pulls/%s/files" % (repo, pr), ".[].filename"
|
||||
try:
|
||||
return LIST in files_of(endpoint, jq)
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
e = os.environ
|
||||
print("true" if decide(e["EVENT"], e.get("ACTION", ""), e.get("BEFORE", ""), e.get("HEAD_SHA", ""), e["REPO"], e.get("PR", ""), gh_files) else "false")
|
||||
PY
|
||||
)
|
||||
if [ "$EVENT" = workflow_run ]; then
|
||||
case "$HEAD_BRANCH" in
|
||||
v*)
|
||||
version="${HEAD_BRANCH#v}"
|
||||
;;
|
||||
*)
|
||||
echo "::error::the publish run is of '$HEAD_BRANCH', not of a v* tag: the version of the package is not known"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
else
|
||||
version=$(python3 -c 'import json, urllib.request; print(json.load(urllib.request.urlopen("https://pypi.org/pypi/invisible-playwright/json", timeout=60))["info"]["version"])')
|
||||
fi
|
||||
echo "admission=$admission" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "admission: $admission, invisible-playwright $version"
|
||||
|
||||
round:
|
||||
name: round (${{ matrix.os }})
|
||||
needs: plan
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
fail-fast: false # one system failing must not hide the other's table
|
||||
matrix:
|
||||
os: [ubuntu-24.04, windows-latest]
|
||||
env:
|
||||
VERSION: ${{ needs.plan.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.12' }
|
||||
|
||||
- name: Linux runtime libraries for the browsers
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb libgtk-3-0 libdbus-glib-1-2 libasound2t64
|
||||
|
||||
# Two venvs that share nothing: what a user gets from the index, and what a user of stock Playwright gets. The wrapper is installed by its published version
|
||||
# (the index may lag a few minutes behind a publication: only the install is asked again), then its engine is fetched the way a user fetches it.
|
||||
- name: The two clean venvs
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }} # the fetch of the engine is a download from GitHub; nothing here opens a page
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$RUNNER_OS" = Windows ]; then BIN=Scripts; EXE=python.exe; else BIN=bin; EXE=python; fi
|
||||
python -m venv venvs/ours
|
||||
python -m venv venvs/stock
|
||||
echo "OURS_PY=venvs/ours/$BIN/$EXE" >> "$GITHUB_ENV"
|
||||
echo "STOCK_PY=venvs/stock/$BIN/$EXE" >> "$GITHUB_ENV"
|
||||
OURS="venvs/ours/$BIN/$EXE"; STOCK="venvs/stock/$BIN/$EXE"
|
||||
PIN=$(tr -d '[:space:]' < scripts/playwright_pin.txt)
|
||||
"$STOCK" -m pip install --quiet --disable-pip-version-check "playwright==$PIN"
|
||||
if [ "$RUNNER_OS" = Linux ]; then "$STOCK" -m playwright install --with-deps firefox; else "$STOCK" -m playwright install firefox; fi
|
||||
for attempt in 1 2 3 4 5 6; do
|
||||
if "$OURS" -m pip install --quiet --disable-pip-version-check "invisible-playwright==$VERSION"; then break; fi
|
||||
if [ "$attempt" = 6 ]; then echo "::error::the index does not give invisible-playwright==$VERSION"; exit 1; fi
|
||||
sleep 20
|
||||
done
|
||||
"$OURS" -m invisible_playwright fetch
|
||||
|
||||
# The pass of stock, the pass of ours, the cells that differ, and for those only two more passes of each in the order stock, ours, stock, ours.
|
||||
- name: The passes
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p cells
|
||||
visit() { # browser, file of the cells, then what run_real_sites.py takes
|
||||
local browser="$1" out="$2" py="$STOCK_PY"
|
||||
shift 2
|
||||
if [ "$browser" = ours ]; then py="$OURS_PY"; fi
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
xvfb-run -a -s "-screen 0 1920x1080x24" "$py" scripts/run_real_sites.py --browser "$browser" --out "$out" "$@"
|
||||
else
|
||||
"$py" scripts/run_real_sites.py --browser "$browser" --out "$out" "$@"
|
||||
fi
|
||||
}
|
||||
visit stock cells/stock-1.json
|
||||
visit ours cells/ours-1.json
|
||||
IDS=$(python scripts/judge_real_sites.py differing --sites tests/realsites/sites.json --stock cells/stock-1.json --ours cells/ours-1.json)
|
||||
echo "cells that differ: ${IDS:-none}"
|
||||
if [ -n "$IDS" ]; then
|
||||
for n in 2 3; do
|
||||
visit stock "cells/stock-$n.json" --only "$IDS"
|
||||
visit ours "cells/ours-$n.json" --only "$IDS"
|
||||
done
|
||||
fi
|
||||
|
||||
- name: The judge
|
||||
shell: bash
|
||||
run: |
|
||||
set +e
|
||||
python scripts/judge_real_sites.py judge --sites tests/realsites/sites.json \
|
||||
--stock cells/stock-*.json --ours cells/ours-*.json --summary cells/summary.md --result cells/result.json
|
||||
code=$?
|
||||
{
|
||||
echo "### $RUNNER_OS: invisible-playwright $VERSION against stock Playwright $(tr -d '[:space:]' < scripts/playwright_pin.txt)"
|
||||
echo
|
||||
cat cells/summary.md
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
exit $code
|
||||
|
||||
- name: The cells and the summary
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: real-sites-${{ runner.os }}
|
||||
path: cells/
|
||||
if-no-files-found: ignore
|
||||
|
||||
# One pass of stock over the list, on one system: five of them per system make the admission.
|
||||
admit:
|
||||
name: admit (${{ matrix.os }}, pass ${{ matrix.repeat }})
|
||||
needs: plan
|
||||
if: needs.plan.outputs.admission == 'true'
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-24.04, windows-latest]
|
||||
repeat: [1, 2, 3, 4, 5]
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.12' }
|
||||
|
||||
- name: Linux runtime libraries for the browser
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb libgtk-3-0 libdbus-glib-1-2 libasound2t64
|
||||
|
||||
- name: Stock Playwright and its Firefox, then one pass
|
||||
shell: bash
|
||||
env:
|
||||
REPEAT: ${{ matrix.repeat }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$RUNNER_OS" = Windows ]; then BIN=Scripts; EXE=python.exe; else BIN=bin; EXE=python; fi
|
||||
python -m venv venvs/stock
|
||||
STOCK="venvs/stock/$BIN/$EXE"
|
||||
PIN=$(tr -d '[:space:]' < scripts/playwright_pin.txt)
|
||||
"$STOCK" -m pip install --quiet --disable-pip-version-check "playwright==$PIN"
|
||||
if [ "$RUNNER_OS" = Linux ]; then "$STOCK" -m playwright install --with-deps firefox; else "$STOCK" -m playwright install firefox; fi
|
||||
mkdir -p cells
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
xvfb-run -a -s "-screen 0 1920x1080x24" "$STOCK" scripts/run_real_sites.py --browser stock --diagnose --out "cells/stock-$REPEAT.json"
|
||||
else
|
||||
"$STOCK" scripts/run_real_sites.py --browser stock --diagnose --out "cells/stock-$REPEAT.json"
|
||||
fi
|
||||
|
||||
- name: The cells
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: admit-${{ runner.os }}-${{ matrix.repeat }}
|
||||
path: cells/
|
||||
if-no-files-found: ignore
|
||||
|
||||
admission:
|
||||
name: admission report
|
||||
needs: admit
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.12' }
|
||||
|
||||
- name: Which sites are the same five of five, and the minimum to write
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" --pattern 'admit-*' --dir admit
|
||||
set +e
|
||||
python scripts/judge_real_sites.py admit --sites tests/realsites/sites.json \
|
||||
--os linux admit/admit-Linux-*/stock-*.json --os windows admit/admit-Windows-*/stock-*.json \
|
||||
--summary admission.md
|
||||
code=$?
|
||||
cat admission.md >> "$GITHUB_STEP_SUMMARY"
|
||||
exit $code
|
||||
|
||||
- name: The report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: admission
|
||||
path: admission.md
|
||||
if-no-files-found: ignore
|
||||
@@ -186,6 +186,12 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# main, for the tests that compare a list of this change with the list of main (tests/test_the_e2e_tests_do_not_wait_on_clocks.py: the debt of
|
||||
# the e2e tests only shrinks). The checkout is one commit deep; without this the comparison has nothing to read and the test says so.
|
||||
- name: main, to compare the lists that may only shrink
|
||||
shell: bash
|
||||
run: git fetch --no-tags --depth=1 origin main:refs/remotes/origin/main
|
||||
|
||||
- name: Set up Python ${{ matrix.python }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
@@ -203,10 +209,10 @@ jobs:
|
||||
# three repos that existed then made the assertion (two now, since
|
||||
# invisible_firefox was deleted on 2026-08-18), but only the core's CI
|
||||
# had this step, so both consumers went red on it. Do here what a
|
||||
# developer does once. It also means install_hooks.py is exercised on
|
||||
# developer does once. It also means `python -m invisible_core.hooks install` is exercised on
|
||||
# every runner instead of only on the one machine that ever ran it by
|
||||
# hand.
|
||||
run: python scripts/install_hooks.py
|
||||
run: python -m invisible_core.hooks install
|
||||
|
||||
- name: undefined names and duplicate definitions
|
||||
# F821 (undefined name) and F811 (redefinition) only. Not a style pass:
|
||||
@@ -222,6 +228,12 @@ jobs:
|
||||
run: |
|
||||
python -m ruff check --select F821,F811,F601 --no-cache --output-format concise .
|
||||
|
||||
# The preloaded-intermediates list is a file of the repository (ci/intermediates.json, empty, the sha256 in ci/intermediates.pin.json): with
|
||||
# STEALTHFOX_INTERMEDIATES set the core neither downloads nor checks Mozilla's.
|
||||
- name: The intermediates list (a fixed file of the repository)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_intermediates.py set --pin ci/intermediates.pin.json
|
||||
|
||||
# The GeoIP database is made by the repository (scripts/ci_lab_geoip.py: the same bytes on every run, the sha256 in ci/geoip.json), never a
|
||||
# site and never a licensed file: without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call
|
||||
# (run 43211837926). The variable reaches every later step of the job.
|
||||
|
||||
+105
-5
@@ -4,11 +4,108 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
## [0.55.0] - 2026-11-19
|
||||
|
||||
## [0.52.1] - 2026-11-14
|
||||
### Changed
|
||||
- Pins invisible-core 66.76.0 (same engine, firefox-66): the core no longer carries its legacy API, and the wrapper no longer reaches any of it.
|
||||
- `tests/conftest.py` takes the engine entry table from `invisible_core.seal.DEFAULT_ENTRY_REL`, and a test fails if a file of the wrapper imports a name the core removed.
|
||||
- The workflows arm the pre-push gates with `python -m invisible_core.hooks install`.
|
||||
|
||||
Same pin as 0.52.0 (invisible-core 64.71.0).
|
||||
### Removed
|
||||
- The nine modules that only re-exported `invisible_core` (`invisible_playwright._geo`, `_headless`, `_proxy`, `_webgl_personas`, `config`,
|
||||
`constants`, `download`, `prefs`, `_fpforge`) and `invisible_playwright._reaper`: import `invisible_core.<module>` (`invisible_core.process`
|
||||
for the reaper). `resolve_session_timezone` is no longer re-exported from the package root.
|
||||
- `INVPW_CURSOR_ENGINE=binary` and the fallback to the browser's own motion when no generator is found: the engine is the Python one, or `off`. The variable is strict: unset, `python` or `off`; any other value (`binary`, `none`, `false`, `0`...) is a `ValueError` that lists them.
|
||||
- The test that scanned a driver bundle tree, which only the removed Node driver had.
|
||||
- `INVPW_TRANSPORT=driver` and its refusal message: there is one transport.
|
||||
- `scripts/install_hooks.py`: `python -m invisible_core.hooks install` (with `--check` to only report) does the same, from the core.
|
||||
|
||||
### Fixed
|
||||
- The documentation no longer presents `INVPW_BINARY_PATH` as a variable of the library, which reads none; a binary you already have is passed
|
||||
as `binary_path=`.
|
||||
|
||||
## [0.54.0] - 2026-11-18
|
||||
|
||||
### Engine firefox-66
|
||||
- A screenshot on Linux draws text in the fonts the page used. The browser's main process rebuilds each font of a screenshot from its
|
||||
file and asks fontconfig to confirm that file; it now shows the bundled fonts to fontconfig before it builds its font list, so the file
|
||||
is known and kept instead of being replaced by a fallback font (screen and canvas were already right; only screenshots were wrong).
|
||||
- A face of a font collection (`.ttc`) keeps its own index when the main process rebuilds it, so it is no longer drawn as another face of
|
||||
the same file (Cambria Math, MS PGothic and NSimSun came out as Cambria, MS Gothic and SimSun). This is Mozilla's fix of bug 2077661,
|
||||
carried as Mozilla wrote it until a Firefox release ships it.
|
||||
- Windows was not affected.
|
||||
|
||||
### Changed
|
||||
- Pins invisible-core 66.75.0 and with it the engine firefox-66.
|
||||
|
||||
### Added
|
||||
- A test that draws text in each bundled family the identity declares (accents, a typographic apostrophe, Chinese, Japanese, Arabic,
|
||||
Russian, and two faces that are not the first of their collection) and compares the screenshot, byte for byte, with the same text drawn
|
||||
by the page itself into a canvas, on Linux and on Windows.
|
||||
- A Linux test that a second launch reads the bundle from fontconfig's cache and does not scan the folder again, measured under strace,
|
||||
with a test of the strace stand-in itself.
|
||||
|
||||
## [0.53.1] - 2026-11-16
|
||||
|
||||
0.53.0 was tagged but never published; its changes ship in 0.53.1. One of its tests read the page's address too early when the first of
|
||||
two navigations wins; 0.53.1 corrects that test.
|
||||
|
||||
### Engine firefox-65
|
||||
- Keys, clicks and the mouse path stay on their planned timing under load.
|
||||
- A second `goto` that starts while a site is changing process no longer hangs.
|
||||
- The isolated worlds of init scripts are always created.
|
||||
- A worker comes back with its page from the back-forward cache.
|
||||
- The names looked up as a context closes go through that context's proxy.
|
||||
- `close()` returns when the browser has exited, and never interrupts it while it exits.
|
||||
|
||||
### Changed
|
||||
- Pins invisible-core 65.74.0 and with it the engine firefox-65.
|
||||
- The path of the cursor leaves as one stroke. The approach, the walk before a click, the wheel burst and the idle movement hand their
|
||||
planned timeline to the core's `Actions.walk`, which sends each point at its planned instant on the client's own clock, without waiting
|
||||
for the reply of the one before; the replies are collected at the end. Before, each point was a command of its own that waited for the
|
||||
engine's reply, and a slow reply was a pause in the path that the page saw (2.6 s measured on a GitHub runner), with the points after it
|
||||
crowded together. A lone `mouse.down`, `mouse.up` or one-step `mouse.move` is still a single command that waits for its reply, as in Playwright.
|
||||
- `close()` returns when the browser has exited, and the removal of the session's directories and the last reap of its tree are left to the
|
||||
reaper of the launch (invisible-core 65.74.0), instead of being done at once and waiting for the sender of the shutdown pings. A session
|
||||
that is over is forgotten by the registry of reapers, so a long-lived server no longer keeps one entry per session.
|
||||
- The download and upload folders of a session are removed by the reapers of its launches, after the tree has ended, and no longer on
|
||||
the server's shutdown thread that the user's exit waits for (4 profiles removed together took up to 2.5 s on Windows). With no reaper
|
||||
they are removed at once, as before.
|
||||
|
||||
### Fixed
|
||||
- The cursor's motion never fails an action for what the engine or the page answers (a closed target, a detached frame, a refused or
|
||||
unanswered command), and no longer hides a bug of ours: an error of our own in the path (an `AttributeError`, a `TypeError`) comes out of
|
||||
the action instead of being swallowed with one warning and a click that goes out with no path.
|
||||
|
||||
### Removed
|
||||
- `pytest-rerunfailures` from the `dev` extra. No run of this repository reruns a test (the e2e run refuses the plugin by name, `-p no:rerunfailures`).
|
||||
|
||||
### Tests
|
||||
- The e2e tests wait for a condition with a deadline of 30 s, not for a clock, and the workers share no port: a Marionette port per launch,
|
||||
the HTTP/3 server serves on the UDP socket its picker held. A test that is red now says what
|
||||
it saw. (#507, #511, #514)
|
||||
- The shelved engine line is firefox-66; its 15 tests wait for it. (#509)
|
||||
- A loop late in its selector is not held; only the time its thread runs counts. (#508)
|
||||
- A check that the e2e tests do not wait on clocks, share ports, write the environment or reach the world; the debt of that check only shrinks.
|
||||
- The whole unit suite is a required suite of the candidate: 1988 tests on Linux and 1989 on Windows.
|
||||
- The click and pointer benches count a stroke's instants on their virtual clock, and the key-delay test reads the browser's own event
|
||||
time stamps. (#516)
|
||||
- The e2e workflow uploads the junit of every pass of the run (Linux, and each Windows part), green or red.
|
||||
|
||||
## [0.52.1] - 2026-11-15
|
||||
|
||||
### Changed
|
||||
- Pins invisible-core 64.73.0 (same engine, firefox-64). The compositor is now declared in software on every machine, as a
|
||||
retail Firefox reports on a machine without a usable GPU, and never read from the host. Before, the hardware compositor
|
||||
was declared over a software adapter, which cost about 6x the CPU in the GPU process.
|
||||
- Windows: the engine is created inside a job of its own, so a launch no longer scans every process of the machine to bind
|
||||
the engine's tree. (#498)
|
||||
- Several browsers in one async program no longer slow one another down:
|
||||
- `connect()` starts no thread on the event loop (#497).
|
||||
- The virtual display of `headless=True` starts off the event loop (#499).
|
||||
- Closing a browser waits for its processes and removes its profile without holding the loop that serves the others:
|
||||
with four browsers in one process the loop was held for up to about 0.5 s per close, and is not held now (#503).
|
||||
- Comments, the fork notes and one test message no longer point at scripts that were deleted (the transport comparison scripts and the prefs byte-parity gate: no round ran them). No behaviour changes. (#458)
|
||||
|
||||
### Added
|
||||
- `page.expose_function`, `page.expose_binding`, `context.expose_function` and `context.expose_binding`, as in Playwright: the page calls a Python function and gets a promise (the value, a rejection when the function raised, an await when it is async). The page sees the function and nothing else (no name of ours on the window, no init script); an engine without `Page.addBinding` is refused with a clear sentence. Arguments and results cross as JSON. (#471)
|
||||
@@ -18,8 +115,11 @@ Same pin as 0.52.0 (invisible-core 64.71.0).
|
||||
- A context init script added after a page exists runs once in it, not twice. (#469)
|
||||
- A CORS preflight (an OPTIONS request that no route holds) is no longer reported to the client, as in Playwright's own server: `page.on("request")`, `route` and a request counter hear of one request fewer for each preflighted fetch of the page. (#467)
|
||||
|
||||
### Changed
|
||||
- Comments, the fork notes and one test message no longer point at scripts that were deleted (the transport comparison scripts and the prefs byte-parity gate: no round ran them). No behaviour changes. (#458)
|
||||
### Tests
|
||||
- Every test module is checked to leave no browser open (a census of the connection threads, which needs no package to run). (#497, #500)
|
||||
- Software compositing is declared: the compositor in use, the CPU of the GPU process, and the bytes a page reads compared
|
||||
against a recorded reference, on Linux and Windows. (#501)
|
||||
- The UDP bench survives a loaded Windows machine, and its verdict says what it saw. (#502)
|
||||
|
||||
## [0.52.0] - 2026-11-14
|
||||
|
||||
|
||||
+2626
File diff suppressed because it is too large.
Load diff
@@ -16,6 +16,11 @@
|
||||
This one runs on an anti-detect Firefox with an undetected fingerprint, compatible with your existing Playwright code.</h3>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://decodo.com/deals/residential-offer?utm_medium=affiliate&utm_source=Federico+Elia&promoter_id=15854270&fpr=7859773"><img alt="Decodo residential proxies, free trial (sponsored)" src="https://raw.githubusercontent.com/oss-invisible/playwright/main/docs/decodo-residential-proxies-trial.png" width="560"></a><br>
|
||||
<sub>Sponsored</sub>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
## How it works
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"format":1,"collection":"security-state/intermediates","collection_timestamp":0,"fetched_utc":"1970-01-01T00:00:00Z","count":0,"set_sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","certs":[]}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"comment": "The preloaded-intermediates list every CI leg launches with (STEALTHFOX_INTERMEDIATES): EMPTY (format 1, no certificates), so a leg never asks Mozilla for the real list (the core neither downloads nor checks when the variable is set) and every run has the same bytes. Set by scripts/ci_lab_intermediates.py. To change the list, change ci/intermediates.json and sha256 here in one commit; `set` refuses to go on when they differ. The real list is looked at only by what the release proves about the product.",
|
||||
"file": "ci/intermediates.json",
|
||||
"sha256": "f4f6a2332a4d589a1e8aaa4e73c820644a764125bb2970667afc7351e7cb3465",
|
||||
"bytes": 219
|
||||
}
|
||||
@@ -5,11 +5,14 @@
|
||||
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
|
||||
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
|
||||
{"id": "wrapper.e2e.context.egress", "giro": "G2", "os": ["linux", "windows"], "min_tests": 14, "exact": true, "tests": ["tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Taken from the minimal-engine port (branch tests/minimal-port) unchanged but for the removed engine gate: 12 = 6 kinds of page work (hints, image/fetch/WebSocket/EventSource, WebRTC STUN and TURN-udp by name, geolocation, a service worker with push, a page still loading when its context closes) x 2 schemes (no proxy at launch and a gateway on the context; a launch gateway and a different one on the context), and 2 = the TURN server named over TCP in those two schemes. EXPECTED RED on the published firefox-63: the 2 TURN-by-name cases (the lookup of the TCP socket takes user context 0; fixed by commits ac0214bff4 and 058edd6cc6 of firefox-64). The 12 have not run on any engine yet. Like wrapper.e2e.doh: the Linux leg runs as root for the resolver trap (INVPW_REQUIRE_TRAP=1); on Windows the DoH log and the gateway's CONNECTs are the sink."},
|
||||
{"id": "wrapper.e2e.context.sink", "giro": "G2", "os": ["linux", "windows"], "min_tests": 35, "exact": true, "tests": ["tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The behavioural half of the class gate 'nothing of a context leaves but through its proxy', with a witness at an address of this host (no root, no address on lo) and the engine's own resolver log as the native-lookup sink. 35 = 31 + the 4 OCSP cases; the 31 are 19 probes (fetch, WebSocket, stun, turn over UDP, turn and turns over TCP, each by name, by IP and by a .local name, behind SOCKS5 and behind an HTTP proxy where the road differs) + 3 controls (the same probe by IP with no proxy IS heard by the witness) + 1 control of the native sink. + 4 PeerConnections built from a torn-down window (a detached iframe, a closed popup; behind SOCKS5 and behind HTTP; defect B3: EXPECTED RED on firefox-63, green on firefox-64) + 2 controls of them (the same PeerConnection from an attached iframe, green on both). + 2 cases of two contexts alive at once (each with its own proxy and DoH, a TURN server over TCP by a different name in each; behind SOCKS5 EXPECTED RED on firefox-63 like turn_tcp-name-socks5, behind HTTP green on both). EXPECTED RED on firefox-63: turn_tcp-name-socks5, turns_tcp-name-socks5 (user context 0, fixed in firefox-64) and the three .local cases fetch-local-socks5, stun-local-socks5, stun-local-http (audit B4, also red on firefox-64 until decided). The Linux leg runs as root so the resolver trap is a second sink. Windows reads the same engine log (its getaddrinfo lines are in the parent process file under the sandbox: run 43574494194), with the no-proxy native control as its positive control. THE OCSP CASES (4): a TLS page whose leaf, signed by a lab CA the engine trusts (put in the profile by the engine's xpcshell, no ignore_https_errors), names its OCSP responder by a NAME (ocsp-<nonce>.lab.test) and by an IP; a context behind the gateway loads it and the request must go through the gateway, never be looked up natively, in user context 0, or reach the responder (2 cases, EXPECTED RED on firefox-63, green on firefox-64); the same page in a context with no proxy IS asked of the responder (control); a page of an issuer the engine does not trust makes no OCSP request (negative control)."},
|
||||
{"id": "wrapper.e2e.context.sink", "giro": "G2", "os": ["linux", "windows"], "min_tests": 36, "exact": true, "tests": ["tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The behavioural half of the class gate 'nothing of a context leaves but through its proxy', with a witness at an address of this host (no root, no address on lo) and the engine's own resolver log as the native-lookup sink. 35 = 31 + the 4 OCSP cases; the 31 are 19 probes (fetch, WebSocket, stun, turn over UDP, turn and turns over TCP, each by name, by IP and by a .local name, behind SOCKS5 and behind an HTTP proxy where the road differs) + 3 controls (the same probe by IP with no proxy IS heard by the witness) + 1 control of the native sink. + 4 PeerConnections built from a torn-down window (a detached iframe, a closed popup; behind SOCKS5 and behind HTTP; defect B3: EXPECTED RED on firefox-63, green on firefox-64) + 2 controls of them (the same PeerConnection from an attached iframe, green on both). + 2 cases of two contexts alive at once (each with its own proxy and DoH, a TURN server over TCP by a different name in each; behind SOCKS5 EXPECTED RED on firefox-63 like turn_tcp-name-socks5, behind HTTP green on both). EXPECTED RED on firefox-63: turn_tcp-name-socks5, turns_tcp-name-socks5 (user context 0, fixed in firefox-64) and the three .local cases fetch-local-socks5, stun-local-socks5, stun-local-http (audit B4, also red on firefox-64 until decided). The Linux leg runs as root so the resolver trap is a second sink. Windows reads the same engine log (its getaddrinfo lines are in the parent process file under the sandbox: run 43574494194), with the no-proxy native control as its positive control. THE OCSP CASES (4): a TLS page whose leaf, signed by a lab CA the engine trusts (put in the profile by the engine's xpcshell, no ignore_https_errors), names its OCSP responder by a NAME (ocsp-<nonce>.lab.test) and by an IP; a context behind the gateway loads it and the request must go through the gateway, never be looked up natively, in user context 0, or reach the responder (2 cases, EXPECTED RED on firefox-63, green on firefox-64); the same page in a context with no proxy IS asked of the responder (control); a page of an issuer the engine does not trust makes no OCSP request (negative control). THE CLOSED CONTEXT CASE (1, gated firefox-65): a beacon sent on pagehide as a proxied context closes, to a name never looked up, is resolved over the DoH through the context's gateway after the close; on firefox-64 it went to the machine's resolver every time (hunt 43733181674)."},
|
||||
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
|
||||
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 249, "exact": true, "tests": ["tests/test_the_server_says_nothing_about_the_launch_counter.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_egress_sink_helpers.py", "tests/test_the_lab_ca_and_its_ocsp_leaf.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 20): the engine's log (the same on Linux and Windows) and the witness read on known inputs, and a blind log that must raise, never answer 'nothing'. The lab CA of its OCSP case (tests/test_the_lab_ca_and_its_ocsp_leaf.py, 17; tests/test_the_fake_doh_answers.py +1, the DoH serving a lab-CA leaf): the leaf's AIA, trusted and untrusted issuers, the responder, the xpcshell step."},
|
||||
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
|
||||
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 259, "exact": true, "tests": ["tests/test_doh_session_prefs_unit.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_preload_newtab_is_written_only_when_asked.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_egress_sink_helpers.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_fake_doh_answers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_host_address_helper.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_the_lab_ca_and_its_ocsp_leaf.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_realness_helpers.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_server_says_nothing_about_the_launch_counter.py", "tests/test_the_udp_bench_survives_what_a_loaded_machine_does_to_it.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 20): the engine's log (the same on Linux and Windows) and the witness read on known inputs, and a blind log that must raise, never answer 'nothing'. The lab CA of its OCSP case (tests/test_the_lab_ca_and_its_ocsp_leaf.py, 17; tests/test_the_fake_doh_answers.py +1, the DoH serving a lab-CA leaf): the leaf's AIA, trusted and untrusted issuers, the responder, the xpcshell step."},
|
||||
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 124, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 + the 9 of test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py (four browsers in one process, one closes: the loop is never seen inside a step of the close, the removal of the profile is held still and reached on a thread of the reaper while the close has returned, the other three keep answering; one control holds the loop on purpose, the other leaves it late in its selector and must not be charged). 114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
|
||||
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."},
|
||||
{"id": "wrapper.e2e.compositing", "giro": "G2", "os": ["linux", "windows"], "min_tests": 3, "exact": true, "tests": ["tests/test_software_compositing_is_declared_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The engine DECLARES software compositing on every machine (core: the compositing entries of zoom.stealth.gfx.feature_status carry the VM decision, and on Windows gfx.webrender.software=true, gfx.webrender.software.d3d11=false). 3 = (1) the compositor read from a privileged context is 'WebRender (Software)' on Windows and on Linux (windowUtils.layerManagerType of each window: Troubleshoot.snapshot().graphics throws on this engine, `ext is null`, so it is not the route); (2) the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows runner: 0.32 s declared, 2.7-4.2 s not, runs 43652292533 and 43642744101; on Linux it is held to the bound if a GPU process exists); (3) the 86 keys of the page-bytes probe plus the canvas 2D scenes (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients) equal tests/data/page_bytes_<os>.json, PNGs on decoded pixels. EXPECTED RED on the core 64.71.0 (tests 1 and 2 on Windows). The reference of Windows holds the 75 stable keys and 6 of the 11 PNG keys of run 43652292533; the five other PNG keys and the new canvas keys, and all of Linux, are written from the first run on the engine of the reference (the failure of test 3 prints RECORD-BEGIN ... RECORD-END with the entries to merge): a reference that is not complete is red, never skipped."},
|
||||
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 17, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process and the CPU of a window, and the shape of the committed Windows reference."}
|
||||
{"id": "wrapper.e2e.compositing", "giro": "G2", "os": ["linux", "windows"], "min_tests": 9, "exact": true, "tests": ["tests/test_software_compositing_is_declared_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The engine DECLARES software compositing on every machine (core: the compositing entries of zoom.stealth.gfx.feature_status carry the VM decision, and on Windows gfx.webrender.software=true, gfx.webrender.software.d3d11=false). 3 = (1) the compositor read from a privileged context is 'WebRender (Software)' on Windows and on Linux (windowUtils.layerManagerType of each window: Troubleshoot.snapshot().graphics throws on this engine, `ext is null`, so it is not the route); (2) the GPU process uses under 1.5 s of CPU on the fixed 10-scene loop of one browser (Windows runner: 0.32 s declared, 2.7-4.2 s not, runs 43652292533 and 43642744101; on Linux it is held to the bound if a GPU process exists); (3) the 86 keys of the page-bytes probe plus the canvas 2D scenes (drawImage scaled with smoothing off/low/medium/high, text with linear/radial/conic gradients) equal tests/data/page_bytes_<os>.json, PNGs on decoded pixels. EXPECTED RED on the core 64.71.0 (tests 1 and 2 on Windows). The reference of Windows holds the 75 stable keys and 6 of the 11 PNG keys of run 43652292533; the five other PNG keys and the new canvas keys, and all of Linux, are written from the first run on the engine of the reference (the failure of test 3 prints RECORD-BEGIN ... RECORD-END with the entries to merge): a reference that is not complete is red, never skipped. 9 = those 3 + the 6 families of tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py (from firefox-66, engine_at_least): a screenshot draws the text of Arial, Times New Roman, Consolas and Segoe UI, with accents, the typographic apostrophe, the euro sign, Chinese, Arabic and Russian, and of MS PGothic (face 2 of msgothic5_32.ttc: Japanese and Latin) and NSimSun (face 1 of simsun.ttc: Chinese), two faces that are not the first of their collection, with the same bytes as the content process drew them in a canvas (an SVG image with a foreignObject of the same markup), cut from the same page.screenshot, on both systems and with no threshold. EXPECTED RED on every engine that rebuilds the text in the parent with another font than the bundle (Linux: fontconfig answers DejaVu Sans), and skipped, hence red here, on an engine older than firefox-66. It saves the screenshot, the two boxes and a result.json under RUNNER_TEMP/invpw-evidence."},
|
||||
{"id": "wrapper.e2e.fontconfig", "giro": "G2", "os": ["linux"], "min_tests": 2, "exact": true, "tests": ["tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "Fontconfig exists only on Linux: the parent of the engine shows <GRE>/fonts to it (FcConfigAppFontAddDir) to rebuild a font from a path and a face index. On Windows DirectWrite opens the file from its path, with no folder to scan and no cache to read, so this test has no Windows counterpart.", "note": "2 = (1) the stand-in that runs the engine under strace stays in the engine's place, as the core launches it (the leader of a process group of its own): a fake engine with a child, no browser; the process the launcher holds lives as long as the fake engine, and the group killed holds strace and the child (the stand-in that exec'd setsid forked and exited 0 at once: candidate 44161687675); (2) the warm launch of the parent reads the bundle from fontconfig's cache and does not scan it again (from firefox-66, engine_at_least). Two launches under strace with the same XDG_CACHE_HOME of the test, the first cold and the second warm: the cold parent opens every font file of <GRE>/fonts (the folder as the disk lists it) before any page and fontconfig writes its cache; the warm parent does not open every one of them, and it opens a *.cache-* file of fontconfig (a few files are opened to be used, so the verdict asks about the whole folder, as a scan does). Scan and drawing are told apart by position: only what the parent opens before the first page counts (the opens that draw are written as after_startup). Evidence in RUNNER_TEMP/invpw-evidence/fontconfig-cache: the interval and the number of opens of the bundle, the names of the files of the bundle each launch opened before the first page, the size of the cache file, the VmRSS of the parent after about:blank and after a page with every family, and a third launch with gfx.bundled-fonts.activate=0 (the behaviour before), which is evidence only. Needs strace on the runner: without it both are red, not skipped. No threshold."},
|
||||
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 30, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference, and the box cut out of a screenshot (its pixels, a box outside the picture refused, written as a PNG and read back, two boxes told apart by a pixel that is named, the pixels that are not grey)."},
|
||||
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2131, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_css_calc_is_windows_e2e.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_math_sin_cos_tan_are_windows_e2e.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_preload_newtab_is_written_only_when_asked.py", "tests/test_protocol_names_are_declared.py", "tests/test_proxy_reaches_the_broLine truncated
|
||||
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2132, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_css_calc_is_windows_e2e.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_math_sin_cos_tan_are_windows_e2e.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_prefs_composition_arm_on_windows.py", "tests/test_preload_newtab_is_written_only_when_asked.py", "tests/test_protocol_names_are_declared.py", "tests/test_proLine truncated
|
||||
]
|
||||
@@ -63,8 +63,9 @@ Three separate limits, three separate ways this fails:
|
||||
|
||||
The download can be moved off the critical path with a cache directory, and the wrapper
|
||||
supports exactly that: `INVISIBLE_PLAYWRIGHT_CACHE_DIR` points the engine at a path your
|
||||
platform already caches between runs, and `INVPW_BINARY_PATH` skips the download entirely
|
||||
when a compatible binary is already on disk (see [Configuration](configuration.md)). That
|
||||
platform already caches between runs, and the `binary_path=` launch argument skips the
|
||||
download entirely when a compatible binary is already on disk (see
|
||||
[Configuration](configuration.md)). That
|
||||
helps a persistent worker a great deal. It helps a stateless function much less, because
|
||||
the thing a function does not keep is exactly the local disk those variables point at.
|
||||
|
||||
@@ -182,7 +183,7 @@ container is the right place to unpack the browser once and keep it warm, but it
|
||||
fix your IP reputation, your account quotas, or your timing. You supply those.
|
||||
|
||||
**How do I avoid downloading Firefox on every invocation?** Bake it into the image at
|
||||
build time, or point `INVPW_BINARY_PATH` at a binary already on disk. On a stateless
|
||||
build time, or pass `binary_path=` for a binary already on disk. On a stateless
|
||||
function neither fully helps, because the local disk does not persist between calls.
|
||||
|
||||
**What is the smallest thing that works?** A single long-lived worker: launch once inside
|
||||
|
||||
@@ -73,12 +73,15 @@ row is for a specific situation.
|
||||
|---|---|
|
||||
| `INVISIBLE_PLAYWRIGHT_CACHE_DIR` | Put the cache somewhere else - another drive, a shared location, a path your CI already caches. It holds the engine and this machine's state (the GeoIP database, the font manifest) |
|
||||
| `INVISIBLE_PLAYWRIGHT_ENGINE_DIR` | Keep the engine apart from the state, for example on a read-only disk built once per release: `invisible-playwright fetch` with it set fills it, and a launch only reads it. The cache directory must still be writable |
|
||||
| `INVPW_BINARY_PATH` | Point at a binary you already have, and skip the download |
|
||||
| `STEALTHFOX_GITHUB_TOKEN` | A rate-limited or corporate network that refuses anonymous GitHub downloads |
|
||||
| `INVISIBLE_PLAYWRIGHT_SKEW=allow` | Run a Playwright version outside the tested range anyway |
|
||||
| `INVPW_CURSOR_ENGINE` | `python` (default), `binary`, or `off` |
|
||||
| `INVPW_CURSOR_ENGINE` | `python` (default, same as unset) or `off`. Any other value stops the launch with an error that lists these two |
|
||||
| `INVISIBLE_DOWNLOAD_DEADLINE` | Seconds allowed for one engine download, default `1800`. Raise it on a very slow link; `0` removes the bound |
|
||||
|
||||
A binary you already have is not an environment variable: pass it as
|
||||
`binary_path=` to `InvisiblePlaywright(...)`. That route skips the download, and the
|
||||
engine is still checked against the sealed build, so a different one is refused.
|
||||
|
||||
```bash
|
||||
export INVISIBLE_PLAYWRIGHT_CACHE_DIR=/mnt/big/engines
|
||||
```
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 537 KiB |
@@ -103,13 +103,12 @@ build runner mounts a persistent volume, point
|
||||
entirely - `fetch` checks the cached tree against the seal first and only
|
||||
downloads if it does not match, so a warm cache makes the step nearly free.
|
||||
|
||||
The three environment variables that matter in a container build:
|
||||
The two environment variables that matter in a container build:
|
||||
|
||||
| Environment variable | What it does | Documented in |
|
||||
|---|---|---|
|
||||
| `STEALTHFOX_GITHUB_TOKEN` | Authenticates the engine download when a CI runner or corporate network rate-limits or blocks anonymous GitHub downloads | [Configuration](configuration.md) |
|
||||
| `INVISIBLE_PLAYWRIGHT_CACHE_DIR` | Points the binary cache at a path the build persists between runs, so a rebuild skips the ~238 MB download | [Configuration](configuration.md) |
|
||||
| `INVPW_BINARY_PATH` | Uses a binary already baked into the image and skips the `fetch` step entirely | [Configuration](configuration.md) |
|
||||
|
||||
## Running headless in the container
|
||||
|
||||
@@ -223,8 +222,8 @@ container would answer with the container's own defaults instead, which
|
||||
by field.
|
||||
|
||||
**Can I skip the download and bring my own binary into the image?** Yes,
|
||||
set `INVPW_BINARY_PATH` to a binary already baked into the image and the
|
||||
fetch step is skipped entirely. Covered in
|
||||
pass `binary_path=` for a binary already baked into the image and the
|
||||
fetch step is skipped entirely. The binary must be the sealed build; see
|
||||
[Configuration](configuration.md).
|
||||
|
||||
**Do I need a real GPU for this to work in a container?** Not for the
|
||||
@@ -238,8 +237,8 @@ is a rendering-quality question, not a detection one.
|
||||
the detection-level page this tutorial complements.
|
||||
- [Installation](installation.md) and the [CLI reference](cli-reference.md)
|
||||
for the exact `fetch` behaviour and environment variables used above.
|
||||
- [Configuration](configuration.md) for `INVISIBLE_PLAYWRIGHT_CACHE_DIR`,
|
||||
`INVPW_BINARY_PATH` and `STEALTHFOX_GITHUB_TOKEN`.
|
||||
- [Configuration](configuration.md) for `INVISIBLE_PLAYWRIGHT_CACHE_DIR`
|
||||
and `STEALTHFOX_GITHUB_TOKEN`.
|
||||
- Playwright documentation, [Docker](https://playwright.dev/python/docs/docker), for the
|
||||
base image and its version tags, retrieved 2026-08-28.
|
||||
- Docker Engine reference, [`docker run`](https://docs.docker.com/engine/containers/run/),
|
||||
|
||||
@@ -45,7 +45,7 @@ export INVISIBLE_PLAYWRIGHT_CACHE_DIR=/mnt/big/engines
|
||||
```
|
||||
|
||||
If you already have a compatible binary on disk and want to skip the download
|
||||
entirely, point `INVPW_BINARY_PATH` at it instead. The full list of environment
|
||||
entirely, pass it as `binary_path=` instead. The full list of environment
|
||||
variables, including the ones for corporate networks and CI, is in
|
||||
[Configuration](configuration.md).
|
||||
|
||||
@@ -76,7 +76,7 @@ against a sha256 shipped inside `invisible-core` every time it runs, not just on
|
||||
first install, so re-running `fetch` is itself the verification.
|
||||
|
||||
**What if I already have a compatible binary, or `fetch` can't reach the network?**
|
||||
Point `INVPW_BINARY_PATH` at a binary you already have to skip the download
|
||||
Pass `binary_path=` for a binary you already have to skip the download
|
||||
entirely. [Configuration](configuration.md) lists the other environment variables,
|
||||
including the ones for corporate networks and CI.
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ install` run" question specifically for the engine this project ships. It does n
|
||||
change how Playwright itself resolves executables for any other browser, and the same
|
||||
environment mismatches above (wrong OS in a Docker build, a filesystem that resets
|
||||
between CI stages, missing system libraries) apply identically to any browser process
|
||||
launched in that environment, patched or stock. Pointing `INVPW_BINARY_PATH` at a binary
|
||||
launched in that environment, patched or stock. Passing `binary_path=` for a binary
|
||||
you already manage yourself skips the automatic download entirely if your deployment
|
||||
already solves this problem another way.
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ is on the [installation](installation.md) page.
|
||||
that path is one the cache action restores. On a corporate or rate-limited runner that
|
||||
refuses anonymous GitHub downloads, `STEALTHFOX_GITHUB_TOKEN` lets the fetch authenticate;
|
||||
both variables are documented in [configuration](configuration.md). If you already ship a
|
||||
binary in the image, `INVPW_BINARY_PATH` skips the download entirely.
|
||||
binary in the image, `binary_path=` skips the download entirely.
|
||||
|
||||
## The real limiting factor: the runner's IP
|
||||
|
||||
@@ -218,7 +218,7 @@ and none is needed.
|
||||
## Sources
|
||||
|
||||
- This project's own CI runs and the documented environment variables
|
||||
(`INVISIBLE_PLAYWRIGHT_CACHE_DIR`, `STEALTHFOX_GITHUB_TOKEN`, `INVPW_BINARY_PATH`) on
|
||||
(`INVISIBLE_PLAYWRIGHT_CACHE_DIR`, `STEALTHFOX_GITHUB_TOKEN`) on
|
||||
the [configuration](configuration.md) page.
|
||||
- The exit-address reading taken from inside a headless runner job, compared against the
|
||||
same script run from a residential connection.
|
||||
|
||||
+3
-3
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.52.1"
|
||||
version = "0.55.0"
|
||||
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==64.71.0",
|
||||
"invisible_core==66.76.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
|
||||
@@ -118,7 +118,7 @@ dependencies = [
|
||||
|
||||
[project.optional-dependencies]
|
||||
remote = ["websockets>=13"]
|
||||
dev = ["websockets>=13", "aioquic>=1.2", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41", "h2>=4,<5"]
|
||||
dev = ["websockets>=13", "aioquic>=1.2", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41", "h2>=4,<5"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
markers = [
|
||||
|
||||
@@ -23,7 +23,6 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import socketserver
|
||||
import sys
|
||||
@@ -32,19 +31,6 @@ import threading
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
|
||||
# ⛔ THE DRIVER ARM IMPORTS AN OLDER TREE, and the line above would otherwise
|
||||
# beat it. `INVPW_DRIVER_TREE` names a git worktree at the last commit that
|
||||
# carried the Node driver, and on the driver arm that tree's package has to WIN
|
||||
# the import - a `PYTHONPATH` from the caller does not, because the insert
|
||||
# above runs afterwards and goes in front of it.
|
||||
#
|
||||
# ⛔ Only the PACKAGE comes from there. This recorder stays this tree's: two
|
||||
# traces produced by two different instruments measure the instruments, which
|
||||
# is the mistake the comparison exists to avoid.
|
||||
if (os.environ.get("INVPW_TRANSPORT") == "driver"
|
||||
and os.environ.get("INVPW_DRIVER_TREE")):
|
||||
sys.path.insert(0, str(pathlib.Path(os.environ["INVPW_DRIVER_TREE"]) / "src"))
|
||||
|
||||
PAGE = b"""<!doctype html><html><head><title>capture</title></head><body>
|
||||
<button id=b onclick="this.textContent='clicked'">press</button>
|
||||
<input id=f>
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""The preloaded-intermediates list of a CI leg: a fixed (empty) file of the repository, and the variable that makes the core use it.
|
||||
|
||||
python scripts/ci_lab_intermediates.py set [--pin ci/intermediates.pin.json] # checks the file against the pin, exports STEALTHFOX_INTERMEDIATES
|
||||
|
||||
Why this exists: without ``STEALTHFOX_INTERMEDIATES`` the core downloads Mozilla's intermediates list on a cold cache (in line, at the first launch or at
|
||||
`invisible_playwright fetch`) and asks once a week whether it changed, from the python of the test. A CI leg reaches no site for its data and every run has to
|
||||
have the same bytes, so the leg launches with ``ci/intermediates.json``: a valid list in the engine's format 1 with no certificate. With the variable set the
|
||||
core neither downloads nor checks, ever. ``ci/intermediates.pin.json`` holds the sha256 of the file: ``set`` refuses to go on when the file is not that.
|
||||
|
||||
``set`` writes ``STEALTHFOX_INTERMEDIATES=<absolute path>`` to ``$GITHUB_ENV`` (every later step of the job sees it) and, when there is no
|
||||
``$GITHUB_ENV``, to stdout. The paths of the pin are relative to the repository, not to the working directory of the caller.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ENV = "STEALTHFOX_INTERMEDIATES"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def sha256_of(path) -> str:
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def load_pin(path) -> dict:
|
||||
try:
|
||||
pin = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise Refused("the pin %s cannot be read: %s" % (path, exc))
|
||||
sha = pin.get("sha256") if isinstance(pin, dict) else None
|
||||
if not isinstance(sha, str) or len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
|
||||
raise Refused("the pin %s has no sha256 that is a sha256" % path)
|
||||
if not isinstance(pin.get("file"), str) or not pin["file"]:
|
||||
raise Refused("the pin %s names no file" % path)
|
||||
return pin
|
||||
|
||||
|
||||
def resolve(pin: dict, pin_path) -> Path:
|
||||
"""The file the pin names, checked against its sha256: a file that is not the pinned one is refused."""
|
||||
target = Path(pin["file"])
|
||||
if not target.is_absolute():
|
||||
target = ROOT / target
|
||||
if not target.is_file():
|
||||
raise Refused("the file %s of the pin cannot be found" % pin["file"])
|
||||
got = sha256_of(target)
|
||||
if got != pin["sha256"]:
|
||||
raise Refused("%s has sha256 %s, the pin says %s: change both in one commit" % (pin["file"], got, pin["sha256"]))
|
||||
return target.resolve()
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
s = sub.add_parser("set")
|
||||
s.add_argument("--pin", default="ci/intermediates.pin.json")
|
||||
ns = ap.parse_args(argv)
|
||||
try:
|
||||
path = resolve(load_pin(ns.pin), ns.pin)
|
||||
except Refused as exc:
|
||||
print("ci_lab_intermediates: %s" % exc, file=sys.stderr)
|
||||
return 1
|
||||
line = "%s=%s" % (ENV, path)
|
||||
env_file = os.environ.get("GITHUB_ENV")
|
||||
if env_file:
|
||||
with open(env_file, "a", encoding="utf-8", newline="\n") as fh:
|
||||
fh.write(line + "\n")
|
||||
else:
|
||||
print(line)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -93,7 +93,7 @@ def product_download(cache: Path) -> Path:
|
||||
"""The core's own road: no variable, a cold cache."""
|
||||
os.environ.pop(lab.ENV, None)
|
||||
os.environ["INVISIBLE_PLAYWRIGHT_CACHE_DIR"] = str(cache)
|
||||
from invisible_core.download import ensure_geoip_mmdb
|
||||
from invisible_core import ensure_geoip_mmdb
|
||||
|
||||
return Path(ensure_geoip_mmdb())
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The reviewed list of the check that keeps third parties out of the verdict of the e2e tests (``tests/gates/e2e_clock_exceptions.json``).
|
||||
|
||||
python scripts/e2e_clock_exceptions.py # what the list says and what the sources say: counts by class, and every difference
|
||||
python scripts/e2e_clock_exceptions.py --write # make the ``debt`` again: every occurrence no ``entries`` item covers (a correction removed some)
|
||||
python scripts/e2e_clock_exceptions.py --write --prune # and drop the ``entries`` that match nothing any more
|
||||
|
||||
``entries`` are the occurrences a person reviewed and decided are deliberate (each has a closed ``kind`` and a ``reason``); ``--write`` never adds one. ``debt`` is every
|
||||
other occurrence: the dangerous ones, not yet corrected. It is made from the sources, so it is regenerated, not edited: when a branch that corrects tests merges, run
|
||||
``--write`` and the corrected occurrences leave the list. A list that grows is refused by ``tests/test_the_e2e_tests_do_not_wait_on_clocks.py`` (against main).
|
||||
Exit 1 when the file on disk is not what ``--write`` would write.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
import _e2e_clocks as clocks # noqa: E402
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
ap.add_argument("--write", action="store_true", help="write the file with the debt made again")
|
||||
ap.add_argument("--prune", action="store_true", help="with --write: drop the entries that match no occurrence")
|
||||
ns = ap.parse_args(argv)
|
||||
found = clocks.scan()
|
||||
path = clocks.GATE_FILE
|
||||
document = clocks.load(path) if path.is_file() else clocks.empty_document()
|
||||
made = clocks.regenerate(document, found, prune_entries=ns.prune)
|
||||
text = clocks.dump(made)
|
||||
differences = clocks.compare(found, document)
|
||||
by_class = collections.Counter(i["class"] for i in made["debt"]) # type: ignore[index, union-attr]
|
||||
kinds = collections.Counter(i["kind"] for i in made["entries"]) # type: ignore[index, union-attr]
|
||||
print("entries: %d %s" % (len(made["entries"]), dict(sorted(kinds.items())))) # type: ignore[arg-type]
|
||||
print("debt: %d %s" % (len(made["debt"]), dict(sorted(by_class.items())))) # type: ignore[arg-type]
|
||||
for name in ("new", "stale_entries", "stale_debt", "both"):
|
||||
for key in differences[name]:
|
||||
print(" %-13s %s" % (name, key))
|
||||
if ns.write:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8", newline="\n")
|
||||
print("written: %s" % path.relative_to(ROOT))
|
||||
return 0
|
||||
if not path.is_file() or path.read_text(encoding="utf-8") != text:
|
||||
print("%s is not what --write makes" % path.relative_to(ROOT), file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Point this clone's git hooks at .githooks/, so the pre-push gates are armed.
|
||||
|
||||
Back-compat shim. The implementation is `invisible_core.hooks.install_main`,
|
||||
moved there on 2026-07-27 because it existed here and therefore existed for ONE
|
||||
of the three repositories: the other two shipped a hook that nothing armed, and
|
||||
nothing checked was armed, so a fresh clone of either had no gates at all and no
|
||||
way to notice. Same asymmetry, and the same fix, as the publish gate.
|
||||
|
||||
python scripts/install_hooks.py # arm this clone
|
||||
python scripts/install_hooks.py --check # exit 1 if it is not armed
|
||||
|
||||
Nobody has to remember: a test in each repo fails in a checkout whose hooksPath
|
||||
is not set, and prints this command. The suite is the reminder, and it runs on
|
||||
its own.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
# No src insert: this repo pins invisible-core exactly, so the shared
|
||||
# implementation is simply importable.
|
||||
|
||||
from invisible_core.hooks import install_main # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(install_main(sys.argv[1:], root=ROOT))
|
||||
@@ -0,0 +1,342 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The judge of the real-sites round (stdlib only).
|
||||
|
||||
``scripts/run_real_sites.py`` visits the list of ``tests/realsites/sites.json`` with ONE browser and writes the cells of that pass. This file reads the cells of
|
||||
the two browsers (stock Firefox driven by stock Playwright, and the published wrapper: "ours") and says whether the wrapper got through where stock did.
|
||||
|
||||
A cell is what one visit of one site gave:
|
||||
|
||||
{"load": "ok" | "timeout" | "error:<type>", "networkidle": "ok" | "timeout", "status": "2xx" | "3xx" | "4xx" | "5xx" | "none",
|
||||
"marker": true | false, "canary": "ok" | "no"}
|
||||
|
||||
It is GOOD when the load is ok, networkidle is ok, the status is 2xx, the marker is there and the canary page, visited right after, reached networkidle.
|
||||
|
||||
The rule, per site, over the runs that are available for that site:
|
||||
|
||||
* RED: stock is good in all three runs and ours is not good in at least two of the three;
|
||||
* INCOMPLETE: a cell that differs in the first pass (one browser good, the other not) must have three runs per browser; without them it is not a red cell but a
|
||||
problem, "giro incompleto" (the job is red, the round's fault);
|
||||
* NO INFORMATION: stock is not good in every run (a site that blocks, has fallen or has changed). Never red. The outcome of ours is still reported, as data;
|
||||
* the job is RED when a cell is red or incomplete, when a site of the list was not visited by both browsers, when the list has no sites, or when fewer cells carry
|
||||
information than half the sites, rounded up (``information_minimum``: 8 of 15; "il giro non ha misurato": the round is broken, not the wrapper; an empty round is
|
||||
never green). The minimum is not a field of the file and is not sampled: a failure of stock only removes information from its cell, and never gives blame.
|
||||
|
||||
THE RUNS. ``judge(stock_runs, ours_runs, sites)`` takes lists of runs; a run is the dict ``{site id: cell}`` of one pass. The workflow supplies, per browser, the first
|
||||
pass over the whole list (``<browser>-1.json``) and, only for the
|
||||
sites whose first-pass cells differ (``differing``: one browser good and the other not), two more passes of those sites alone, in the order stock, ours, stock,
|
||||
ours (``<browser>-2.json``, ``<browser>-3.json``). A site is "visited" when it is in the FIRST pass of each browser; a site absent from a later pass is only a
|
||||
site that did not differ. A cell that did not differ has one run each: good and good is green, and bad and bad is no information.
|
||||
|
||||
The function is pure (no file, no clock, no network): ``main`` reads the files and writes the summary.
|
||||
|
||||
judge_real_sites.py judge --sites tests/realsites/sites.json --stock FILE... --ours FILE... [--summary summary.md] [--result result.json]
|
||||
judge_real_sites.py differing --sites tests/realsites/sites.json --stock FILE --ours FILE (ids of the cells that differ, one comma-joined line)
|
||||
judge_real_sites.py admit --sites tests/realsites/sites.json --os LABEL FILE... [--os LABEL FILE...] [--summary admission.md]
|
||||
exit 1 only for a defect of the list, never for the luck of one site: an invalid list (a ``min_informative`` in the file is one), a pass that is missing, a
|
||||
site never good in any pass on a system and not of the class protetta, more than 4 protetta, more than 20 sites. A site good in some passes stays, with its
|
||||
count per system. 0 for an empty list.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
#: What a good cell is, field by field.
|
||||
GOOD = {"load": "ok", "networkidle": "ok", "status": "2xx", "marker": True, "canary": "ok"}
|
||||
FIELDS = tuple(GOOD)
|
||||
CLASSES = ("calma", "giornale", "negozio", "applicazione", "protetta")
|
||||
#: A cell that differs in the first pass has this many runs of each browser; without them the round is incomplete (its fault, not a red cell).
|
||||
RUNS_OF_A_DIFFERING_CELL = 3
|
||||
#: Red: stock good in every one of its three runs and ours not good in at least this many of its three.
|
||||
BAD_RUNS_FOR_RED = 2
|
||||
#: A list has at most this many sites, of which at most MAX_PROTECTED are of the class PROTECTED (kept as data: stock may be blocked there).
|
||||
MAX_KEPT = 20
|
||||
MAX_PROTECTED = 4
|
||||
PROTECTED = "protetta"
|
||||
NOT_MEASURED = "il giro non ha misurato"
|
||||
STATE_LABEL = {"red": "red", "green": "green", "no_information": "no information", "missing": "missing", "incomplete": "incomplete"}
|
||||
SITE_ID = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Judgement:
|
||||
verdict: str # "green" or "red": one per job
|
||||
exit_code: int # 0 or 1
|
||||
table: list # one row per site of the list, in its order
|
||||
informative: int # cells with information (stock good in every run)
|
||||
red: int # red cells
|
||||
ours_good_stock_not: int # cells where ours is good in every run and stock is not (data, not a verdict)
|
||||
problems: list = field(default_factory=list)
|
||||
|
||||
|
||||
def is_good(cell) -> bool:
|
||||
return isinstance(cell, dict) and all(cell.get(name) == want for name, want in GOOD.items())
|
||||
|
||||
|
||||
def _why(cells) -> str:
|
||||
"""What was not good, named once per field and value, over the runs: ``load=timeout, status=4xx``; empty when every run was good."""
|
||||
seen = []
|
||||
for cell in cells:
|
||||
if is_good(cell):
|
||||
continue
|
||||
if not isinstance(cell, dict):
|
||||
notes = ["cell=unreadable"]
|
||||
else:
|
||||
notes = ["%s=%s" % (name, str(cell.get(name)).lower()) for name, want in GOOD.items() if cell.get(name) != want]
|
||||
seen += [note for note in notes if note not in seen]
|
||||
return ", ".join(seen)
|
||||
|
||||
|
||||
def _side(cells) -> dict:
|
||||
return {"runs": len(cells), "good": sum(1 for c in cells if is_good(c)), "why": _why(cells)}
|
||||
|
||||
|
||||
def _cells(runs, site_id) -> list:
|
||||
return [run[site_id] for run in runs if isinstance(run, dict) and site_id in run]
|
||||
|
||||
|
||||
def _visited(runs, site_id) -> bool:
|
||||
return bool(runs) and isinstance(runs[0], dict) and site_id in runs[0]
|
||||
|
||||
|
||||
def information_minimum(site_count) -> int:
|
||||
"""The cells that must carry information for the round to have measured: half the sites, rounded up."""
|
||||
return (site_count + 1) // 2
|
||||
|
||||
|
||||
def judge(stock_runs, ours_runs, sites) -> Judgement:
|
||||
"""The verdict, the table and the exit code of one job. Pure: it reads only its arguments and changes none of them."""
|
||||
table, problems = [], []
|
||||
informative = red = ours_good_stock_not = 0
|
||||
for site in sites:
|
||||
site_id = site["id"]
|
||||
base = {"id": site_id, "class": site.get("class", "")}
|
||||
missing = [name for name, runs in (("stock", stock_runs), ("ours", ours_runs)) if not _visited(runs, site_id)]
|
||||
stock, ours = _side(_cells(stock_runs, site_id)), _side(_cells(ours_runs, site_id))
|
||||
if missing:
|
||||
problems += ["%s was not visited by %s" % (site_id, name) for name in missing]
|
||||
table.append({**base, "state": "missing", "stock": stock, "ours": ours})
|
||||
continue
|
||||
differs = is_good(stock_runs[0][site_id]) != is_good(ours_runs[0][site_id])
|
||||
if differs and min(stock["runs"], ours["runs"]) < RUNS_OF_A_DIFFERING_CELL:
|
||||
problems.append("giro incompleto: %s differs in the first pass and has %d runs of stock and %d of ours, %d each are needed"
|
||||
% (site_id, stock["runs"], ours["runs"], RUNS_OF_A_DIFFERING_CELL))
|
||||
table.append({**base, "state": "incomplete", "stock": stock, "ours": ours})
|
||||
continue
|
||||
if stock["good"] != stock["runs"]:
|
||||
state = "no_information"
|
||||
if ours["good"] == ours["runs"]:
|
||||
ours_good_stock_not += 1
|
||||
else:
|
||||
informative += 1
|
||||
not_good = ours["runs"] - ours["good"]
|
||||
if not_good >= BAD_RUNS_FOR_RED:
|
||||
state = "red"
|
||||
red += 1
|
||||
problems.append("%s is red: stock was good in %d of %d runs and ours in %d of %d (%s)"
|
||||
% (site_id, stock["good"], stock["runs"], ours["good"], ours["runs"], ours["why"] or "no reason read"))
|
||||
else:
|
||||
state = "green"
|
||||
table.append({**base, "state": state, "stock": stock, "ours": ours})
|
||||
if not sites:
|
||||
problems.append("%s: the list has no sites" % NOT_MEASURED)
|
||||
elif informative < information_minimum(len(sites)):
|
||||
problems.append("%s: %d cells with information of %d sites, the minimum is %d" % (NOT_MEASURED, informative, len(sites), information_minimum(len(sites))))
|
||||
code = 1 if problems else 0
|
||||
return Judgement("red" if code else "green", code, table, informative, red, ours_good_stock_not, problems)
|
||||
|
||||
|
||||
def differing_sites(stock_first, ours_first, sites) -> list:
|
||||
"""The ids, in the order of the list, whose first-pass cells differ in being good: the ones that get two more runs of each browser."""
|
||||
return [site["id"] for site in sites
|
||||
if site["id"] in stock_first and site["id"] in ours_first and is_good(stock_first[site["id"]]) != is_good(ours_first[site["id"]])]
|
||||
|
||||
|
||||
def admission(runs_by_os, sites, expected_runs=5) -> dict:
|
||||
"""The passes of stock alone, ``expected_runs`` per system, counted per site and system: how many were good. Only the five fields of a cell count: what a pass
|
||||
adds to diagnose a marker (``diagnosis``) is not part of the outcome. A site good in some passes is not a defect, whatever its count: a rare failure of stock
|
||||
is every real site's, and it only removes information from the round."""
|
||||
report = {"problems": [], "expected_runs": expected_runs}
|
||||
for label, runs in runs_by_os.items():
|
||||
if len(runs) != expected_runs:
|
||||
report["problems"].append("%s: %d passes of stock, %d expected" % (label, len(runs), expected_runs))
|
||||
rows = []
|
||||
for site in sites:
|
||||
cells = _cells(runs, site["id"])
|
||||
rows.append({"id": site["id"], "class": site.get("class", ""), "good": sum(1 for c in cells if is_good(c)), "runs": len(runs), "why": _why(cells)})
|
||||
report[label] = {"rows": rows}
|
||||
report["labels"] = list(runs_by_os)
|
||||
return report
|
||||
|
||||
|
||||
def admission_problems(report, sites) -> list:
|
||||
"""What makes the admission red: a defect of the list, never the luck of one site. A pass that is missing; a site never good in any pass of a system and not of the
|
||||
class protetta (a wrong marker, or a fixed block); more than MAX_PROTECTED sites of the class protetta; more than MAX_KEPT sites. (An invalid list is refused
|
||||
when it is read.) An empty list is not asked anything: there is nothing to admit."""
|
||||
if not sites:
|
||||
return []
|
||||
out = list(report["problems"])
|
||||
for label in report["labels"]:
|
||||
out += ["%s: never good on %s%s" % (r["id"], label, " (%s)" % r["why"] if r["why"] else "")
|
||||
for r in report[label]["rows"] if r["good"] == 0 and r["class"] != PROTECTED]
|
||||
protected = sum(1 for site in sites if site.get("class") == PROTECTED)
|
||||
if protected > MAX_PROTECTED:
|
||||
out.append("%d sites of the class %s, more than %d" % (protected, PROTECTED, MAX_PROTECTED))
|
||||
if len(sites) > MAX_KEPT:
|
||||
out.append("%d sites, more than %d" % (len(sites), MAX_KEPT))
|
||||
return out
|
||||
|
||||
|
||||
def validate_sites(sites) -> list:
|
||||
"""The problems of a list: every site has an id (unique, lowercase letters, digits and hyphens), an https url, a marker and one of the five classes. Given the
|
||||
whole file (a dict) it also refuses a ``min_informative``: the minimum is computed by the judge from the number of sites and is not written anywhere."""
|
||||
out, seen = [], set()
|
||||
if isinstance(sites, dict):
|
||||
if "min_informative" in sites:
|
||||
out.append("min_informative is not a field of the list: the judge computes the minimum (half the sites, rounded up)")
|
||||
sites = sites.get("sites", [])
|
||||
if not isinstance(sites, list):
|
||||
return out + ["the sites are not a list"]
|
||||
for i, site in enumerate(sites):
|
||||
if not isinstance(site, dict):
|
||||
out.append("site %d is not an object" % i)
|
||||
continue
|
||||
site_id = site.get("id")
|
||||
if not isinstance(site_id, str) or not SITE_ID.match(site_id):
|
||||
out.append("site %d: the id %r is not lowercase letters, digits and hyphens" % (i, site_id))
|
||||
elif site_id in seen:
|
||||
out.append("site %d: the id %r is used twice" % (i, site_id))
|
||||
seen.add(site_id)
|
||||
for name in ("url", "marker"):
|
||||
if not isinstance(site.get(name), str) or not site[name].strip():
|
||||
out.append("%s: no %s" % (site_id, name))
|
||||
if isinstance(site.get("url"), str) and site["url"].strip() and not site["url"].startswith("https://"):
|
||||
out.append("%s: the url is not https" % site_id)
|
||||
if site.get("class") not in CLASSES:
|
||||
out.append("%s: the class %r is not one of %s" % (site_id, site.get("class"), ", ".join(CLASSES)))
|
||||
return out
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------------------ the summary
|
||||
def _side_text(side) -> str:
|
||||
if side["runs"] == 0:
|
||||
return "not visited"
|
||||
text = "%d/%d good" % (side["good"], side["runs"])
|
||||
return text + (" (%s)" % side["why"]) if side["why"] else text
|
||||
|
||||
|
||||
def render_markdown(result: Judgement) -> str:
|
||||
lines = ["## Real sites: ours against stock", "",
|
||||
"**Verdict: %s**" % result.verdict, "",
|
||||
"- informative cells: %d" % result.informative,
|
||||
"- red cells: %d" % result.red,
|
||||
"- ours good, stock not: %d (data, not a verdict)" % result.ours_good_stock_not, ""]
|
||||
if result.problems:
|
||||
lines += ["### Problems", ""] + ["- " + p for p in result.problems] + [""]
|
||||
lines += ["| site | class | stock | ours | state |", "|---|---|---|---|---|"]
|
||||
for r in result.table:
|
||||
lines.append("| %s | %s | %s | %s | %s |" % (r["id"], r["class"], _side_text(r["stock"]), _side_text(r["ours"]), STATE_LABEL[r["state"]]))
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def render_admission(report: dict, verdict_problems=()) -> str:
|
||||
labels = report.get("labels", [])
|
||||
lines = ["## Admission of the list: stock, %d passes per system" % report.get("expected_runs", 0), ""]
|
||||
sites = [r for r in report[labels[0]]["rows"]] if labels else []
|
||||
lines += ["| site | class | " + " | ".join(labels) + " | note |", "|---|---|" + "---|" * len(labels) + "---|"]
|
||||
for index, site in enumerate(sites):
|
||||
counts, notes = [], []
|
||||
for label in labels:
|
||||
r = report[label]["rows"][index]
|
||||
counts.append("%d of %d on %s" % (r["good"], r["runs"], label))
|
||||
if r["good"] == 0 and r["class"] == PROTECTED:
|
||||
notes.append("never good on %s, kept as data" % label)
|
||||
elif r["good"] == 0:
|
||||
notes.append("never good on %s" % label)
|
||||
lines.append("| %s | %s | %s | %s |" % (site["id"], site["class"], " | ".join(counts), "; ".join(notes)))
|
||||
shown = [(label, r) for label in labels for r in report[label]["rows"] if r["good"] < r["runs"] and r["why"]]
|
||||
if shown:
|
||||
lines += ["", "What stock showed where it was not good (the cells of the passes also hold the status, the title and the first ids of the page where the marker was not found):", ""]
|
||||
lines += ["- %s, %s: %s" % (label, r["id"], r["why"]) for label, r in shown]
|
||||
if report["problems"]:
|
||||
lines += ["", "### Problems", ""] + ["- " + p for p in report["problems"]]
|
||||
lines += ["", "**Verdict: %s**" % ("red" if verdict_problems else "green")]
|
||||
lines += ["- " + p for p in verdict_problems]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------------------ the files
|
||||
def _read_json(path):
|
||||
return json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _read_sites(path):
|
||||
data = _read_json(path)
|
||||
problems = validate_sites(data)
|
||||
sites = data.get("sites", []) if not problems else []
|
||||
if problems:
|
||||
raise SystemExit("the list of sites is not valid:\n " + "\n ".join(problems))
|
||||
return data, sites
|
||||
|
||||
|
||||
def _cells_of(path) -> dict:
|
||||
data = _read_json(path)
|
||||
cells = data.get("cells") if isinstance(data, dict) else None
|
||||
if not isinstance(cells, dict):
|
||||
raise SystemExit("%s holds no cells" % path)
|
||||
return cells
|
||||
|
||||
|
||||
def _write(path, text):
|
||||
Path(path).write_text(text, encoding="utf-8", newline="\n")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
p_judge = sub.add_parser("judge")
|
||||
p_judge.add_argument("--sites", required=True)
|
||||
p_judge.add_argument("--stock", nargs="+", required=True, help="the files of the passes of stock, the first pass first")
|
||||
p_judge.add_argument("--ours", nargs="+", required=True, help="the files of the passes of ours, the first pass first")
|
||||
p_judge.add_argument("--summary")
|
||||
p_judge.add_argument("--result")
|
||||
p_diff = sub.add_parser("differing")
|
||||
p_diff.add_argument("--sites", required=True)
|
||||
p_diff.add_argument("--stock", required=True)
|
||||
p_diff.add_argument("--ours", required=True)
|
||||
p_admit = sub.add_parser("admit")
|
||||
p_admit.add_argument("--sites", required=True)
|
||||
p_admit.add_argument("--os", nargs="+", action="append", required=True, metavar="LABEL FILE", help="a system label, then its passes of stock")
|
||||
p_admit.add_argument("--expected-runs", type=int, default=5)
|
||||
p_admit.add_argument("--summary")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
data, sites = _read_sites(args.sites)
|
||||
if args.command == "differing":
|
||||
print(",".join(differing_sites(_cells_of(args.stock), _cells_of(args.ours), sites)))
|
||||
return 0
|
||||
if args.command == "admit":
|
||||
report = admission({group[0]: [_cells_of(f) for f in group[1:]] for group in args.os}, sites, args.expected_runs)
|
||||
problems = admission_problems(report, sites)
|
||||
text = render_admission(report, problems)
|
||||
if args.summary:
|
||||
_write(args.summary, text)
|
||||
print(text)
|
||||
return 1 if problems else 0
|
||||
result = judge([_cells_of(f) for f in args.stock], [_cells_of(f) for f in args.ours], sites)
|
||||
text = render_markdown(result)
|
||||
if args.summary:
|
||||
_write(args.summary, text)
|
||||
if args.result:
|
||||
_write(args.result, json.dumps({"verdict": result.verdict, "exit_code": result.exit_code, "informative": result.informative, "red": result.red,
|
||||
"ours_good_stock_not": result.ours_good_stock_not, "problems": result.problems, "table": result.table}, indent=2) + "\n")
|
||||
print(text)
|
||||
return result.exit_code
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One pass over the list of real sites with ONE browser, and the cells it gave, in a JSON file. No judgement is made here (scripts/judge_real_sites.py does it).
|
||||
|
||||
run_real_sites.py --browser stock --out cells/stock-1.json # stock Firefox driven by stock Playwright
|
||||
run_real_sites.py --browser ours --out cells/ours-1.json # the published wrapper (invisible_playwright)
|
||||
|
||||
One browser, one context and one page are reused for the whole list: it is how a client uses the package. For every site of ``tests/realsites/sites.json``:
|
||||
|
||||
1. ``goto`` with the wait ``load``;
|
||||
2. the wait ``networkidle``;
|
||||
3. the marker (a CSS selector that matches only when the real page arrived), and the HTTP status of the document;
|
||||
4. the canary: a quiet page served by this script on 127.0.0.1, visited on the same page, which must reach ``networkidle`` (a state that survives the
|
||||
navigation, a request that never ends, a route left behind, makes it fail).
|
||||
|
||||
The cell of a site:
|
||||
|
||||
load "ok" | "timeout" | "error:<type>" the ``goto`` (the type is the engine's NS_ERROR_* name when it gives one, else the exception class)
|
||||
networkidle "ok" | "timeout" the wait for ``networkidle`` after the load
|
||||
status "2xx" | "3xx" | "4xx" | "5xx" | "none" the last response of the main document (a redirect chain is read to its end)
|
||||
marker true | false
|
||||
canary "ok" | "no"
|
||||
|
||||
No time is measured or asserted: the waits are Playwright's own, with the same limits for both browsers (``--load-timeout``, ``--idle-timeout``). Both browsers
|
||||
are launched with a window, at the same viewport, with no proxy and with the language of the runner (no locale is passed to either).
|
||||
|
||||
No click and no handling of a consent wall: both browsers see what the page shows. ``--diagnose`` (the admission of a list, stock alone) adds to the cell, where
|
||||
the marker was not found, a ``diagnosis`` of the document: its HTTP status, its title and the first 40 element ids, to fix the marker. It is a note for the person
|
||||
who reads the file: the judge ignores it.
|
||||
|
||||
``--binary`` (the engine to drive) and ``--core-ref`` (the core the engine was built with) are accepted for the round of a candidate; ``--binary`` is passed to
|
||||
the launch when given and ``--core-ref`` is only written into the file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import http.server
|
||||
import json
|
||||
import platform
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from importlib import metadata
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_SITES = ROOT / "tests" / "realsites" / "sites.json"
|
||||
CANARY_PAGE = b"<!doctype html><html><head><meta charset=utf-8><title>canary</title></head><body><p id=canary>quiet</p></body></html>"
|
||||
ENGINE_ERROR = re.compile(r"\b(NS_[A-Z0-9_]+)\b")
|
||||
|
||||
|
||||
class _Canary(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802 (the name the server calls)
|
||||
if self.path.split("?", 1)[0] == "/canary":
|
||||
body, status, kind = CANARY_PAGE, 200, "text/html; charset=utf-8"
|
||||
else:
|
||||
body, status, kind = b"", 204, "text/plain"
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", kind)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *_args): # quiet
|
||||
pass
|
||||
|
||||
|
||||
def serve_canary():
|
||||
"""The quiet page, on a free port of the loopback: returns the server (to shut down) and the URL of the page."""
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Canary)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, "http://127.0.0.1:%d/canary" % server.server_address[1]
|
||||
|
||||
|
||||
def status_class(code) -> str:
|
||||
return "none" if not isinstance(code, int) or not 200 <= code <= 599 else "%dxx" % (code // 100)
|
||||
|
||||
|
||||
def load_error(exc: BaseException) -> str:
|
||||
"""``error:<type>``: the engine's own name for the failure when the message carries one, else the exception class."""
|
||||
found = ENGINE_ERROR.search(str(exc))
|
||||
return "error:" + (found.group(1) if found else type(exc).__name__)
|
||||
|
||||
|
||||
def read_sites(path, only=None):
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
sites = data.get("sites", [])
|
||||
if only:
|
||||
wanted = [s for s in only.split(",") if s]
|
||||
known = {s["id"] for s in sites}
|
||||
unknown = [s for s in wanted if s not in known]
|
||||
if unknown:
|
||||
raise SystemExit("not in the list: " + ", ".join(unknown))
|
||||
sites = [s for s in sites if s["id"] in wanted]
|
||||
return sites
|
||||
|
||||
|
||||
def visit(page, state, site, canary_url, timeouts, errors, diagnose=False):
|
||||
"""One visit of one site on the reused page, then the canary. Returns the cell."""
|
||||
PWError, PWTimeout = errors
|
||||
load_ms, idle_ms = timeouts
|
||||
state["status"] = None
|
||||
cell = {"load": "ok", "networkidle": "ok", "status": "none", "marker": False, "canary": "no"}
|
||||
response = None
|
||||
try:
|
||||
response = page.goto(site["url"], wait_until="load", timeout=load_ms)
|
||||
except PWTimeout:
|
||||
cell["load"] = "timeout"
|
||||
except PWError as exc:
|
||||
cell["load"] = load_error(exc)
|
||||
except Exception as exc: # a driver that fails is a cell, not the end of the pass
|
||||
cell["load"] = load_error(exc)
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=idle_ms)
|
||||
except Exception:
|
||||
cell["networkidle"] = "timeout"
|
||||
try:
|
||||
cell["marker"] = page.locator(site["marker"]).count() > 0
|
||||
except Exception:
|
||||
cell["marker"] = False
|
||||
code = response.status if response is not None else state["status"]
|
||||
cell["status"] = status_class(code)
|
||||
if diagnose and not cell["marker"]:
|
||||
cell["diagnosis"] = diagnosis(page, code)
|
||||
cell["canary"] = canary(page, canary_url, timeouts, errors)
|
||||
return cell
|
||||
|
||||
|
||||
def diagnosis(page, code) -> dict:
|
||||
"""What the document is, for fixing a marker: its HTTP status, its title and the first 40 ids of its elements. Read, never judged."""
|
||||
out = {"http_status": code, "title": None, "ids": []}
|
||||
try:
|
||||
out["title"] = page.title()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
ids = page.evaluate("() => Array.from(document.querySelectorAll('[id]')).map(e => e.id).filter(i => i).slice(0, 40)")
|
||||
out["ids"] = [i for i in ids if isinstance(i, str) and i][:40]
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def canary(page, canary_url, timeouts, errors):
|
||||
load_ms, idle_ms = timeouts
|
||||
try:
|
||||
page.goto(canary_url, wait_until="load", timeout=load_ms)
|
||||
page.wait_for_load_state("networkidle", timeout=idle_ms)
|
||||
return "ok" if page.locator("#canary").count() == 1 else "no"
|
||||
except Exception:
|
||||
return "no"
|
||||
|
||||
|
||||
def run_pass(browser, sites, canary_url, timeouts, errors, viewport, cells, diagnose=False):
|
||||
context = browser.new_context(viewport=viewport)
|
||||
page = context.new_page()
|
||||
state = {"status": None}
|
||||
|
||||
def on_response(response):
|
||||
try:
|
||||
if response.request.is_navigation_request() and response.request.frame == page.main_frame:
|
||||
state["status"] = response.status
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
page.on("response", on_response)
|
||||
try:
|
||||
for site in sites:
|
||||
cells[site["id"]] = visit(page, state, site, canary_url, timeouts, errors, diagnose)
|
||||
print("%s %s" % (site["id"], json.dumps(cells[site["id"]], sort_keys=True)), flush=True)
|
||||
finally:
|
||||
context.close()
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
parser.add_argument("--browser", choices=("stock", "ours"), required=True)
|
||||
parser.add_argument("--out", required=True, help="the JSON file of the cells")
|
||||
parser.add_argument("--sites", default=str(DEFAULT_SITES))
|
||||
parser.add_argument("--only", help="comma-separated site ids: visit these sites alone (the later passes of the cells that differ)")
|
||||
parser.add_argument("--binary", help="the engine (ours) or Firefox (stock) to drive, for the round of a candidate")
|
||||
parser.add_argument("--core-ref", help="the core the engine was built with; only written into the file")
|
||||
parser.add_argument("--load-timeout", type=int, default=30000, help="ms, the limit of goto with the wait load")
|
||||
parser.add_argument("--idle-timeout", type=int, default=15000, help="ms, the limit of the wait for networkidle")
|
||||
parser.add_argument("--diagnose", action="store_true", help="where the marker is not found, add the status, the title and the first 40 ids of the document")
|
||||
parser.add_argument("--viewport", default="1280x720")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
width, height = (int(n) for n in args.viewport.lower().split("x"))
|
||||
viewport = {"width": width, "height": height}
|
||||
sites = read_sites(args.sites, args.only)
|
||||
timeouts = (args.load_timeout, args.idle_timeout)
|
||||
|
||||
# Each mode imports its own package and no other: the venv of ours holds invisible-playwright (its client is vendored, there is no `playwright` in it), the venv of
|
||||
# stock holds playwright. The errors of ours are the ones its client raises: invisible_playwright.sync_api exports the classes of
|
||||
# invisible_playwright/_pw/_impl/_errors.py, which the waiter of a navigation raises on a timeout (_pw/_impl/_waiter.py reject_on_timeout) and which the answer of
|
||||
# the server is turned into by parse_error (_pw/_impl/_helper.py), so an `except TimeoutError` here catches what goto and wait_for_load_state raise.
|
||||
server, canary_url = serve_canary()
|
||||
meta = {"browser": args.browser, "os": platform.system().lower(), "python": platform.python_version(),
|
||||
"binary": args.binary, "core_ref": args.core_ref, "viewport": args.viewport, "load_timeout_ms": args.load_timeout,
|
||||
"idle_timeout_ms": args.idle_timeout, "only": args.only}
|
||||
cells, complete = {}, False # filled site by site: a pass that dies keeps what it had, marked incomplete
|
||||
try:
|
||||
if args.browser == "stock":
|
||||
from playwright.sync_api import Error as PWError, TimeoutError as PWTimeout, sync_playwright
|
||||
errors = (PWError, PWTimeout)
|
||||
meta["playwright"] = metadata.version("playwright")
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.launch(headless=False, **({"executable_path": args.binary} if args.binary else {}))
|
||||
try:
|
||||
meta["engine"] = browser.version
|
||||
run_pass(browser, sites, canary_url, timeouts, errors, viewport, cells, args.diagnose)
|
||||
finally:
|
||||
browser.close()
|
||||
else:
|
||||
from invisible_playwright.sync_api import Error as PWError, InvisiblePlaywright, TimeoutError as PWTimeout
|
||||
errors = (PWError, PWTimeout)
|
||||
meta["package"] = metadata.version("invisible-playwright")
|
||||
with InvisiblePlaywright(**({"binary_path": args.binary} if args.binary else {})) as browser:
|
||||
meta["engine"] = browser.version
|
||||
run_pass(browser, sites, canary_url, timeouts, errors, viewport, cells, args.diagnose)
|
||||
complete = True
|
||||
finally:
|
||||
server.shutdown()
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps({**meta, "complete": complete, "order": [s["id"] for s in sites], "cells": cells}, indent=2) + "\n", encoding="utf-8", newline="\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -54,16 +54,6 @@ did so on evidence rather than on the code looking finished:
|
||||
since 0.30.0, with their extractors in the core's `scripts/`), and the four rules
|
||||
the `user.js` writer was compared against (the comparison script and the frozen
|
||||
rules file were later deleted; they are in git history).
|
||||
- ⛔ And the second arm. A comparison between the two transports only exists
|
||||
while there are two implementations to compare, and the scripts that did it
|
||||
were deleted with the driver arm. To get one back:
|
||||
|
||||
git worktree add /tmp/judge <the last commit that carried _driver/>
|
||||
INVPW_DRIVER_TREE=/tmp/judge python scripts/capture_protocol.py <bin>
|
||||
|
||||
A worktree rather than an installed release, because a published wrapper pins
|
||||
a published core and a sealed engine and therefore cannot drive a locally
|
||||
built binary - which is the only kind worth judging.
|
||||
|
||||
### The changes that used to live in the driver bundle
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ Quickstart:
|
||||
``humanize`` is on by default and needs no new API: the ordinary Playwright
|
||||
pointer calls - ``page.click`` / ``page.hover`` / ``locator.click`` /
|
||||
``page.mouse.move`` - move the cursor along a path drawn from ``seed``, so the
|
||||
same seed replays the same motion. ``INVPW_CURSOR_ENGINE=binary`` restores the
|
||||
previous behaviour, where the browser drew the path instead.
|
||||
same seed replays the same motion. ``INVPW_CURSOR_ENGINE=off`` disables the
|
||||
motion process-wide.
|
||||
"""
|
||||
# ── Import-time core assertion, and repair ───────────────────────────────────
|
||||
# Runs BEFORE every other import. Two questions, one check: is the installed
|
||||
@@ -65,7 +65,7 @@ _assert_pw_range()
|
||||
|
||||
from invisible_core import get_default_args, get_default_stealth_prefs
|
||||
from invisible_core import BINARY_VERSION, FIREFOX_UPSTREAM_VERSION
|
||||
from invisible_core import GeoTimezoneError, resolve_session_timezone
|
||||
from invisible_core import GeoTimezoneError
|
||||
from invisible_core import ensure_binary, ensure_geoip_mmdb
|
||||
from .launcher import InvisiblePlaywright
|
||||
from ._juggler.remote import RemoteServer, launch_server, launch_server_async
|
||||
@@ -87,7 +87,6 @@ __all__ = [
|
||||
"ensure_geoip_mmdb",
|
||||
"get_default_stealth_prefs",
|
||||
"get_default_args",
|
||||
"resolve_session_timezone",
|
||||
"GeoTimezoneError",
|
||||
"BINARY_VERSION",
|
||||
"FIREFOX_UPSTREAM_VERSION",
|
||||
|
||||
@@ -15,15 +15,15 @@ What stays here is what has to be decided BEFORE a browser exists, in the
|
||||
caller's process:
|
||||
|
||||
* WHO draws the motion (`resolve_cursor_engine`): this package's Python
|
||||
generator, the browser's own expansion, or nobody. The answer travels to the
|
||||
server in the launch prefs (`_session.build_prefs`), once.
|
||||
generator, or nobody. The answer travels to the server in the launch prefs
|
||||
(`_session.build_prefs`), once.
|
||||
* the motion budget `humanize=<seconds>` implies (`max_seconds_for`);
|
||||
* the page's motion seed, derived from the session seed and the page's number
|
||||
(`page_motion_seed`) - one function for the server that draws from it and for
|
||||
the tests that replay it;
|
||||
* the opt-out for the off-centre landing (`landing_enabled`);
|
||||
* the generator's contract (`_motion_factory`, `_build_profile`), which the
|
||||
server reads here so that a stub put in `_motion_mod` replaces it for both;
|
||||
* the generator's contract (`_motion_factory`), which the server reads here so
|
||||
that a stub put in `_motion_mod` replaces it for both;
|
||||
* ONE wrapper on the client: an EXPLICIT `Mouse.move`. That is the caller's
|
||||
and a server leaves it alone (a Go client's `mouse.move` reaches the page as
|
||||
exactly the point it named), but this client has always walked its own, so it
|
||||
@@ -32,26 +32,22 @@ caller's process:
|
||||
(`enable_for`), so a page of any other session - or a server that is not
|
||||
ours - receives the plain move.
|
||||
|
||||
The escape hatch ``INVPW_CURSOR_ENGINE`` picks who generates the motion:
|
||||
``python`` (default), ``binary`` (the browser's own expansion) or ``off``.
|
||||
``INVPW_CURSOR_ENGINE`` picks who generates the motion: ``python`` (default) or
|
||||
``off``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import os
|
||||
import warnings
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
# The escape hatch. ``INVPW_CURSOR_ENGINE`` picks who generates the motion:
|
||||
# ``INVPW_CURSOR_ENGINE`` picks who generates the motion:
|
||||
# "python" (default) - the server's pointer, seeded from the session seed
|
||||
# "binary" - the browser's own expansion, i.e. the pre-existing
|
||||
# behaviour, for anyone who was depending on it
|
||||
# "off" - no humanisation at all, same as humanize=False
|
||||
ENGINE_ENV = "INVPW_CURSOR_ENGINE"
|
||||
|
||||
ENGINE_PYTHON = "python"
|
||||
ENGINE_BINARY = "binary"
|
||||
ENGINE_OFF = "off"
|
||||
|
||||
# Opt-out for the one behaviour that changes what the automation layer itself
|
||||
@@ -91,9 +87,7 @@ def _reset_warnings() -> None:
|
||||
# ``_motion`` supplies the stroke generator. It must expose a per-session
|
||||
# class:
|
||||
#
|
||||
# CursorMotion(seed: int) - the shipped name
|
||||
# MotionProfile(seed, max_seconds) / new_motion(...) - also accepted, so
|
||||
# the generator can grow a duration argument without this file moving
|
||||
# CursorMotion(seed: int, *, style=None)
|
||||
#
|
||||
# and the instance must expose:
|
||||
#
|
||||
@@ -107,68 +101,17 @@ def _reset_warnings() -> None:
|
||||
# it, since a cursor that is at the top-left corner at the start of
|
||||
# every session is an invariant shared by every install.
|
||||
#
|
||||
# Anything else is treated as "no generator available" and the session falls
|
||||
# back to the browser's own expansion, which is always a working browser.
|
||||
try: # pragma: no cover - exercised by the import-failure test via monkeypatch
|
||||
# The package that publishes the generator: `_motion_factory` looks the
|
||||
# factory up on it by name, and the tests put a stub module here.
|
||||
from invisible_core import juggler as _motion_mod # type: ignore[attr-defined]
|
||||
except Exception as _motion_exc: # noqa: BLE001 - a broken generator must not break launching
|
||||
_motion_mod = None # type: ignore[assignment]
|
||||
_MOTION_IMPORT_ERROR: Optional[BaseException] = _motion_exc
|
||||
else:
|
||||
_MOTION_IMPORT_ERROR = None
|
||||
|
||||
#: ONE physical floor for the package, taken from where it is defined.
|
||||
#: Re-exported here because it is part of this module's published surface.
|
||||
from invisible_core.juggler import MIN_EVENT_INTERVAL_MS # noqa: E402 - re-exported, see above
|
||||
# The core is pinned with `==`, so the generator is always there: the import is
|
||||
# direct, and an install without it fails here, at import.
|
||||
#
|
||||
# The package that publishes the generator: `_motion_factory` reads it from here,
|
||||
# and the tests put a stub module in its place.
|
||||
from invisible_core import juggler as _motion_mod
|
||||
|
||||
|
||||
_MOTION_FACTORY_NAMES = ("CursorMotion", "MotionProfile", "new_motion")
|
||||
|
||||
|
||||
def _motion_factory() -> Optional[Callable[..., Any]]:
|
||||
"""Return the callable that builds a per-page stroke generator, or None."""
|
||||
mod = _motion_mod
|
||||
if mod is not None:
|
||||
for name in _MOTION_FACTORY_NAMES:
|
||||
factory = getattr(mod, name, None)
|
||||
if callable(factory):
|
||||
return factory
|
||||
detail = (
|
||||
f" ({type(_MOTION_IMPORT_ERROR).__name__}: {_MOTION_IMPORT_ERROR})"
|
||||
if _MOTION_IMPORT_ERROR is not None
|
||||
else ""
|
||||
)
|
||||
_warn_once(
|
||||
"no-motion",
|
||||
"no cursor motion generator found "
|
||||
"(invisible_core.juggler.CursorMotion)" + detail + "; falling "
|
||||
"back to the browser's own motion for this process. This is a broken "
|
||||
"install, not a configuration.",
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _build_profile(factory: Callable[..., Any], seed: int, max_seconds: float) -> Any:
|
||||
"""Construct a profile, whether or not the generator wants the cap.
|
||||
|
||||
The cap belongs to the public constructor (``humanize=<seconds>``), so the
|
||||
pointer honours it either way: a generator that takes it applies it itself,
|
||||
one that does not gets its schedule fitted by the pointer.
|
||||
"""
|
||||
try:
|
||||
params = inspect.signature(factory).parameters
|
||||
except (TypeError, ValueError): # C-level or otherwise unintrospectable
|
||||
params = {}
|
||||
if "max_seconds" in params:
|
||||
return factory(seed=seed, max_seconds=max_seconds)
|
||||
return factory(seed)
|
||||
|
||||
|
||||
def motion_available() -> bool:
|
||||
"""True when a generator exists AND the bindings could be wrapped."""
|
||||
return _motion_factory() is not None and _ensure_patched()
|
||||
def _motion_factory() -> Callable[..., Any]:
|
||||
"""The callable that builds a per-page stroke generator."""
|
||||
return _motion_mod.CursorMotion
|
||||
|
||||
|
||||
def resolve_cursor_engine(humanize: Any) -> str:
|
||||
@@ -177,19 +120,22 @@ def resolve_cursor_engine(humanize: Any) -> str:
|
||||
``humanize`` keeps exactly the meaning it has always had on the public
|
||||
constructor: falsy disables humanisation, ``True`` enables it with the
|
||||
default cap, a number enables it with that cap in seconds. This function
|
||||
only decides WHERE the motion comes from, never WHETHER the user asked
|
||||
for it.
|
||||
only decides WHETHER the Python generator draws it or nobody does.
|
||||
|
||||
``INVPW_CURSOR_ENGINE`` is strict: unset or empty (the default), ``python``
|
||||
or ``off``. Any other value is a ``ValueError`` naming the valid ones, even
|
||||
when ``humanize`` is falsy: a value that is ignored is a setting that does
|
||||
nothing while the caller believes it does something.
|
||||
"""
|
||||
if not humanize:
|
||||
choice = os.environ.get(ENGINE_ENV, "")
|
||||
if choice not in ("", ENGINE_PYTHON, ENGINE_OFF):
|
||||
raise ValueError(
|
||||
"invisible_playwright: %s=%r is not a cursor engine; the valid values "
|
||||
"are %r (the default, same as unset), %r and %r"
|
||||
% (ENGINE_ENV, choice, "", ENGINE_PYTHON, ENGINE_OFF))
|
||||
if not humanize or choice == ENGINE_OFF:
|
||||
return ENGINE_OFF
|
||||
choice = (os.environ.get(ENGINE_ENV) or "").strip().lower()
|
||||
if choice in (ENGINE_BINARY, "juggler"):
|
||||
return ENGINE_BINARY
|
||||
if choice in (ENGINE_OFF, "none", "false", "0"):
|
||||
return ENGINE_OFF
|
||||
# "", "python", "wrapper" and anything unrecognised: prefer the Python
|
||||
# generator, but never at the price of a session that cannot move at all.
|
||||
return ENGINE_PYTHON if motion_available() else ENGINE_BINARY
|
||||
return ENGINE_PYTHON
|
||||
|
||||
|
||||
def max_seconds_for(humanize: Any) -> float:
|
||||
@@ -265,8 +211,6 @@ def enable_for(owner: Any, *, seed: int, max_seconds: float) -> bool:
|
||||
"""
|
||||
if not _ensure_patched():
|
||||
return False
|
||||
if _motion_factory() is None:
|
||||
return False
|
||||
try:
|
||||
_SESSIONS[_impl(owner)] = {"seed": int(seed), "max_seconds": float(max_seconds)}
|
||||
except TypeError: # not weak-referenceable: refuse rather than leak
|
||||
@@ -346,15 +290,12 @@ def _ensure_patched() -> bool:
|
||||
|
||||
__all__ = [
|
||||
"ENGINE_ENV",
|
||||
"ENGINE_BINARY",
|
||||
"ENGINE_OFF",
|
||||
"ENGINE_PYTHON",
|
||||
"LANDING_ENV",
|
||||
"MIN_EVENT_INTERVAL_MS",
|
||||
"enable_for",
|
||||
"landing_enabled",
|
||||
"max_seconds_for",
|
||||
"motion_available",
|
||||
"page_motion_seed",
|
||||
"resolve_cursor_engine",
|
||||
]
|
||||
@@ -1,8 +1,7 @@
|
||||
"""Every route from a chosen path to a spawned Firefox goes through here.
|
||||
|
||||
``binary_path=`` (and ``INVPW_BINARY_PATH``, which the test suite and the e2e
|
||||
scripts turn into ``binary_path=``) never reaches ``ensure_binary()``, so none
|
||||
of the download-side checks run on that route. The guard therefore sits on the
|
||||
``binary_path=`` never reaches ``ensure_binary()``, so none of the download-side
|
||||
checks run on that route. The guard therefore sits on the
|
||||
resolved executable, not inside the fetcher.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -20,12 +19,9 @@ def resolve_executable(binary_path: Optional[Union[str, Path]]) -> Path:
|
||||
"""``binary_path=`` skips the download path entirely, so the guard sits on the
|
||||
resolved executable rather than inside the fetcher.
|
||||
|
||||
⛔ This used to say "binary_path= and INVPW_BINARY_PATH", and the second half
|
||||
was false: nothing here reads that variable. It is translated into
|
||||
``binary_path=`` by the test scripts and by ``run_e2e.py``, so it is a
|
||||
convention of this repo's harness and not a feature of the library. Corrected
|
||||
2026-08-14 - a docstring that promises an env var the code never reads sends
|
||||
the reader looking for a bug in the wrong function.
|
||||
⛔ Nothing here reads ``INVPW_BINARY_PATH``. It is a convention of this
|
||||
repo's harness (the test fixtures and ``run_e2e.py`` turn it into
|
||||
``binary_path=``), not a feature of the library.
|
||||
|
||||
Driving an engine the packaged seal does not describe is done with
|
||||
``binary_path=`` plus ``INVISIBLE_SEAL_FILE`` pointing at a seal generated for
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
"""Backward-compat shim - moved to invisible_core._fpforge (full alias).
|
||||
|
||||
Aliases the package AND its submodules to the same objects as the core, so
|
||||
``from invisible_playwright._fpforge.profile import Profile`` and
|
||||
``from invisible_core._fpforge.profile import Profile`` are the SAME class
|
||||
(isinstance works) and the private names stay accessible.
|
||||
"""
|
||||
import sys as _sys
|
||||
import invisible_core._fpforge as _pkg
|
||||
from invisible_core._fpforge import profile as _profile
|
||||
from invisible_core._fpforge import _sampler as _sampler_mod
|
||||
from invisible_core._fpforge import _network as _network_mod
|
||||
|
||||
_sys.modules[__name__] = _pkg
|
||||
_sys.modules[__name__ + ".profile"] = _profile
|
||||
_sys.modules[__name__ + "._sampler"] = _sampler_mod
|
||||
_sys.modules[__name__ + "._network"] = _network_mod
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - spostato in invisible_core._geo (alias completo)."""
|
||||
import sys as _sys
|
||||
from invisible_core import _geo as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - spostato in invisible_core._headless (alias completo)."""
|
||||
import sys as _sys
|
||||
from invisible_core import _headless as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -0,0 +1,159 @@
|
||||
"""What follows the exit of the browser, for the in-process server: the session's directories go with the launch's reaper.
|
||||
|
||||
⛔ THE CLOSE OF A BROWSER RETURNS WHEN THE BROWSER HAS EXITED (invisible-core's `Connection.close`). What stays after it is
|
||||
the sender of the shutdown pings, and the launch's `reaper` (`invisible_core.process.Reaper`, a thread that is not a
|
||||
daemon) waits for it within its grace, ends what is left, releases the launch and runs the steps handed to `reaper.then`.
|
||||
The removal of the session's directories is such a step: `SessionFiles.remove` waits for the sender too, so run by the
|
||||
server after the shutdown it kept the wrapper's close as slow as it was before the core stopped waiting.
|
||||
|
||||
A core before that has no `reaper` on its connection: the removal runs after the shutdown, as it always did.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
_lock = threading.Lock()
|
||||
#: Session token (its value) -> the reapers of the launches made under it, the ones that have not finished at the last look.
|
||||
_reapers: Dict[str, List[Any]] = {}
|
||||
|
||||
|
||||
def reaper_of(conn: Any) -> Any:
|
||||
"""The launch's reaper, or None: the core has none, or the connection was never closed."""
|
||||
return getattr(conn, "reaper", None)
|
||||
|
||||
|
||||
class SessionRemoval:
|
||||
"""The removal of ONE launch's directories, run once, by the reaper when the connection has one and otherwise by the
|
||||
server after its hooks."""
|
||||
|
||||
def __init__(self, remove: Callable[[], None], token: str = "") -> None:
|
||||
self._remove = remove
|
||||
self._token = token
|
||||
self._lock = threading.Lock()
|
||||
self._done = False
|
||||
self._handed = False
|
||||
|
||||
def run(self) -> None:
|
||||
with self._lock:
|
||||
if self._done:
|
||||
return
|
||||
self._done = True
|
||||
self._remove()
|
||||
|
||||
def after_shutdown(self) -> None:
|
||||
"""The step the server runs once its hooks have: the removal itself, unless the reaper has been handed it.
|
||||
|
||||
⛔ ON THIS ROUTE THERE IS NO LAUNCH THREAD TO HAND THE STEP TO: `close` did not hand it, because the connection has no
|
||||
reaper (a core before the one that makes them, or a close that raised), so the removal runs where it is, here. The
|
||||
session's other steps (`after_the_reapers`) are the ones that wait for the reapers."""
|
||||
with self._lock:
|
||||
if self._handed:
|
||||
return
|
||||
self.run()
|
||||
|
||||
def close(self, conn: Any) -> None:
|
||||
"""The hook of the shutdown: closes the connection (which returns when the browser has exited) and, when the core
|
||||
gives the launch a reaper, hands the removal to it, so the shutdown does not wait for the sender or the tree."""
|
||||
conn.close()
|
||||
reaper = reaper_of(conn)
|
||||
if reaper is None:
|
||||
return
|
||||
with self._lock:
|
||||
if self._handed:
|
||||
return
|
||||
self._handed = True
|
||||
if self._token:
|
||||
with _lock:
|
||||
kept = [r for r in _reapers.get(self._token, ()) if not getattr(r, "finished", False)]
|
||||
kept.append(reaper)
|
||||
_reapers[self._token] = kept
|
||||
reaper.then(self.run)
|
||||
|
||||
|
||||
def wait_reaped(token: Any, timeout: Optional[float] = None) -> bool:
|
||||
"""Waits for what follows the exit of the browsers closed under ``token`` (a `SessionToken` or its value): the
|
||||
processes that outlived them are finished or ended, the launches are released and the session's directories are gone.
|
||||
True when it is all done (also when the core has no reaper: nothing is left to wait for), False at ``timeout``. Costs
|
||||
nothing when nothing was left. Only after the close."""
|
||||
value = getattr(token, "value", token)
|
||||
with _lock:
|
||||
reapers = list(_reapers.get(value, ()))
|
||||
deadline = None if timeout is None else time.monotonic() + timeout
|
||||
for reaper in reapers:
|
||||
reaper.join(None if deadline is None else max(0.0, deadline - time.monotonic()))
|
||||
done = all(getattr(r, "finished", True) for r in reapers)
|
||||
if done:
|
||||
with _lock:
|
||||
kept = [r for r in _reapers.get(value, ()) if r not in reapers]
|
||||
if kept:
|
||||
_reapers[value] = kept
|
||||
else:
|
||||
_reapers.pop(value, None)
|
||||
return done
|
||||
|
||||
|
||||
def after_the_reapers(step: Callable[[], Any], *tokens: Any, forget: bool = False) -> Any:
|
||||
"""Runs ``step`` once, after the last of the reapers of the launches made under ``tokens`` (a `SessionToken` or its
|
||||
value each), and returns at once with None when it was handed over. With no reaper at all it runs now, on the caller,
|
||||
and its result is returned: the way it always ran.
|
||||
|
||||
⛔ THE ONE PLACE FOR "AFTER THE SESSION'S REAPERS". A step that the server's shutdown thread or the user's close would run
|
||||
waits there for what the reaper waits for (the sender of the shutdown pings, the tree), and a folder's removal is as slow
|
||||
as the disk. Handed to the reapers (`then`) it runs on the thread that ends the tree, after the grace, and nothing is
|
||||
waited for. Nothing here assumes which thread runs the step: that is `Reaper.then`'s to say.
|
||||
|
||||
``forget``: the reapers of this snapshot are taken out of the tokens' entries with the step (even when it raises): a
|
||||
process that opens sessions without end (the server) would keep one entry per session, with its reapers and their trees.
|
||||
Only the reapers of THIS snapshot go: a launch registered under the same token meanwhile keeps its own. Left False, the
|
||||
entries stay for `wait_reaped`, which is what joins the reapers and takes them out. Never raises on the reapers' side;
|
||||
the step's own errors reach whoever runs it."""
|
||||
values = [getattr(token, "value", token) for token in tokens]
|
||||
with _lock:
|
||||
reapers = [r for value in values for r in _reapers.get(value, ())]
|
||||
if not reapers:
|
||||
return step()
|
||||
pending = [len(reapers)]
|
||||
gate = threading.Lock()
|
||||
|
||||
def after_the_last() -> None:
|
||||
with gate:
|
||||
pending[0] -= 1
|
||||
if pending[0]:
|
||||
return
|
||||
try:
|
||||
step()
|
||||
finally:
|
||||
if forget:
|
||||
for value in values:
|
||||
_forget(value, reapers)
|
||||
|
||||
for reaper in reapers:
|
||||
reaper.then(after_the_last)
|
||||
return None
|
||||
|
||||
|
||||
def final_reap(guard: Any, token: Any) -> int:
|
||||
"""The teardown's last step: whatever still carries the session's ``token`` is ended.
|
||||
|
||||
⛔ WHEN THE SESSION'S LAUNCHES HAVE A REAPER THE LAST REAP IS ITS TO RUN. `guard.reap` ends the session's tree at once, and
|
||||
what is left at that moment is the sender of the shutdown pings: ended here, the pings were lost and the grace the reaper
|
||||
gives it was for nothing. The reap is handed to the reapers (`after_the_reapers`), so it runs after the grace and the end of
|
||||
what is left, and it is the net it always was for what the reaper did not end. Returns at once then, with 0: nothing is
|
||||
waited for.
|
||||
|
||||
With no reaper (a core before the one that makes them, a launch that failed before it had one, an error path that never
|
||||
reached the shutdown) it runs now, as it always did. Never raises on the reapers' side; the guard's own errors reach the
|
||||
caller as they did."""
|
||||
return after_the_reapers(lambda: guard.reap(token), token, forget=True) or 0
|
||||
|
||||
|
||||
def _forget(value: str, reapers: List[Any]) -> None:
|
||||
"""Takes ``reapers`` out of the token's entry, and the entry with them when nothing else is in it."""
|
||||
with _lock:
|
||||
kept = [r for r in _reapers.get(value, ()) if not any(r is gone for gone in reapers)]
|
||||
if kept:
|
||||
_reapers[value] = kept
|
||||
else:
|
||||
_reapers.pop(value, None)
|
||||
@@ -39,6 +39,7 @@ import time
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from . import perimeter, variants
|
||||
from ._reaped import after_the_reapers
|
||||
from ._threads import ThreadStarter
|
||||
# One class for a target that is gone, raised here for a disposed object and
|
||||
# by the connection for a closed pipe. Defined there, the lower layer.
|
||||
@@ -275,6 +276,8 @@ class Server:
|
||||
self._on_shutdown: list = []
|
||||
#: What `shutdown` runs after every hook. See `after_shutdown`.
|
||||
self._after_shutdown: list = []
|
||||
#: The session tokens of the launches this server made, in order: what `after_reapers` waits for.
|
||||
self._session_tokens: list = []
|
||||
self._starter: Optional[ThreadStarter] = None
|
||||
self._starter_lock = threading.Lock()
|
||||
self._is_shut_down = False
|
||||
@@ -443,6 +446,21 @@ class Server:
|
||||
"""
|
||||
self._after_shutdown.append(step)
|
||||
|
||||
def note_session_token(self, token: Any) -> None:
|
||||
"""A launch was made under ``token`` (a `SessionToken` or its value): its reaper is one of those `after_reapers` waits for."""
|
||||
value = getattr(token, "value", token)
|
||||
if value and value not in self._session_tokens:
|
||||
self._session_tokens.append(value)
|
||||
|
||||
def after_reapers(self, step: Callable[[], None]) -> None:
|
||||
"""Like `after_shutdown`, for a step that is slow or waits for something (a folder's removal): it is run once the
|
||||
session's reapers are done with the launches (`_reaped.after_the_reapers`), never on the shutdown thread that the user's
|
||||
stop waits for. With no reaper it runs there, as `after_shutdown` runs it.
|
||||
|
||||
⛔ THE TOKENS ARE READ WHEN THE SHUTDOWN RUNS THE STEP, not now: the folders are made by a context, after the launch
|
||||
that gives the reaper its token, and the reaper itself exists only once the hooks have closed the connection."""
|
||||
self.after_shutdown(lambda: after_the_reapers(step, *self._session_tokens))
|
||||
|
||||
def shutdown(self) -> None:
|
||||
for hook in reversed(self._on_shutdown):
|
||||
try:
|
||||
|
||||
@@ -48,15 +48,17 @@ from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
from invisible_core.juggler import (
|
||||
DONE, SLEEP, Ev as _Ev, Pacer, PointerPersona, Step,
|
||||
clamp_to_viewport as _clamp, fine_timer as _fine_timer,
|
||||
Ev as _Ev, PointerPersona, Step,
|
||||
clamp_to_viewport as _clamp,
|
||||
fit_timeline as _fit_timeline, initial_pointer, landing_point,
|
||||
plan_aimless_move, plan_approach, plan_idle, plan_scroll,
|
||||
steps_from_waypoints, tail_within,
|
||||
)
|
||||
from invisible_core.juggler.connection import ReplyTimeout
|
||||
from invisible_core.juggler.connection import (
|
||||
ProtocolError, ReplyTimeout, TargetClosedError)
|
||||
from invisible_core.juggler.deadline import Deadline
|
||||
from invisible_core.juggler.injected import ContextDestroyed, EvaluationError
|
||||
from invisible_core.juggler.injected import (
|
||||
ContextDestroyed, EvaluationError, FrameDetached)
|
||||
from invisible_core.seedmix import sub_seed
|
||||
|
||||
from .. import _cursor
|
||||
@@ -88,10 +90,12 @@ _LANDING_MIN_BOX_PX = 12.0
|
||||
_LANDING_SPREAD = 0.14
|
||||
_LANDING_KEEP = 0.26
|
||||
|
||||
#: What a probe of the page can legitimately answer while we are only AIMING:
|
||||
#: the element went away, the frame navigated, the page closed.
|
||||
_PROBE_ERRORS = (ContextDestroyed, EvaluationError, ReplyTimeout,
|
||||
ProtocolException, TimeoutError)
|
||||
#: What the ENGINE and the page can legitimately answer while we are only AIMING or walking: the element went away, the frame
|
||||
#: navigated or detached, the page or the browser closed (`TargetClosedError`), a command was refused or not answered. These are
|
||||
#: the errors that motion never turns into the action's failure (the action meets the same state itself and raises its own).
|
||||
#: Nothing else is in it on purpose: an AttributeError, a TypeError or a NameError out of the path is OUR bug, and it comes out.
|
||||
_PROBE_ERRORS = (ContextDestroyed, EvaluationError, FrameDetached, ReplyTimeout,
|
||||
ProtocolError, ProtocolException, TargetClosedError, TimeoutError)
|
||||
|
||||
|
||||
# ── the clock ───────────────────────────────────────────────────────────────
|
||||
@@ -179,41 +183,6 @@ def _normalise_waypoints(raw: Iterable[Any], max_seconds: float) -> List[Tuple[f
|
||||
return out
|
||||
|
||||
|
||||
def _drive(evs: Sequence[_Ev], emit_move: Callable[[float, float], Any],
|
||||
emit_wheel: Optional[Callable[[float, float], Any]] = None, *,
|
||||
emit_last: bool = True,
|
||||
origin: Optional[Tuple[float, float]] = None) -> int:
|
||||
"""The synchronous driver of `Pacer`. Returns events sent.
|
||||
|
||||
The rules it obeys - absolute deadlines from one ``t0``, drop rather than
|
||||
send late while the drop stays within reach, never two events in one
|
||||
instant - are the pacer's, the core's, and are the same ones the client's
|
||||
asynchronous driver obeyed. This supplies a clock, a way of waiting and
|
||||
where the pointer starts from; it makes no decision the pacer has not made.
|
||||
"""
|
||||
if not evs:
|
||||
return 0
|
||||
clock = _CLOCK
|
||||
pacer = Pacer(evs, emit_last=emit_last, origin=origin)
|
||||
with _fine_timer():
|
||||
while True:
|
||||
what, arg = pacer.step(clock.now())
|
||||
if what == DONE:
|
||||
break
|
||||
if what == SLEEP:
|
||||
clock.sleep(arg)
|
||||
continue
|
||||
if arg.is_wheel:
|
||||
if emit_wheel is None:
|
||||
pacer.dropped() # nothing here can carry a notch
|
||||
continue
|
||||
emit_wheel(arg.dx, arg.dy)
|
||||
else:
|
||||
emit_move(arg.x, arg.y)
|
||||
pacer.emitted(clock.now())
|
||||
return pacer.delivered
|
||||
|
||||
|
||||
# ── one page's hand ─────────────────────────────────────────────────────────
|
||||
|
||||
class _Hand:
|
||||
@@ -226,7 +195,7 @@ class _Hand:
|
||||
synced: Any) -> None:
|
||||
self.seed = int(seed)
|
||||
self.max_seconds = float(max_seconds)
|
||||
self._profile = _cursor._build_profile(factory, self.seed, self.max_seconds)
|
||||
self._profile = factory(self.seed)
|
||||
self.persona = PointerPersona.from_seed(self.seed)
|
||||
self.x: Optional[float] = None
|
||||
self.y: Optional[float] = None
|
||||
@@ -363,8 +332,6 @@ class Pointer:
|
||||
if not draws or session_seed is None or not budget_s:
|
||||
return
|
||||
factory = _cursor._motion_factory()
|
||||
if factory is None:
|
||||
return
|
||||
seed = _cursor.page_motion_seed(session_seed, number)
|
||||
try:
|
||||
self.hand = _Hand(seed, budget_s, factory,
|
||||
@@ -409,10 +376,18 @@ class Pointer:
|
||||
hand.x, hand.y = hand.start_point(w, h)
|
||||
return float(hand.x), float(hand.y)
|
||||
|
||||
def _emit_move(self, x: float, y: float) -> None:
|
||||
def _walk(self, evs: Sequence[_Ev], *, emit_last: bool = True) -> int:
|
||||
"""Hand a planned timeline to the core, which walks it as ONE stroke: the pacer's instants on the client's clock, each point
|
||||
carrying `stroke` and `at`, no reply waited for between two points. Returns the events delivered.
|
||||
|
||||
⛔ THIS IS THE ONLY PLACE A PATH LEAVES. It used to be driven here, one point at a time through `actions.move`, and each point
|
||||
waited for the engine's reply: a slow reply was a pause in the path that the page saw, and the points after it were crowded
|
||||
together. The pacer's decisions are the core's, and so is the loop that applies them (`Actions.walk`)."""
|
||||
hand = self.hand
|
||||
self.actions.move(x, y)
|
||||
sent = self.actions.walk(evs, origin=(hand.x, hand.y), emit_last=emit_last,
|
||||
now=_CLOCK.now, sleep=_CLOCK.sleep)
|
||||
hand.synced = getattr(self.actions, "position", None)
|
||||
return sent
|
||||
|
||||
# -- the probes --------------------------------------------------------
|
||||
|
||||
@@ -505,21 +480,19 @@ class Pointer:
|
||||
|
||||
# -- travelling --------------------------------------------------------
|
||||
|
||||
def _run_steps(self, steps: Sequence[Any], emit_wheel: Optional[Callable] = None,
|
||||
*, budget_s: float, emit_last: bool = True) -> None:
|
||||
"""Dispatch a planned ``_behaviour`` timeline, inside a time budget."""
|
||||
def _run_steps(self, steps: Sequence[Any], *, budget_s: float, emit_last: bool = True) -> None:
|
||||
"""Dispatch a planned ``_behaviour`` timeline, inside a time budget: moves and wheel notches, as one stroke."""
|
||||
hand = self.hand
|
||||
evs = _fit_timeline(_timeline(steps), budget_s)
|
||||
if not evs:
|
||||
return
|
||||
|
||||
def move(x: float, y: float) -> None:
|
||||
self._emit_move(x, y)
|
||||
hand.x, hand.y = x, y
|
||||
|
||||
_drive(evs, move, emit_wheel, emit_last=emit_last,
|
||||
origin=(hand.x, hand.y))
|
||||
if not emit_last and evs:
|
||||
self._walk(evs, emit_last=emit_last)
|
||||
if emit_last:
|
||||
# The pointer is where the last move that went out put it (a notch leaves it where it was).
|
||||
now = getattr(self.actions, "position", None)
|
||||
if now is not None:
|
||||
hand.x, hand.y = float(now[0]), float(now[1])
|
||||
else:
|
||||
hand.x, hand.y = evs[-1].x, evs[-1].y
|
||||
hand.last_event_at = _CLOCK.now()
|
||||
|
||||
@@ -654,7 +627,7 @@ class Pointer:
|
||||
override = None
|
||||
try:
|
||||
override = self.approach(frame_id, selector, position, trial)
|
||||
except Exception as exc: # noqa: BLE001 - motion never fails an action
|
||||
except _PROBE_ERRORS as exc: # motion never fails an action for what the engine or the page answers; a bug of ours is not that
|
||||
_cursor._warn_once(
|
||||
"approach-failed",
|
||||
"the cursor approach raised (%s: %s); the action itself is "
|
||||
@@ -696,7 +669,7 @@ class Pointer:
|
||||
hand.action += 1
|
||||
try:
|
||||
self._travel(x, y)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
except _PROBE_ERRORS as exc: # what the engine or the page answers, not a bug of ours (see `_PROBE_ERRORS`)
|
||||
_cursor._warn_once(
|
||||
"move-failed",
|
||||
"the cursor path raised during %s (%s: %s); the action "
|
||||
@@ -756,11 +729,7 @@ class Pointer:
|
||||
# though the caller is the one that emits it.
|
||||
evs.append(_Ev(max(t, evs[-1].t_ms if evs else 0.0), to_x, to_y))
|
||||
|
||||
def emit(x: float, y: float) -> None:
|
||||
self._emit_move(x, y)
|
||||
hand.x, hand.y = x, y
|
||||
|
||||
_drive(evs, emit, emit_last=False, origin=(hand.x, hand.y))
|
||||
self._walk(evs, emit_last=False)
|
||||
hand.x, hand.y = to_x, to_y
|
||||
hand.last_event_at = _CLOCK.now()
|
||||
|
||||
@@ -799,12 +768,11 @@ class Pointer:
|
||||
try:
|
||||
plan = self._scroll_plan(float(dx), float(dy))
|
||||
if plan:
|
||||
self._run_steps(plan, self.actions.wheel,
|
||||
budget_s=hand.max_seconds)
|
||||
self._run_steps(plan, budget_s=hand.max_seconds)
|
||||
return True
|
||||
finally:
|
||||
hand.busy = False
|
||||
except Exception as exc: # noqa: BLE001
|
||||
except _PROBE_ERRORS as exc: # what the engine or the page answers, not a bug of ours (see `_PROBE_ERRORS`)
|
||||
_cursor._warn_once(
|
||||
"wheel-failed",
|
||||
"the scroll planner raised (%s: %s); the scroll itself is "
|
||||
|
||||
@@ -718,7 +718,7 @@ def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
|
||||
from invisible_core import configure_proxy, prepare_session_geo
|
||||
from invisible_core import make_virtual_display
|
||||
from invisible_playwright._engine import resolve_executable
|
||||
from invisible_playwright._reaper import SessionToken
|
||||
from invisible_core.process import SessionToken
|
||||
|
||||
geo = prepare_session_geo(session._timezone, session._proxy,
|
||||
session._locale_requested, seed=session.seed,
|
||||
@@ -837,7 +837,6 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
|
||||
LocalUtilsDispatcher(server)
|
||||
browser = server.object(
|
||||
browser_type.op_launch(params)["browser"]["guid"])
|
||||
session._bind_process_tree()
|
||||
|
||||
class _Reported: # what assert_wire_version reads off a Browser
|
||||
version = browser.initializer.get("version", "")
|
||||
|
||||
@@ -48,6 +48,7 @@ from invisible_core.juggler import connection as juggler
|
||||
from invisible_core.juggler.actions import Actions
|
||||
from invisible_core.juggler.deadline import Deadline
|
||||
from . import _bindings, dialogs
|
||||
from ._reaped import SessionRemoval
|
||||
from ._threads import ThreadStarterLease
|
||||
from .pointer import Pointer
|
||||
from .dispatcher import (Dispatcher, ExpectNotMet, ProtocolException,
|
||||
@@ -5971,7 +5972,7 @@ class BrowserDispatcher(Dispatcher):
|
||||
if root is None:
|
||||
import shutil
|
||||
root = self._downloads_root = tempfile.mkdtemp(prefix="invpw-downloads-")
|
||||
self.server.after_shutdown(
|
||||
self.server.after_reapers(
|
||||
lambda: shutil.rmtree(root, ignore_errors=True))
|
||||
path = os.path.join(root, context_id or "default")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
@@ -6218,7 +6219,12 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
named = {e["name"] for e in params.get("env") or []}
|
||||
environment.update({k: v for k, v in session_env.items() if k not in named})
|
||||
files = SessionFiles(params.get("userDataDir"), environment)
|
||||
self.server.after_shutdown(files.remove)
|
||||
# ⛔ WITH A CORE THAT GIVES THE LAUNCH A REAPER the removal is handed to it once `conn.close` has returned (see
|
||||
# `_reaped`); without one it runs here, after the hooks, as before.
|
||||
session_token = getattr(getattr(files, "token", None), "value", "")
|
||||
removal = SessionRemoval(files.remove, session_token)
|
||||
self.server.note_session_token(session_token)
|
||||
self.server.after_shutdown(removal.after_shutdown)
|
||||
env, profile = files.env, files.profile
|
||||
# ⛔ THE TYPING SEED TRAVELS IN THE PREFS AND IS TAKEN OUT AGAIN HERE,
|
||||
# before a single byte reaches the profile.
|
||||
@@ -6281,7 +6287,7 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
headless=bool(params.get("headless", True)),
|
||||
env=env, argv_extra=params.get("args") or [],
|
||||
ready_timeout=ready, proxy=proxy)
|
||||
self.server.on_shutdown(conn.close)
|
||||
self.server.on_shutdown(lambda: removal.close(conn))
|
||||
# ⛔ A LAUNCH THAT FAILS FROM HERE ON CLOSES THE BROWSER IT STARTED.
|
||||
# A browser that is running and was never handed to the caller is one
|
||||
# nobody will close before the server shuts down.
|
||||
@@ -6368,7 +6374,7 @@ class JugglerServer(Server):
|
||||
if root is None:
|
||||
root = tempfile.mkdtemp(prefix="invisible_upload_")
|
||||
self._upload_root = root
|
||||
self.after_shutdown(lambda: remove_profile(root))
|
||||
self.after_reapers(lambda: remove_profile(root))
|
||||
path = os.path.join(tempfile.mkdtemp(dir=root), name)
|
||||
with open(path, "wb") as out:
|
||||
out.write(base64.b64decode(payload.get("buffer") or ""))
|
||||
|
||||
@@ -43,6 +43,7 @@ names the guid it creates, and that is the dispatcher's job, not the pool's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import _thread as _raw_thread
|
||||
import asyncio
|
||||
import os
|
||||
import queue
|
||||
@@ -50,6 +51,7 @@ import threading
|
||||
import traceback
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from invisible_core._offloop import off_the_loop
|
||||
from invisible_playwright._pw._impl._helper import parse_error
|
||||
from invisible_playwright._pw._impl._transport import Transport
|
||||
|
||||
@@ -101,6 +103,10 @@ class InProcessTransport(Transport):
|
||||
self._stopped = threading.Event()
|
||||
self._stopped_future: asyncio.Future = loop.create_future()
|
||||
self._threads: list = []
|
||||
#: The thread that runs the server's shutdown (see `request_stop`); None until the stop is requested.
|
||||
self._shutdown_thread: Optional[threading.Thread] = None
|
||||
#: Set once the raw thread has begun (or failed to begin) the shutdown thread, so the join below knows whether to wait.
|
||||
self._shutdown_begun = threading.Event()
|
||||
server.attach(self)
|
||||
|
||||
# ── the five methods the seam declares ──────────────────────────────────
|
||||
@@ -131,6 +137,14 @@ class InProcessTransport(Transport):
|
||||
await self._stopped_future
|
||||
|
||||
def request_stop(self) -> None:
|
||||
"""⛔ THE SERVER'S SHUTDOWN IS NOT RUN BY THE CALLER, and the caller is usually the user's event loop. `server.shutdown()` runs the
|
||||
hooks of the session (the engine's `conn.close`, which waits for its processes to exit) and then the removal of its directories:
|
||||
seconds of waiting, and on the loop they stopped every other browser of the process for as long as they took (measured with
|
||||
four browsers in one process). It runs on a thread of its own, NOT a daemon: a close that the interpreter's exit could cut short
|
||||
is a browser left half closed, a leak. `wait_until_stopped` is where it is waited for, and off the loop too.
|
||||
|
||||
The thread is begun by a raw thread, as the server's starter is: `Thread.start` does not return until the new thread runs, and
|
||||
that wait on a loaded machine is the loop's own (see `connect`)."""
|
||||
if self._stopped.is_set():
|
||||
return
|
||||
self._stopped.set()
|
||||
@@ -138,23 +152,58 @@ class InProcessTransport(Transport):
|
||||
# a flag.
|
||||
for _ in self._threads:
|
||||
self._queue.put(None)
|
||||
|
||||
def shutdown() -> None:
|
||||
try:
|
||||
self._server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
# The stop is settled when the shutdown has ended, as it always was: `run` returns after the hooks.
|
||||
try:
|
||||
self._loop.call_soon_threadsafe(self._settle)
|
||||
except RuntimeError:
|
||||
pass # the loop is closed: nobody waits for the stop any more
|
||||
|
||||
thread = threading.Thread(target=shutdown, name="juggler-shutdown")
|
||||
self._shutdown_thread = thread
|
||||
# Not through the server's `ThreadStarter`: `Server.shutdown` stops it, and a starter that has stopped drops what it is handed,
|
||||
# which here would be the shutdown itself. A raw thread begins this one (the caller returns at once).
|
||||
try:
|
||||
self._server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
if not self._stopped_future.done():
|
||||
self._loop.call_soon_threadsafe(self._settle)
|
||||
_raw_thread.start_new_thread(self._begin, (thread, shutdown))
|
||||
except RuntimeError:
|
||||
self._shutdown_begun.set()
|
||||
shutdown() # no thread can be made: the shutdown still has to happen, as it did before
|
||||
|
||||
def _begin(self, thread: threading.Thread, shutdown: Any) -> None:
|
||||
try:
|
||||
thread.start()
|
||||
except BaseException:
|
||||
self._shutdown_begun.set()
|
||||
shutdown() # on this raw thread, which is not the loop's
|
||||
else:
|
||||
self._shutdown_begun.set()
|
||||
|
||||
def _settle(self) -> None:
|
||||
if not self._stopped_future.done():
|
||||
self._stopped_future.set_result(None)
|
||||
|
||||
async def wait_until_stopped(self) -> None:
|
||||
await self._stopped_future
|
||||
def _join_workers(self) -> None:
|
||||
"""What `wait_until_stopped` waits for besides the stop itself: the workers (and the shutdown thread, which has settled the stop
|
||||
and is ending). Blocking, so never on the loop."""
|
||||
for t in self._threads:
|
||||
# A worker the starter never started (the transport stopped first) has nothing to join.
|
||||
if t.is_alive():
|
||||
t.join(timeout=5)
|
||||
shutdown = self._shutdown_thread
|
||||
if shutdown is not None:
|
||||
self._shutdown_begun.wait(5) # the raw thread that begins it may be a moment late
|
||||
if shutdown.is_alive():
|
||||
shutdown.join(timeout=5)
|
||||
|
||||
async def wait_until_stopped(self) -> None:
|
||||
await self._stopped_future
|
||||
await off_the_loop(self._join_workers)
|
||||
|
||||
def send(self, message: Dict) -> None:
|
||||
"""⛔ ENQUEUE ONLY. Running the operation here would run it on the
|
||||
@@ -258,48 +307,15 @@ class JsonWireTransport(InProcessTransport):
|
||||
super().emit_message(carried)
|
||||
|
||||
|
||||
# ── choosing one ────────────────────────────────────────────────────────────
|
||||
#
|
||||
# ⛔ THIS WAS A MODULE OF ITS OWN UNTIL 2026-08-29, and what it chose between
|
||||
# no longer exists. `factory.py` held 88 lines to pick between the Node driver
|
||||
# and this transport; the driver went on 2026-08-28, so a module whose whole
|
||||
# job was to call another module was left choosing between one thing and an
|
||||
# error message.
|
||||
#
|
||||
# ⛔ AND ITS TYPO GUARD WENT WITH IT, on purpose. It refused an unknown value
|
||||
# on the argument that "a typo would run the driver while you believed you
|
||||
# were testing the Python path". That was true and is not: there is no driver
|
||||
# to run by accident, so the check protected nothing and cost a concept.
|
||||
#
|
||||
# What was KEPT is the message below. Version 0.7.4 shipped with the driver as
|
||||
# the default, so somebody can have `INVPW_TRANSPORT=driver` still set in a
|
||||
# shell, and "unknown transport" would tell them nothing about what happened.
|
||||
# ── making one ──────────────────────────────────────────────────────────────
|
||||
|
||||
CHOICE_ENV = "INVPW_TRANSPORT"
|
||||
#: `json` puts the wire between the client and the server (`JsonWireTransport`), as it is
|
||||
#: for a remote client. Off by default: local use passes the dicts as it always did.
|
||||
WIRE_ENV = "INVPW_WIRE"
|
||||
DRIVER = "driver"
|
||||
JUGGLER = "juggler"
|
||||
|
||||
|
||||
def chosen() -> str:
|
||||
"""Which transport this process asked for. Anything but `driver` is us."""
|
||||
return (os.environ.get(CHOICE_ENV) or JUGGLER).strip().lower()
|
||||
|
||||
|
||||
def make_transport(loop: asyncio.AbstractEventLoop) -> "InProcessTransport":
|
||||
"""The transport a `Connection` should speak through."""
|
||||
if chosen() == DRIVER:
|
||||
raise RuntimeError(
|
||||
"the Node driver was removed on 2026-08-28: this package no "
|
||||
"longer ships `_driver/` and no longer downloads node. What "
|
||||
"replaced it is the in-process Python server, which is now the "
|
||||
"only transport - unset %s and it runs. To get the old arm back "
|
||||
"for a COMPARISON (the only thing it was still for): check out "
|
||||
"the last commit that carried it into a git worktree and point "
|
||||
"INVPW_DRIVER_TREE at it, which `scripts/capture_protocol.py` "
|
||||
"reads." % CHOICE_ENV)
|
||||
from .server import JugglerServer
|
||||
if (os.environ.get(WIRE_ENV) or "").strip().lower() == "json":
|
||||
return JsonWireTransport(loop, JugglerServer())
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - spostato in invisible_core._proxy (alias completo)."""
|
||||
import sys as _sys
|
||||
from invisible_core import _proxy as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -99,8 +99,3 @@ class Transport(ABC):
|
||||
# ⛔ The `Transport` ABC above STAYS, and it is not vestigial: it is the
|
||||
# seam the in-process transport implements, and the reason the swap was one
|
||||
# class rather than a rewrite of the client.
|
||||
#
|
||||
# ⛔ To get the old arm back for a comparison - which is the only thing it
|
||||
# was still for - check out the last commit that carried it into a git
|
||||
# worktree and point `INVPW_DRIVER_TREE` at it. `scripts/capture_protocol.py`
|
||||
# reads that variable.
|
||||
@@ -29,9 +29,7 @@ class PlaywrightContextManager:
|
||||
async def __aenter__(self) -> AsyncPlaywright:
|
||||
loop = asyncio.get_running_loop()
|
||||
# MODIFIED by invisible_playwright: the transport is the in-process
|
||||
# server, from `make_transport`. The Node driver was removed on
|
||||
# 2026-08-28, and `INVPW_TRANSPORT=driver` is refused with a message
|
||||
# that says so - see `_juggler/transport.py`.
|
||||
# server, from `make_transport` (`_juggler/transport.py`).
|
||||
transport = make_transport(loop)
|
||||
self._connection = Connection(
|
||||
None,
|
||||
|
||||
@@ -58,9 +58,7 @@ Please use the Async API instead."""
|
||||
dispatcher_fiber = MainGreenlet(greenlet_main)
|
||||
|
||||
# MODIFIED by invisible_playwright: the transport is the in-process
|
||||
# server, from `make_transport`. The Node driver was removed on
|
||||
# 2026-08-28, and `INVPW_TRANSPORT=driver` is refused with a message
|
||||
# that says so - see `_juggler/transport.py`.
|
||||
# server, from `make_transport` (`_juggler/transport.py`).
|
||||
transport = make_transport(self._loop)
|
||||
self._connection = Connection(
|
||||
dispatcher_fiber,
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
"""Make the browser tree die when this process does.
|
||||
|
||||
THIS MODULE IS NOW A RE-EXPORT. The implementation lives in
|
||||
``invisible_core.process``. It went there to be shared with the profile manager,
|
||||
which launched the same browser and had exactly the same bug - and had it a day
|
||||
longer, because the fix was in this repository. That repository was deleted on
|
||||
2026-08-18; the implementation stays in the core, where this package imports it
|
||||
from.
|
||||
|
||||
Keeping the module rather than deleting it is deliberate: the names below are
|
||||
imported by `launcher`, by `async_api` and by `tests/test_reaper.py`, and the
|
||||
published wrapper reads `INVPW_SESSION_TOKEN` from a process environment, so the
|
||||
token spelling is a compatibility surface that outlives any refactor here.
|
||||
|
||||
WHAT MOVING IT FIXED, beyond the duplication. The two copies had already drifted:
|
||||
the core's version records only SUCCESSFUL job assignments, while this one added
|
||||
a pid to ``_adopted`` whether the assignment succeeded or not - so a refused
|
||||
process was never retried and the returned count was a number of attempts. On the
|
||||
manager that reported eight processes adopted out of eight while eight survived
|
||||
the kill. This package shipped that same accounting until 0.4.4.
|
||||
|
||||
The core's version also carries ``spawn_into``: create the process suspended,
|
||||
assign it to the job while it is still alone, then resume, so the whole tree is
|
||||
BORN inside the job. That exists because adopting afterwards cannot work for this
|
||||
browser - ``AssignProcessToJobObject`` refuses six of eight processes with
|
||||
ACCESS_DENIED, since Firefox has already placed its content processes in its own
|
||||
sandbox jobs. This package does not need it today (Playwright spawns the browser
|
||||
and the adoption path holds there), but it is one implementation now, so the next
|
||||
person does not have to discover that twice.
|
||||
|
||||
The full write-up - the bug, the token design, and why identification must be
|
||||
positive - is the module docstring of ``invisible_core.process``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from invisible_core.process import ( # noqa: F401 (re-export surface)
|
||||
JobObjectGuard,
|
||||
LifetimeGuard,
|
||||
NullGuard,
|
||||
SessionToken,
|
||||
TOKEN_VAR,
|
||||
alive,
|
||||
find_processes,
|
||||
guard_for,
|
||||
terminate,
|
||||
wait_until_gone,
|
||||
)
|
||||
|
||||
# psutil is re-exported because `tests/test_reaper.py` monkeypatches
|
||||
# `_reaper.psutil` to drive the unavailable-mechanism path. It is the same object
|
||||
# the core holds; patching it here would NOT affect the core, so the tests that
|
||||
# do that were moved with the implementation.
|
||||
from invisible_core.process import psutil # noqa: F401
|
||||
|
||||
__all__ = [
|
||||
"JobObjectGuard",
|
||||
"LifetimeGuard",
|
||||
"NullGuard",
|
||||
"SessionToken",
|
||||
"TOKEN_VAR",
|
||||
"alive",
|
||||
"find_processes",
|
||||
"guard_for",
|
||||
"terminate",
|
||||
"wait_until_gone",
|
||||
]
|
||||
@@ -20,9 +20,9 @@ the two classes is `await`, and nothing else belongs in this file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from ._cursor import (ENGINE_BINARY,
|
||||
ENGINE_PYTHON,
|
||||
from ._cursor import (ENGINE_PYTHON,
|
||||
enable_for as _enable_cursor_engine,
|
||||
max_seconds_for as _cursor_max_seconds)
|
||||
from ._engine import resolve_executable
|
||||
@@ -216,13 +216,9 @@ def build_prefs(
|
||||
#
|
||||
# What stays here is this path's DELIVERY and its two decisions:
|
||||
#
|
||||
# humanize The pref selects WHICH generator runs, not whether motion
|
||||
# happens. While the wrapper draws the path it must be false,
|
||||
# or every waypoint we send would itself be expanded into a
|
||||
# path by the browser. `max_seconds_for` is applied HERE rather
|
||||
# than passing `humanize` through, because a falsy-but-numeric
|
||||
# cap with the binary engine selected has to mean the default,
|
||||
# not "off".
|
||||
# humanize Always false: the wrapper draws the path, and a true value
|
||||
# would make the browser expand every waypoint we send into a
|
||||
# path of its own.
|
||||
# show_cursor Passed through UNTRANSLATED, and that is the difference
|
||||
# from the line above: `humanize` needs a decision here
|
||||
# because two engines compete for it, while the visible dot
|
||||
@@ -244,12 +240,10 @@ def build_prefs(
|
||||
# workarounds meant for that desktop apply only then. Nothing here
|
||||
# reads the platform: the fact travels, not a prediction of it.
|
||||
virtual_display=virtual_display,
|
||||
humanize=(_cursor_max_seconds(humanize)
|
||||
if cursor_engine == ENGINE_BINARY else False),
|
||||
humanize=False,
|
||||
show_cursor=show_cursor,
|
||||
# Handed to the core only when asked: a core that does not know the option is never called with it,
|
||||
# so a caller who does not use it cannot meet a TypeError from a pairing with an older core.
|
||||
**({} if preload_newtab is None else {"preload_newtab": preload_newtab}),
|
||||
# None (the caller did not say) writes nothing in the core; False / True are declarations.
|
||||
preload_newtab=preload_newtab,
|
||||
).prefs
|
||||
# ⛔ THE TYPING SEED RIDES IN THE PREFS AND NEVER REACHES THE PROFILE.
|
||||
#
|
||||
@@ -276,9 +270,8 @@ def build_prefs(
|
||||
# nobody is making.
|
||||
#
|
||||
# ⛔ AND WHO DRAWS THE WALK TRAVELS TOO (`POINTER_PREF`): with the seed
|
||||
# alone the server could not tell the Python generator from the engine's own
|
||||
# expansion or from `INVPW_CURSOR_ENGINE=off`, and a walk drawn on top of
|
||||
# either would humanise twice.
|
||||
# alone the server could not tell the Python generator from
|
||||
# `INVPW_CURSOR_ENGINE=off`, and would draw a walk nobody asked for.
|
||||
#
|
||||
# Milliseconds, and an int: Gecko has no float pref type, and `1.0` written
|
||||
# as a number arrives with the right value and the wrong type - the defect
|
||||
@@ -436,19 +429,72 @@ class CommonLaunch:
|
||||
``self._virtual_display`` is the fact ``_build_prefs`` reads to decide
|
||||
whether the desktop workarounds apply (B172).
|
||||
"""
|
||||
pw_headless, vd = self._plan_headless()
|
||||
if vd is not None:
|
||||
vd.start()
|
||||
self._virtual_display = vd
|
||||
return pw_headless
|
||||
|
||||
def _plan_headless(self) -> "tuple[bool, Any]":
|
||||
"""THE decision, made once for both APIs: ``(pw_headless, display)``.
|
||||
|
||||
``pw_headless`` is what Playwright is told; ``display`` is the hidden
|
||||
surface the caller must START (and then record in
|
||||
``self._virtual_display``, which `_build_prefs` reads), or None when
|
||||
none is wanted: headless off, true headless asked for, or a platform
|
||||
with no display to make. The two callers only decide WHERE the start
|
||||
runs - inline in the sync client, in a worker in the async one - so
|
||||
the decision cannot drift between them (B172 was one such drift).
|
||||
"""
|
||||
if not self._headless:
|
||||
return False
|
||||
return False, None
|
||||
# Opt-in TRUE headless, shared with the async class. It existed on the
|
||||
# async API ONLY until 2026-07-27: a documented env var that worked
|
||||
# depending on which entry point the caller happened to pick, which is
|
||||
# the same drift that shipped the process-leak fix to half the users.
|
||||
if true_headless_requested():
|
||||
return True
|
||||
vd = make_virtual_display()
|
||||
if vd is not None:
|
||||
vd.start()
|
||||
self._virtual_display = vd
|
||||
return False
|
||||
return True, None
|
||||
return False, make_virtual_display()
|
||||
|
||||
async def _resolve_headless_async(self) -> bool:
|
||||
"""`_resolve_headless` for the async API: the display starts in a worker.
|
||||
|
||||
Starting the surface is a blocking call - on Linux it spawns an Xvfb
|
||||
and waits for it to report ready (~75 ms measured, seconds on a loaded
|
||||
host) - and `__aenter__` made it on the user's loop, so every other
|
||||
browser of the process stood still for that long, `headless=True`
|
||||
or not. The surface is the same and is still created before the prefs
|
||||
are composed; only the thread changes. The sync API keeps the direct
|
||||
call: nothing else runs on its thread.
|
||||
"""
|
||||
pw_headless, vd = self._plan_headless()
|
||||
if vd is None:
|
||||
return pw_headless
|
||||
started = asyncio.ensure_future(asyncio.to_thread(vd.start))
|
||||
try:
|
||||
await asyncio.shield(started)
|
||||
except asyncio.CancelledError:
|
||||
# The worker cannot be interrupted and may yet create the surface
|
||||
# for a launch nobody is waiting for: release it when it ends.
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
def release(done: "asyncio.Future") -> None:
|
||||
if not done.cancelled() and done.exception() is None:
|
||||
loop.run_in_executor(None, vd.stop)
|
||||
|
||||
started.add_done_callback(release)
|
||||
raise
|
||||
self._virtual_display = vd
|
||||
return pw_headless
|
||||
|
||||
def _take_display(self) -> Any:
|
||||
"""THE release, made once for both APIs: the hidden surface this session started, taken out of it (None when there is none).
|
||||
|
||||
The counterpart of `_plan_headless`: the two teardowns only decide WHERE the stop runs - inline in the sync client, off the
|
||||
loop in the async one. Stopping waits for the Xvfb to exit (`Popen.wait`, a loop of sleeps on POSIX), and on the user's loop
|
||||
that wait held every other browser of the process (e2e Linux, run 43701692047)."""
|
||||
display, self._virtual_display = self._virtual_display, None
|
||||
return display
|
||||
|
||||
def _default_context_kwargs(self) -> Dict[str, Any]:
|
||||
# The screen and viewport in CSS pixels, derived once in the core:
|
||||
@@ -546,24 +592,3 @@ class CommonLaunch:
|
||||
_enable_cursor_engine(
|
||||
owner, seed=self.seed, max_seconds=_cursor_max_seconds(self._humanize)
|
||||
)
|
||||
|
||||
def _bind_process_tree(self) -> None:
|
||||
"""Tie the browser tree to this process's lifetime, at the OS level.
|
||||
|
||||
MEASURED before being written, because the first attempt at this fixed
|
||||
a path that was not broken: an exception out of the `with` block does
|
||||
NOT leak - __exit__ runs and Playwright cleans up, zero survivors over
|
||||
an interleaved A/B. The leak is the killed-runner path, where __exit__
|
||||
never executes at all: launch, kill the runner, and eight processes
|
||||
were still alive; twelve on the second attempt. Nothing written inside
|
||||
_teardown can reach that, so the guarantee comes from a Windows job
|
||||
object that the kernel empties when this process's handle closes,
|
||||
however this process ends.
|
||||
|
||||
Best-effort by construction: a failure here leaves the pre-existing
|
||||
behaviour rather than breaking a launch that is otherwise fine.
|
||||
"""
|
||||
try:
|
||||
self._lifetime_guard.bind(self._session_token)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - spostato in invisible_core._webgl_personas (alias completo)."""
|
||||
import sys as _sys
|
||||
from invisible_core import _webgl_personas as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -15,7 +15,9 @@ from invisible_core._fpforge import Profile, generate_profile
|
||||
from invisible_core import SessionLocale, persona_cookies, prepare_session_geo, record_session_seed, resolve_session_seed
|
||||
from ._engine import assert_wire_version, resolve_executable
|
||||
from invisible_core import configure_proxy as _configure_proxy_shared
|
||||
from ._reaper import SessionToken, guard_for
|
||||
from invisible_core._offloop import off_the_loop
|
||||
from invisible_core.process import SessionToken, guard_for
|
||||
from ._juggler._reaped import final_reap
|
||||
|
||||
|
||||
class InvisiblePlaywright(_session.CommonLaunch):
|
||||
@@ -52,8 +54,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._extra_args = list(extra_args or [])
|
||||
self._humanize = humanize
|
||||
# See the sync launcher: who draws the cursor path (this package by
|
||||
# default, the browser under INVPW_CURSOR_ENGINE=binary, nobody when
|
||||
# humanize is falsy). Decided here because the prefs depend on it.
|
||||
# default, nobody when humanize is falsy or INVPW_CURSOR_ENGINE=off).
|
||||
# Decided here because the prefs depend on it.
|
||||
self._cursor_engine = resolve_cursor_engine(humanize)
|
||||
# See the sync launcher: independent of `humanize`, deliberately.
|
||||
# ⛔ NOT `bool(...)`: that would collapse None - "the caller did not
|
||||
@@ -129,7 +131,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# the REAL result of _resolve_headless (did it create an
|
||||
# alternate desktop or not?) must be known BEFORE composing the
|
||||
# prefs, not after: B172, 2026-08-24.
|
||||
pw_headless = self._resolve_headless()
|
||||
pw_headless = await self._resolve_headless_async()
|
||||
prefs = self._build_prefs()
|
||||
playwright_proxy = _configure_proxy_shared(self._proxy, prefs)
|
||||
self._session_token = SessionToken.mint()
|
||||
@@ -153,7 +155,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
env=env,
|
||||
**self._default_context_kwargs(),
|
||||
)
|
||||
self._bind_process_tree()
|
||||
self._arm_cursor_engine(self._persistent_context)
|
||||
return self._persistent_context
|
||||
self._browser = await self._pw.firefox.launch(
|
||||
@@ -167,7 +168,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# See the sync launcher: browser.version comes from the connection
|
||||
# initializer, costs no round trip, and cannot be spoofed by a pref.
|
||||
assert_wire_version(self._browser)
|
||||
self._bind_process_tree()
|
||||
except BaseException:
|
||||
await self._teardown()
|
||||
raise
|
||||
@@ -351,18 +351,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
if self._pw is not None:
|
||||
await close(self._pw.stop())
|
||||
self._pw = None
|
||||
if self._virtual_display is not None:
|
||||
# Synchronous, so it cannot be cancelled mid-call the way the
|
||||
# three awaits above can.
|
||||
try:
|
||||
self._virtual_display.stop()
|
||||
except Exception:
|
||||
pass
|
||||
self._virtual_display = None
|
||||
display = self._take_display()
|
||||
if display is not None:
|
||||
# Off the loop like its start (`_resolve_headless_async`): a cancellation stops the waiting, not the stop.
|
||||
await close(off_the_loop(display.stop))
|
||||
finally:
|
||||
if self._session_token:
|
||||
# ⛔ NOT ON THE LOOP: `reap` waits for the tree of the session to be gone. It runs in a thread of its own
|
||||
# (`off_the_loop`); a cancellation of this task stops the waiting and not the reaping, which runs to its end.
|
||||
try:
|
||||
self._lifetime_guard.reap(self._session_token)
|
||||
await off_the_loop(final_reap, self._lifetime_guard, self._session_token)
|
||||
except asyncio.CancelledError as stop:
|
||||
cancelled = stop
|
||||
except Exception:
|
||||
pass
|
||||
self._session_token = SessionToken()
|
||||
|
||||
@@ -38,7 +38,7 @@ import argparse
|
||||
import sys
|
||||
|
||||
from . import __version__
|
||||
from invisible_core import BINARY_VERSION, FIREFOX_UPSTREAM_VERSION
|
||||
from invisible_core import BINARY_VERSION, FIREFOX_UPSTREAM_VERSION, ensure_intermediates
|
||||
from invisible_core.download import cache_root, engine_root, ensure_binary # noqa: F401
|
||||
|
||||
from ._pin import (
|
||||
@@ -86,6 +86,12 @@ def _cmd_fetch(_args: argparse.Namespace) -> int:
|
||||
except Exception as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
return 1
|
||||
# The list of preloaded intermediate certificates the core declares to the engine, cached now so the first launch does not download it in line. A
|
||||
# failure here is a warning and nothing more: it changes neither the exit code nor the last line (the launch declares the list again, or goes on without).
|
||||
try:
|
||||
ensure_intermediates()
|
||||
except Exception as e:
|
||||
print(f"warning: the intermediates list could not be fetched: {e}", file=sys.stderr)
|
||||
# Last line, alone, so `$(invisible-playwright fetch)` is a path.
|
||||
print(path)
|
||||
return 0
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - spostato in invisible_core.config (alias completo)."""
|
||||
import sys as _sys
|
||||
from invisible_core import config as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - moved to invisible_core.constants (full alias)."""
|
||||
import sys as _sys
|
||||
from invisible_core import constants as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - spostato in invisible_core.download (alias completo)."""
|
||||
import sys as _sys
|
||||
from invisible_core import download as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -13,7 +13,8 @@ from invisible_core._fpforge import Profile, generate_profile
|
||||
from invisible_core import SessionLocale, persona_cookies, prepare_session_geo, record_session_seed, resolve_session_seed
|
||||
from ._engine import assert_wire_version, resolve_executable
|
||||
from invisible_core import configure_proxy as _configure_proxy_shared
|
||||
from ._reaper import SessionToken, guard_for
|
||||
from invisible_core.process import SessionToken, guard_for
|
||||
from ._juggler._reaped import final_reap
|
||||
|
||||
|
||||
# ⛔ `_NEWTAB_SETTLE = 0.4` AND ITS WRAPPER AROUND `ctx.new_page` USED TO BE
|
||||
@@ -125,8 +126,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
call. Default ``True`` (~1.5 s cap per movement); ``False``
|
||||
disables; a float caps a movement in seconds. The path is
|
||||
drawn from ``seed``, so the same seed replays the same motion.
|
||||
Set ``INVPW_CURSOR_ENGINE=binary`` to go back to letting the
|
||||
browser draw it, or ``=off`` to disable motion process-wide.
|
||||
Set ``INVPW_CURSOR_ENGINE=off`` to disable motion process-wide.
|
||||
locale: BCP-47 tag (e.g. ``"en-US"``) or ``"auto"`` (default).
|
||||
``"auto"`` derives the locale from the egress country - the proxy
|
||||
egress IP, or the host's public IP without a proxy - exactly like
|
||||
@@ -200,9 +200,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._udp_stun_servers = _session.udp_stun_list(udp_stun_servers)
|
||||
self._extra_args = list(extra_args or [])
|
||||
self._humanize = humanize
|
||||
# Who draws the cursor path: this package (default), the browser
|
||||
# (``INVPW_CURSOR_ENGINE=binary``, the way back for anyone depending on
|
||||
# the old behaviour), or nobody (``humanize=False``). Resolved once,
|
||||
# Who draws the cursor path: this package (default), or nobody
|
||||
# (``humanize=False`` or ``INVPW_CURSOR_ENGINE=off``). Resolved once,
|
||||
# here, because the prefs handed to the browser depend on the answer.
|
||||
self._cursor_engine = resolve_cursor_engine(humanize)
|
||||
# ⛔ Stored raw and NOT folded into `_cursor_engine`. The two are
|
||||
@@ -358,7 +357,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
env=env,
|
||||
**self._persistent_context_kwargs(),
|
||||
)
|
||||
self._bind_process_tree()
|
||||
self._arm_cursor_engine(self._persistent_context)
|
||||
return self._persistent_context
|
||||
self._browser = self._pw.firefox.launch(
|
||||
@@ -374,7 +372,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# pref can spoof it. Inside the try so a refusal tears the browser
|
||||
# down instead of leaking the process we just refused.
|
||||
assert_wire_version(self._browser)
|
||||
self._bind_process_tree()
|
||||
except BaseException:
|
||||
# Python doesn't call __exit__ when __enter__ raises - clean up
|
||||
# the virtual display + Playwright manually so we don't leak Xvfb
|
||||
@@ -571,12 +568,12 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
except Exception:
|
||||
pass
|
||||
self._pw = None
|
||||
if self._virtual_display is not None:
|
||||
display = self._take_display()
|
||||
if display is not None:
|
||||
try:
|
||||
self._virtual_display.stop()
|
||||
display.stop()
|
||||
except Exception:
|
||||
pass
|
||||
self._virtual_display = None
|
||||
# Last, and unconditionally: whatever Playwright's close() did or did
|
||||
# not manage, nothing carrying this session's token may outlive it. Each
|
||||
# step above is individually wrapped in `except: pass`, so before this
|
||||
@@ -584,7 +581,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# silence. Only processes positively identified as ours are touched.
|
||||
if self._session_token:
|
||||
try:
|
||||
self._lifetime_guard.reap(self._session_token)
|
||||
final_reap(self._lifetime_guard, self._session_token)
|
||||
except Exception:
|
||||
pass
|
||||
self._session_token = SessionToken()
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Backward-compat shim - spostato in invisible_core.prefs (alias completo)."""
|
||||
import sys as _sys
|
||||
from invisible_core import prefs as _mod
|
||||
_sys.modules[__name__] = _mod
|
||||
@@ -0,0 +1,114 @@
|
||||
"""What a test that expects a page back from the back-forward cache writes down BEFORE it asserts anything, and the wait that leaves it
|
||||
a page the cache can take.
|
||||
|
||||
The test used to read `window.__shown` after `go_back()` and assert on it with nothing else saved: a red said "the page was loaded again" and
|
||||
nobody could tell whether the engine had announced a restore (and the page was loaded again anyway), or Firefox had refused or evicted the page.
|
||||
`read_after_go_back` takes, in one place and before any assertion, what tells them apart:
|
||||
|
||||
* `__shown`: `[False, True]` is a `pageshow` with `persisted` after the first one; `[False]` alone is a document that was built again;
|
||||
* the type of the navigation entry and the `readyState` of the document that answers;
|
||||
* the protocol events since `go_back()`: a restore is announced by the engine with a navigation id that starts with `nav-bfcache-` (and
|
||||
`Page.frameDocumentRestored`); a document that loaded again comes with a `Page.eventFired` `load` and new execution contexts.
|
||||
|
||||
`decide_outcome` writes that down FIRST (stdout, which pytest prints with the failure) and then says which of the two outcomes happened:
|
||||
the page was `restored` from the cache, or the document was built again (`reloaded`). The second is accepted ONLY where Firefox itself may
|
||||
not use the cache: a navigation the PARENT starts (`Page.navigate`, `goto`, to the same site or to another) is checked by the parent against the
|
||||
requests in the old document's loadgroup, and the navigation's own DocumentChannel may still be there when the check runs (measured 2026-11-12,
|
||||
SHIPBFCache log: `AllowedInBFCache` found "requests in the loadgroup" in 15 of 56 goto sessions, never after the page's own navigation). The test then asserts the worker's contract for the outcome that happened, whole, and says which it was.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, List
|
||||
|
||||
#: The navigation id of a restore: Juggler's FrameTree.announceRestoredDocument gives it `nav-bfcache-<n>`; a document loaded again has the id of its load.
|
||||
RESTORE_PREFIX = "nav-bfcache-"
|
||||
|
||||
#: The protocol events that say what the engine did with the document, and the one parameter that names each.
|
||||
_SAID = {
|
||||
"Page.navigationStarted": "navigationId",
|
||||
"Page.navigationCommitted": "navigationId",
|
||||
"Page.eventFired": "name",
|
||||
"Page.frameDocumentRestored": "frameId",
|
||||
"Runtime.executionContextsCleared": None,
|
||||
"Runtime.executionContextCreated": None,
|
||||
"Page.workerCreated": "workerId",
|
||||
"Page.workerDestroyed": "workerId",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Evidence:
|
||||
shown: object
|
||||
navigation_type: object
|
||||
ready_state: object
|
||||
events: List[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def restored(self) -> bool:
|
||||
return self.shown == [False, True]
|
||||
|
||||
@property
|
||||
def engine_announced_a_restore(self) -> bool:
|
||||
return any(e.startswith("Page.navigationCommitted " + RESTORE_PREFIX) for e in self.events)
|
||||
|
||||
def text(self) -> str:
|
||||
return ("[bfcache] after go_back: __shown=%r navigation entry type=%r readyState=%r; the engine announced a restore: %s; events: %s"
|
||||
% (self.shown, self.navigation_type, self.ready_state, "yes" if self.engine_announced_a_restore else "no",
|
||||
self.events))
|
||||
|
||||
def why_not(self) -> str:
|
||||
if self.engine_announced_a_restore:
|
||||
return ("the engine announced a restore (%s...) but the page did not run a pageshow with persisted after its first one"
|
||||
% RESTORE_PREFIX)
|
||||
return ("the page was built again instead of restored from the back-forward cache (no restore was announced by the engine), "
|
||||
"so this test proves nothing")
|
||||
|
||||
|
||||
def summarize_events(events, start: int) -> List[str]:
|
||||
"""The events since ``start`` that say what became of the document, one short string each, in order."""
|
||||
said = []
|
||||
for method, params in events[start:]:
|
||||
if method not in _SAID:
|
||||
continue
|
||||
key = _SAID[method]
|
||||
said.append(method if key is None else "%s %s" % (method, params.get(key)) + (
|
||||
" %s" % params.get("url") if method == "Page.navigationCommitted" else ""))
|
||||
return said
|
||||
|
||||
|
||||
def read_after_go_back(page, events, start: int) -> Evidence:
|
||||
"""Everything the test knows right after ``go_back()``, taken before any assertion."""
|
||||
return Evidence(
|
||||
shown=page.evaluate("window.__shown"),
|
||||
navigation_type=page.evaluate("() => { const e = performance.getEntriesByType('navigation')[0]; return e ? e.type : null; }"),
|
||||
ready_state=page.evaluate("document.readyState"),
|
||||
events=summarize_events(events, start),
|
||||
)
|
||||
|
||||
|
||||
def decide_outcome(evidence: Evidence, may_reload: bool, write: Callable[[str], None] = print) -> str:
|
||||
"""Write the evidence down (always, first), then say what happened: ``"restored"``, or ``"reloaded"`` when the document was built again
|
||||
and ``may_reload`` (the case where Firefox may refuse the cache); anything else fails, naming why and carrying the evidence. A restore
|
||||
the engine announced that the page did not see fails even where a reload is accepted: that is a defect of ours, not of the cache."""
|
||||
outcome = "restored" if evidence.restored else (
|
||||
"reloaded" if may_reload and not evidence.engine_announced_a_restore else "failed")
|
||||
write(evidence.text() + " => outcome: " + outcome)
|
||||
assert outcome != "failed", "%s: %s" % (evidence.why_not(), evidence.text())
|
||||
return outcome
|
||||
|
||||
|
||||
def wait_cacheable(page, seconds: float = 10.0) -> None:
|
||||
"""Until every document of the page that records `pageshow` has had it. A document whose `pageshow` has not run is still marked as
|
||||
loading and Firefox will not cache it (Document::OnPageShow clears the mark): the lab does not leave before that, however slow the
|
||||
machine is. The worker has started and answered before this: the callers asked it twice."""
|
||||
def shown() -> bool:
|
||||
return all(frame.evaluate("(window.__shown || [0]).length >= 1") for frame in page.frames)
|
||||
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
if shown():
|
||||
return
|
||||
time.sleep(0.1)
|
||||
assert shown(), "a document of the page never ran its pageshow: %r" % [f.url for f in page.frames]
|
||||
@@ -0,0 +1,161 @@
|
||||
"""The verdicts of `test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py`, as pure functions of what its client recorded (so a
|
||||
unit test feeds them the red case and the green case without a browser).
|
||||
|
||||
None of them reads how long something took: a loop that is held is told by WHERE the thread of the loop was (inside a blocking step of
|
||||
the close), a browser that keeps answering is told by the ORDER of the events (a call that began and ended while the close was in
|
||||
flight, and answers that came while the removal of the profile was held), and the removal of the profile is told by WHICH THREAD
|
||||
reached it (the reaper's or its continuation's, never the loop's nor one of the close's) and by the order of the close's return and
|
||||
the release of the hold. A machine that is slow stretches every duration and changes none of these.
|
||||
|
||||
``gate`` is what the client recorded of the removal of the closing browser's profile, which the test holds still (the stimulus):
|
||||
``{"reached": bool, "released_by": "answered" | "deadline" | None, "order": [the events in the order they happened: "reached",
|
||||
"close_returned", "released"], "removal": {"thread": name, "ident": id of the thread that reached it, "loop_ident": id of the loop's
|
||||
thread, "stack": ["<file>:<function>", ... outermost first] of the call}}``.
|
||||
|
||||
``inside`` is what the watcher saw of the loop's thread, one entry per frame that was ever on its stack while it was running something
|
||||
(not waiting in the selector): ``{"<file>:<function>": {"n": samples, "stack": [the innermost frames of the first stack it was seen in]}}``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
#: A blocking step of a close: (a part of the file's path, the functions of it). They WAIT (for the processes of the tree, for the
|
||||
#: workers, for the directories to go), so none of them may be on the stack of the thread that runs the loop of the user:
|
||||
#: `InProcessTransport.request_stop`'s `shutdown` and `_join_workers`, `reap` / `reap_session` of the core, `op_close` of the engine's
|
||||
#: dispatcher, and the blocking calls those make (`psutil.wait_procs`, `shutil.rmtree`, `Thread.join`).
|
||||
BLOCKING_STEPS: Tuple[Tuple[str, Tuple[str, ...]], ...] = (
|
||||
("/invisible_playwright/", ("shutdown", "_join_workers", "op_close")),
|
||||
("/invisible_core/", ("shutdown", "reap", "reap_session")),
|
||||
("/psutil/", ("wait_procs",)),
|
||||
("/shutil.py", ("rmtree",)),
|
||||
("/threading.py", ("join",)),
|
||||
)
|
||||
|
||||
#: The steps of the close that the user waits for (the first two lines of `BLOCKING_STEPS`): a removal reached inside one of them is a
|
||||
#: removal the close waits for.
|
||||
CLOSE_STEPS: Tuple[Tuple[str, Tuple[str, ...]], ...] = BLOCKING_STEPS[:2]
|
||||
|
||||
#: Where a step handed to `Reaper.then` runs: `run` of the reaper's own thread while it works, `_continue` of the thread it starts for the
|
||||
#: steps handed over after it has finished (the thread that is not the loop's nor the close's).
|
||||
REAPER_STEPS: Tuple[Tuple[str, Tuple[str, ...]], ...] = (("/invisible_core/process.py", ("run", "_continue")),)
|
||||
|
||||
|
||||
def blocked_by(inside: Dict[str, dict], steps: Iterable[Tuple[str, Sequence[str]]] = BLOCKING_STEPS) -> List[str]:
|
||||
"""The frames of ``steps`` that were on the stack of the loop's thread while it ran something, sorted."""
|
||||
found = []
|
||||
for frame in inside:
|
||||
path, _, function = frame.rpartition(":")
|
||||
for part, functions in steps:
|
||||
if part in path and function in functions:
|
||||
found.append(frame)
|
||||
break
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def close_on_the_loop_problem(inside: Dict[str, dict]) -> Optional[str]:
|
||||
"""What is wrong when a step of the close that waits ran on the thread of the loop, or None. Red on a close made on the loop
|
||||
(the defect), whatever the speed of the machine; green on one made in threads of their own."""
|
||||
found = blocked_by(inside)
|
||||
if not found:
|
||||
return None
|
||||
lines = []
|
||||
for frame in found:
|
||||
entry = inside[frame]
|
||||
lines.append("%s (seen in %d samples of the loop's thread), the innermost frames of the first one:\n %s"
|
||||
% (frame, entry["n"], "\n ".join(entry["stack"])))
|
||||
return "the loop's own thread was inside a step of the close that waits:\n" + "\n".join(lines)
|
||||
|
||||
|
||||
def blind_instrument_problem(inside: Dict[str, dict], steps: Iterable[Tuple[str, Sequence[str]]]) -> Optional[str]:
|
||||
"""The control: a loop that was held on purpose, inside the function ``steps`` names, must have been seen there at least once."""
|
||||
if blocked_by(inside, steps):
|
||||
return None
|
||||
return ("the watcher never saw the loop's thread inside %s while the loop was held on purpose: it could not see a close made on "
|
||||
"the loop (frames it did see: %s)" % (list(steps), sorted(inside)[:12]))
|
||||
|
||||
|
||||
def charged_more_than_ran_problem(held: float, busy_run: float) -> Optional[str]:
|
||||
"""The second control: a loop the machine did not schedule waits in its selector, and only the time its thread was seen RUNNING is
|
||||
held. ``busy_run`` is the longest stretch the watcher saw the thread run without a pause in the selector, read off the same
|
||||
samples as ``held``: what is charged can never be more than that. Charging the whole lateness (the wait in the selector too, as
|
||||
the first instrument did: 94 ms with nothing on the loop's thread, candidate 43727128285) is more than that, whatever the machine."""
|
||||
if held <= busy_run:
|
||||
return None
|
||||
return ("the loop was charged %.0f ms of hold and its thread was seen running for at most %.0f ms in a row: the time it waited in "
|
||||
"its selector (the machine did not schedule it) was counted as held" % (held * 1000, busy_run * 1000))
|
||||
|
||||
|
||||
def others_answered_problem(others: Sequence[dict], gate: dict) -> Optional[str]:
|
||||
"""What is wrong with the way the other browsers answered while the first one closed, or None.
|
||||
|
||||
``others`` has one record per other browser: ``inside`` is the calls that began AFTER the close began and ended BEFORE it ended
|
||||
(a call that was answered during the close, in the order of the events, not by how long it took), ``during_removal`` the calls
|
||||
that began after the removal of the closing browser's profile was reached and ended while it was still held. ``gate`` says how that
|
||||
hold ended: ``reached`` (the removal ran), ``released_by``: ``answered`` (the close had returned and every other browser had
|
||||
answered a call that began after the removal was reached: the loop was free while the removal waited) or ``deadline`` (they had not,
|
||||
in 30 s: the loop could not run while the removal was waiting, which is a removal made on the loop's thread)."""
|
||||
if len(others) != 3:
|
||||
return "the client followed %d other browsers instead of 3: %r" % (len(others), others)
|
||||
silent = [i for i, r in enumerate(others) if r["inside"] < 1]
|
||||
if silent:
|
||||
return ("the other browsers %s did not answer a single call that began and ended inside the close (calls inside it, per "
|
||||
"browser: %s): the loop that serves them did not run during the close" % (silent, [r["inside"] for r in others]))
|
||||
if gate.get("reached") and gate.get("released_by") != "answered":
|
||||
return ("the removal of the profile was held until every other browser answered, and they did not (%s): the loop that "
|
||||
"serves them could not run while the removal waited, so the removal ran on it (answers during the removal, per "
|
||||
"browser: %s)" % (gate.get("released_by"), [r["during_removal"] for r in others]))
|
||||
if gate.get("reached"):
|
||||
mute = [i for i, r in enumerate(others) if r["during_removal"] < 1]
|
||||
if mute:
|
||||
return ("the other browsers %s did not answer a call that began and ended while the removal of the profile was held "
|
||||
"(answers during the removal, per browser: %s)" % (mute, [r["during_removal"] for r in others]))
|
||||
return None
|
||||
|
||||
|
||||
def removal_never_reached_problem(gate: dict) -> Optional[str]:
|
||||
"""What is wrong when the removal of the closing browser's profile was never reached, or None. The client waits for it after the
|
||||
close has returned (30 s, the deadline of a hang): a close that removes nothing through the instrumented call would pass every other
|
||||
verdict by not being gated."""
|
||||
if gate.get("reached"):
|
||||
return None
|
||||
return ("the removal of the profile never ran through `shutil.rmtree` after the first browser closed (waited 30 s after the close "
|
||||
"returned): there was nothing held, so the others were not judged on a removal in flight (%r)" % (gate,))
|
||||
|
||||
|
||||
def removal_on_the_users_thread_problem(gate: dict) -> Optional[str]:
|
||||
"""What is wrong when the removal ran on a thread that the user waits on, or None.
|
||||
|
||||
The close of a browser returns once the browser has exited and the removal of its profile is the reaper's: the thread that reaches
|
||||
it is the one that ends the tree (`Reaper.run`) or the continuation of a reaper that had finished (`Reaper._continue`). Red when it
|
||||
is the loop's thread, a thread inside a step of the close (`CLOSE_STEPS`), or any thread that is not the reaper's. A removal that
|
||||
was never reached is `removal_never_reached_problem`'s."""
|
||||
removal = gate.get("removal")
|
||||
if not gate.get("reached"):
|
||||
return None
|
||||
if not removal:
|
||||
return "the removal was reached and the client recorded no thread for it: %r" % (gate,)
|
||||
frames = "\n ".join(removal.get("stack", [])[-8:])
|
||||
where = "on the thread %r, in:\n %s" % (removal.get("thread"), frames)
|
||||
if removal.get("ident") == removal.get("loop_ident"):
|
||||
return "the removal of the profile ran on the thread of the loop, %s" % where
|
||||
stack = {frame: {} for frame in removal.get("stack", [])}
|
||||
waits = blocked_by(stack, CLOSE_STEPS)
|
||||
if waits:
|
||||
return "the removal of the profile ran inside a step of the close that the user waits for (%s), %s" % (waits, where)
|
||||
if not blocked_by(stack, REAPER_STEPS):
|
||||
return "the removal of the profile ran on a thread that is not the reaper's nor its continuation, %s" % where
|
||||
return None
|
||||
|
||||
|
||||
def close_waited_for_the_removal_problem(gate: dict) -> Optional[str]:
|
||||
"""What is wrong when the close of the first browser returned only after the removal of its profile was released, or None.
|
||||
|
||||
The removal is held by the test until the close has returned and the other browsers have answered. A close that waits for the
|
||||
removal cannot return while it is held: it returns after the hold ended, at its deadline. The order of the events decides."""
|
||||
order = list(gate.get("order") or [])
|
||||
if "close_returned" not in order:
|
||||
return "the close of the first browser never returned (events: %s)" % order
|
||||
if "released" in order and order.index("released") < order.index("close_returned"):
|
||||
return ("the close of the first browser returned only after the removal of its profile was released (%s, events: %s): the "
|
||||
"close waited for the removal" % (gate.get("released_by"), order))
|
||||
return None
|
||||
+27
-5
@@ -37,8 +37,25 @@ def delta_by_type(start: Dict[int, Tuple[str, float]], last: Dict[int, Tuple[str
|
||||
return out
|
||||
|
||||
|
||||
def is_engine(proc) -> bool:
|
||||
"""True when the process runs the firefox executable (its file name, whatever name the process gave itself)."""
|
||||
import psutil
|
||||
|
||||
try:
|
||||
exe = proc.exe()
|
||||
except (psutil.Error, OSError):
|
||||
exe = ""
|
||||
# Either separator: the file name of the executable, whichever system wrote the path.
|
||||
return (exe or proc.name()).replace("\\", "/").rsplit("/", 1)[-1].lower().startswith("firefox")
|
||||
|
||||
|
||||
def engine_processes(root_pid: int) -> Dict[int, Tuple[str, float]]:
|
||||
"""pid -> (type, cumulative CPU seconds) of every process named firefox below `root_pid`, now."""
|
||||
"""pid -> (type, cumulative CPU seconds) of every process of the engine below `root_pid`, now.
|
||||
|
||||
⛔ AN ENGINE PROCESS IS KNOWN BY ITS EXECUTABLE, NOT BY ITS NAME. On Linux a child names itself after its role ("Web Content",
|
||||
"Isolated Web Co", "forkserver", "Socket Process", read from /proc/<pid>/comm) while its executable stays the firefox binary, so a
|
||||
filter on the name kept the parent alone and the content processes were never counted (e2e Linux, run 43701692047). On Windows the
|
||||
name and the executable are the same file."""
|
||||
import psutil
|
||||
|
||||
out: Dict[int, Tuple[str, float]] = {}
|
||||
@@ -48,7 +65,7 @@ def engine_processes(root_pid: int) -> Dict[int, Tuple[str, float]]:
|
||||
return out
|
||||
for proc in below:
|
||||
try:
|
||||
if not proc.name().lower().startswith("firefox"):
|
||||
if not is_engine(proc):
|
||||
continue
|
||||
times = proc.cpu_times()
|
||||
out[proc.pid] = (classify(proc.cmdline()), times.user + times.system)
|
||||
@@ -81,9 +98,14 @@ class CpuSampler:
|
||||
self._thread.start()
|
||||
|
||||
def end(self) -> Dict[str, float]:
|
||||
"""Stop, take one more sample, and return the CPU seconds of the window by type."""
|
||||
"""Stop, take one more sample, and return the CPU seconds of the window by type.
|
||||
|
||||
The window ends HERE. The counters are cumulative, so the sample taken now already holds everything the processes used until
|
||||
this call: waiting before it (the old ``sleep(0.3)``) added a third of a second of whatever the browser did after the
|
||||
measured work to the number, and a slower machine added more. The sampler's thread is waited for up to 30 s (it ends at once:
|
||||
its only wait is the event just set, after the sample it was in the middle of), and a sample still running then is a hang."""
|
||||
self._halt.set()
|
||||
self._thread.join(timeout=10)
|
||||
time.sleep(0.3)
|
||||
self._thread.join(timeout=30)
|
||||
assert not self._thread.is_alive(), "the CPU sampler's thread did not end within 30 s of being told to stop"
|
||||
self._take()
|
||||
return delta_by_type(self.start, self.last)
|
||||
+14
-5
@@ -240,6 +240,11 @@ class FakeDoh:
|
||||
self._failed: Set[Tuple[str, int]] = set()
|
||||
#: Every query, in order.
|
||||
self.queries: List[DohQuery] = []
|
||||
#: The same questions, in the same order, as (name, type, connection): ``connection`` is what the one that handed the
|
||||
#: socket to :meth:`serve` called it (the index of the control connection of the gateway that carried the CONNECT to this
|
||||
#: DoH; None for a socket nobody named). It says WHICH connection carried each question, exactly, with no guess from ports.
|
||||
self.question_connections: List[Tuple[str, int, Optional[int]]] = []
|
||||
self._local = threading.local()
|
||||
#: The names for which this server answered a type 65 (HTTPS) query WITH DATA. It never does: the retail Firefox reads
|
||||
#: h3 at its first visit when the DNS answer carries that record, so a test that expects h2 first (the h3 e2e) asserts
|
||||
#: that this stays empty, and says so if the server learns to serve it.
|
||||
@@ -316,8 +321,10 @@ class FakeDoh:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn, "direct"), daemon=True).start()
|
||||
|
||||
def serve(self, sock: socket.socket, via: str) -> None:
|
||||
"""Serve one connection (TLS first) that arrived by ``via``. Blocks until it ends, and closes ``sock``."""
|
||||
def serve(self, sock: socket.socket, via: str, connection: Optional[int] = None) -> None:
|
||||
"""Serve one connection (TLS first) that arrived by ``via``, named ``connection`` by whoever hands it over (see
|
||||
:attr:`question_connections`). Blocks until it ends, and closes ``sock``."""
|
||||
self._local.connection = connection
|
||||
try:
|
||||
sock.settimeout(60)
|
||||
tls = self._context.wrap_socket(sock, server_side=True)
|
||||
@@ -405,6 +412,7 @@ class FakeDoh:
|
||||
return bad(400)
|
||||
with self._lock:
|
||||
self.queries.append(DohQuery(query.name, query.qtype, via))
|
||||
self.question_connections.append((query.name, query.qtype, getattr(self._local, "connection", None)))
|
||||
names = dict(self.names)
|
||||
kind = self.fail_first.get(query.name)
|
||||
if kind is not None and (query.name, query.qtype) in self._failed:
|
||||
@@ -666,15 +674,16 @@ class DohGateway(Gateway):
|
||||
if (host, port) in DOH_TARGETS:
|
||||
self.connects.append((host, port))
|
||||
self._send(c, self._reply(0))
|
||||
connection = getattr(self._local, "index", None) # the control connection that carries this tunnel: said to the DoH
|
||||
if self.tcp_data_delay and self.rtt: # a far gateway: every chunk of the tunnel waits half the round trip
|
||||
near, far = socket.socketpair()
|
||||
threading.Thread(target=self.doh.serve, args=(far, self.name), daemon=True).start()
|
||||
threading.Thread(target=self.doh.serve, args=(far, self.name, connection), daemon=True).start()
|
||||
try:
|
||||
relay(c, near, self.rtt / 2)
|
||||
finally:
|
||||
near.close()
|
||||
return
|
||||
self.doh.serve(c, self.name)
|
||||
self.doh.serve(c, self.name, connection)
|
||||
return
|
||||
if (host, port) in (WHOAMI4, WHOAMI6, (WEB_NAME, 80)):
|
||||
super()._connect(c, host, port)
|
||||
@@ -686,7 +695,7 @@ class DohGateway(Gateway):
|
||||
return
|
||||
self.connects.append((host, port))
|
||||
try:
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
upstream = socket.create_connection((host, port), timeout=30)
|
||||
except OSError:
|
||||
self._send(c, self._reply(5))
|
||||
return
|
||||
|
||||
@@ -0,0 +1,746 @@
|
||||
"""What an e2e test of this repository must not depend on: the reading of the sources behind ``test_the_e2e_tests_do_not_wait_on_clocks.py``.
|
||||
|
||||
An e2e test is red for no fault of the product when its verdict depends on something that is not the product: the speed of the machine (a fixed pause before
|
||||
a read, an absolute bound on a duration), a resource the workers share (a literal port, ``os.environ``), or the world (a real site, a service of the internet).
|
||||
This module reads the e2e files and the helpers of ``tests/`` with ``ast`` (a word in a comment or in a docstring counts for nothing) and says where each of those
|
||||
is. It decides nothing about what is allowed: the exceptions are a reviewed list (``tests/gates/e2e_clock_exceptions.json``), and the occurrences that are
|
||||
dangerous and not yet corrected are the ``debt`` of that file, which a script regenerates (``scripts/e2e_clock_exceptions.py --write``).
|
||||
|
||||
THE RULES (a stable name each; ``CLASS`` is the letter of the audit of the e2e tests that the rule belongs to):
|
||||
|
||||
* ``sleep`` (A): ``time.sleep``, ``asyncio.sleep`` (not ``sleep(0)``), ``.wait_for_timeout(``. A fixed pause and then a read judges the speed of the machine.
|
||||
* ``js-timer`` (A): ``setTimeout(`` / ``setInterval(`` in a string of the test (a page of the test): when the verdict depends on when it fires, it judges the machine.
|
||||
* ``bound`` (B): ``assert <something that is a duration> < <an absolute limit>`` (``<=`` too): an upper bound on a time. An absolute limit is a number, a name in capitals,
|
||||
a variable NAMED a limit (``limit_s``, ``max_ms``), or anything an absolute slack is added to (``rtt_ms + 250``, ``control + 0.5``). A bound against a value measured in the
|
||||
same run and scaled (``took <= control * 3``) is not flagged, and neither is a lower bound (it cannot fail because the machine is slow).
|
||||
* ``port`` (C): a port written as a number in a ``bind``, a ``*Server((addr, N))``, a ``port=N``, a ``"...port": N`` or a ``NAME_PORT = N`` (N not 0). Two workers that
|
||||
run at once, or a port someone else holds, make it red.
|
||||
* ``env`` (C): ``os.environ`` written (``[k] = v``, ``pop``, ``setdefault``, ``update``, ``del``, ``putenv``): ``monkeypatch.setenv`` undoes itself, this does not.
|
||||
* ``net`` (D): a ``http(s)://`` URL of a real host, ``urlopen``, ``requests.get``, a ``pip install``, outside the files of the round after a publication.
|
||||
* ``count`` (E): ``assert len(<processes, pids, children>) == N``: a number of processes the product does not promise (``_processes.py`` and ``_waits.py`` are how it is counted).
|
||||
* ``timeout`` (F): an explicit deadline under 30 s on a wait for something that MUST happen: ``timeout=`` (``wait_for_*``, ``expect_*``, ``goto``, an action, ``join``, ``urlopen``,
|
||||
``create_connection``, a subprocess), ``set_default_timeout(...)``, ``set_default_navigation_timeout(...)``, the default of a parameter named ``timeout``. A deadline is the
|
||||
time a healthy run is allowed, and a loaded runner takes longer than a developer's machine: 30 s is the one the whole suite uses (the unit is read from the callee:
|
||||
milliseconds for the Playwright API, seconds for the standard library and for the helpers of ``tests/``). A wait for something that must NOT happen is accepted by its shape
|
||||
(inside ``pytest.raises``, under a ``try`` that swallows the timeout, or a limit that is NAMED ``NEGATIVE_...``); any other is a reviewed ``entries`` item with its reason.
|
||||
* ``egress`` (D): the conftest has no autouse session fixture that declares the exit of the lab (tests/_lab_egress.py), so a launch asks three services of the internet.
|
||||
|
||||
WHAT IS ACCEPTED WITHOUT A LIST, because it is recognised by its shape: a pause that is the step of a poll with a deadline (a ``while``/``for`` that compares with a clock
|
||||
or a deadline and ends with a ``return``, ``break`` or ``raise``); the body of ``pump``/``pause``/``wait_*``/``*_until``/``poll*``, a function handed by name to ``wait_until``/``watch``/``awatch``, and a lambda passed as the ``pump`` of
|
||||
those; a ``sleep`` in a method of a ``*Handler``/``*Server`` class (a test server that is slow on purpose); a ``sleep(0)``; a test that
|
||||
carries no ``e2e`` marker (it runs in the unit run, with fakes).
|
||||
|
||||
An occurrence is named by ``(file, scope, rule, nth)``: the file, the qualified name of the function or class that holds it (a module-level constant: ``<module>.NAME``), the rule,
|
||||
and its position among the occurrences of that rule in that scope. No line number, so moving code does not break the list.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import ipaddress
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, Optional, Set, Tuple
|
||||
|
||||
TESTS = Path(__file__).resolve().parent
|
||||
|
||||
#: The rule -> the class of the audit.
|
||||
CLASS = {"sleep": "A", "js-timer": "A", "bound": "B", "port": "C", "env": "C", "net": "D", "egress": "D", "count": "E", "timeout": "F"}
|
||||
RULES = tuple(CLASS)
|
||||
|
||||
#: The files that say what is forbidden (their own patterns would be found) and the files of the round after a publication (``net`` is theirs by design).
|
||||
SELF = {"_e2e_clocks.py", "test_the_e2e_tests_do_not_wait_on_clocks.py"}
|
||||
POST_PUBLICATION = ("test_release_e2e.py", "test_upgrade_e2e.py")
|
||||
#: How processes are counted: the one allowed way.
|
||||
COUNTING = {"_processes.py", "_waits.py"}
|
||||
|
||||
_DURATION_WORDS = {"took", "elapsed", "seconds", "secs", "sec", "duration", "wall", "latency", "ms", "held", "late", "waited", "wait", "slowest",
|
||||
"longest", "spent", "rtt", "cpu", "lag", "stall", "delay", "opened"}
|
||||
#: A variable that is named a limit (``limit``, ``max_ms``, ``deadline_s``) is a constant of the test even when it is not written in capitals.
|
||||
_LIMIT_WORDS = {"limit", "limits", "bound", "ceiling", "budget", "timeout", "threshold", "max", "maximum", "allowed", "slack", "margin", "cap"}
|
||||
_CLOCKS = {"monotonic", "perf_counter", "time", "process_time", "time_ns", "monotonic_ns", "perf_counter_ns"}
|
||||
_DEADLINE_NAMES = re.compile(r"(deadline|until|give_?up|stop_at|expires?|budget|limit|timeout|end_at)", re.I)
|
||||
_POLLING_FUNCTIONS = re.compile(r"^(_?pump\w*|_?pause\w*|_?wait\w*|\w*wait_for\w*|\w*_until|_?poll\w*|_?settle\w*|_?spin\w*)$")
|
||||
_PUMP_CALLEES = {"wait_until", "watch", "awatch"}
|
||||
_PROCESS_WORDS = re.compile(r"(pids?|processes|children|procs|content_processes)\b")
|
||||
_SERVER_BASE = re.compile(r"(Handler|Server|Protocol)$")
|
||||
_TIMER = re.compile(r"\bset(?:Timeout|Interval)\(")
|
||||
_URL = re.compile(r"https?://([^\s/:'\"<>)\\]*)(?::[^\s/'\"<>)\\]*)?")
|
||||
#: What stands right before a URL that is a NAME and not an address: the value of an ``xmlns`` / ``xmlns:p`` attribute, or the namespace argument of a DOM
|
||||
#: call that takes one (``createElementNS("...", "svg")``). An XML namespace is an identifier that nothing fetches; a page that writes one in its markup
|
||||
#: (an SVG image, an XHTML island in a ``foreignObject``) makes no request. It is recognised by where it stands, never by which host it names, so a
|
||||
#: request to the same host (``href``, ``src``, ``goto``, ``fetch``) is still a request.
|
||||
_NAMESPACE_OF = re.compile(r"(?:\bxmlns(?::[\w.-]+)?\s*=\s*|\b(?:createElementNS|createAttributeNS|createDocument|setAttributeNS|getAttributeNS"
|
||||
r"|hasAttributeNS|removeAttributeNS|getElementsByTagNameNS)\(\s*)\\?[\"']$")
|
||||
_SAFE_HOST = re.compile(r"(^|\.)(test|invalid|localhost|example|local)$|^localhost$")
|
||||
#: The shortest deadline an e2e test may give to a wait for something that must happen, in seconds.
|
||||
MIN_DEADLINE_S = 30
|
||||
#: The callees whose ``timeout`` is in SECONDS (the standard library and the helpers of ``tests/``); the Playwright API (``goto``, ``wait_for_*``, ``expect_*``, an action) is in milliseconds.
|
||||
_SECONDS_CALLEES = re.compile(r"^(join|acquire|wait|communicate|run|check_call|check_output|call|Popen|urlopen|create_connection|settimeout|get|put|recv|accept|connect|"
|
||||
r"_?run|_?retry\w*|send|launch\w*|wait_until\w*|wait_procs|wait_for_state|wait_for_new_navigation|\w*_s)$")
|
||||
_PLAYWRIGHT_CALLEES = re.compile(r"^(goto|click|dblclick|tap|fill|type|type_text|press|hover|focus|blur|check|uncheck|select_option|set_input_files|set_files|dispatch_event|"
|
||||
r"drag_and_drop|screenshot|inner_text|inner_html|text_content|input_value|scroll_into_view_if_needed|go_back|go_forward|reload|"
|
||||
r"wait_for\w*|expect_\w+|to_\w+|not_to_\w+|set_default_timeout|set_default_navigation_timeout)$")
|
||||
_TIMEOUT_KEYWORD = re.compile(r"(^|_)timeout(_ms|_s)?$")
|
||||
_PIP = re.compile(r"\bpip\b.*\binstall\b|\buv\b.*\b(add|pip|install|sync)\b")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Violation:
|
||||
file: str
|
||||
scope: str
|
||||
rule: str
|
||||
nth: int
|
||||
line: int
|
||||
text: str = ""
|
||||
|
||||
@property
|
||||
def key(self) -> Tuple[str, str, str, int]:
|
||||
return (self.file, self.scope, self.rule, self.nth)
|
||||
|
||||
@property
|
||||
def klass(self) -> str:
|
||||
return CLASS[self.rule]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
# What a node is
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
def _dotted(node: ast.AST) -> str:
|
||||
"""``a.b.c`` of an attribute chain, or the name; '' for anything else."""
|
||||
parts: List[str] = []
|
||||
while isinstance(node, ast.Attribute):
|
||||
parts.append(node.attr)
|
||||
node = node.value
|
||||
if isinstance(node, ast.Name):
|
||||
parts.append(node.id)
|
||||
return ".".join(reversed(parts))
|
||||
return ""
|
||||
|
||||
|
||||
def _marks(node: ast.AST) -> Set[str]:
|
||||
"""The names of the ``pytest.mark.X`` of a decorator list, a ``pytestmark`` value, or one mark."""
|
||||
found: Set[str] = set()
|
||||
for sub in ast.walk(node):
|
||||
if isinstance(sub, ast.Attribute) and isinstance(sub.value, ast.Attribute) and sub.value.attr == "mark":
|
||||
found.add(sub.attr)
|
||||
return found
|
||||
|
||||
|
||||
def _identifier_words(node: ast.AST) -> Set[str]:
|
||||
words: Set[str] = set()
|
||||
for sub in ast.walk(node):
|
||||
names = []
|
||||
if isinstance(sub, ast.Name):
|
||||
names.append(sub.id)
|
||||
elif isinstance(sub, ast.Attribute):
|
||||
names.append(sub.attr)
|
||||
elif isinstance(sub, ast.Constant) and isinstance(sub.value, str) and len(sub.value) < 40:
|
||||
names.append(sub.value)
|
||||
for name in names:
|
||||
words.update(w for w in re.split(r"[^A-Za-z0-9]+|_", name.lower()) if w)
|
||||
return words
|
||||
|
||||
|
||||
def _is_constant_number(node: ast.AST) -> bool:
|
||||
"""A number, or arithmetic of numbers and of NAMES IN CAPITALS (a constant of the module)."""
|
||||
if isinstance(node, ast.Constant):
|
||||
return isinstance(node.value, (int, float)) and not isinstance(node.value, bool)
|
||||
if isinstance(node, ast.Name):
|
||||
return node.id.isupper()
|
||||
if isinstance(node, ast.Attribute):
|
||||
return node.attr.isupper() and isinstance(node.value, (ast.Name, ast.Attribute))
|
||||
if isinstance(node, ast.UnaryOp):
|
||||
return _is_constant_number(node.operand)
|
||||
if isinstance(node, ast.BinOp):
|
||||
return _is_constant_number(node.left) and _is_constant_number(node.right)
|
||||
return False
|
||||
|
||||
_NUMBER_CALLS = {"int": int, "float": float, "min": min, "max": max, "round": round, "abs": abs}
|
||||
|
||||
|
||||
def _number(node: ast.AST, names: Dict[str, float]) -> Optional[float]:
|
||||
"""The value of an expression made of numbers, of the numbers the module names (``names``) and of ``int``/``min``/``max``...; None for anything else (a parameter, a call)."""
|
||||
if isinstance(node, ast.Constant):
|
||||
return node.value if isinstance(node.value, (int, float)) and not isinstance(node.value, bool) else None
|
||||
if isinstance(node, ast.Name):
|
||||
return names.get(node.id)
|
||||
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
|
||||
value = _number(node.operand, names)
|
||||
return None if value is None else (-value if isinstance(node.op, ast.USub) else value)
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv)):
|
||||
left, right = _number(node.left, names), _number(node.right, names)
|
||||
if left is None or right is None:
|
||||
return None
|
||||
try:
|
||||
return {ast.Add: lambda: left + right, ast.Sub: lambda: left - right, ast.Mult: lambda: left * right,
|
||||
ast.Div: lambda: left / right, ast.FloorDiv: lambda: left // right}[type(node.op)]()
|
||||
except ZeroDivisionError:
|
||||
return None
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _NUMBER_CALLS and node.args and not node.keywords:
|
||||
values = [_number(a, names) for a in node.args]
|
||||
if all(v is not None for v in values):
|
||||
return _NUMBER_CALLS[node.func.id](*values) # type: ignore[arg-type]
|
||||
return None
|
||||
|
||||
|
||||
#: The objects of the package under test that take a ``timeout`` in SECONDS (the actions and the lifecycle of the driver), where the Playwright API takes milliseconds.
|
||||
_SECONDS_RECEIVERS = {"actions", "lifecycle", "lc", "inj", "sess", "session", "conn", "connection", "transport"}
|
||||
|
||||
|
||||
def _receiver(node: ast.AST) -> str:
|
||||
"""The name at the left end of a call chain (``actions`` of ``actions.click(...)``, ``page`` of ``page.locator(x).click(...)``)."""
|
||||
while isinstance(node, (ast.Attribute, ast.Call, ast.Subscript)):
|
||||
node = node.func if isinstance(node, ast.Call) else node.value
|
||||
return node.id if isinstance(node, ast.Name) else ""
|
||||
|
||||
|
||||
def _deadline_seconds(value: float, callee: str, keyword: str, receiver: str = "", driver: bool = False) -> float:
|
||||
"""A ``timeout`` in seconds: milliseconds for the Playwright API (an object of the driver, ``actions.click`` or ``goto(until=...)``, reads seconds) and for a keyword that says ``_ms``,
|
||||
seconds for the standard library, a keyword that says ``_s`` and the helpers of ``tests/``; any other callee is read by size (a thousand or more is milliseconds)."""
|
||||
if keyword.endswith("_ms"):
|
||||
return value / 1000.0
|
||||
if keyword.endswith("_s") or _SECONDS_CALLEES.match(callee) or ((driver or receiver in _SECONDS_RECEIVERS) and value < 1000):
|
||||
return float(value)
|
||||
if _PLAYWRIGHT_CALLEES.match(callee):
|
||||
return value / 1000.0
|
||||
return value / 1000.0 if value >= 1000 else float(value)
|
||||
|
||||
|
||||
def _is_an_absolute_limit(node: ast.AST) -> bool:
|
||||
"""What an upper bound on a duration is held to be absolute by: a constant (:func:`_is_constant_number`), a variable that is NAMED a limit (``limit_s``, ``max_ms``),
|
||||
or anything with an absolute slack added to it or taken from it (``rtt_ms + 250``, ``control + 0.5``: a stall of the machine longer than the slack is red whatever
|
||||
the control was). A product (``control * 3``) is relative: it grows with a measure of the same run."""
|
||||
if _is_constant_number(node):
|
||||
return True
|
||||
if isinstance(node, (ast.Name, ast.Attribute)):
|
||||
return bool(_identifier_words(node) & _LIMIT_WORDS)
|
||||
if isinstance(node, ast.BinOp):
|
||||
if isinstance(node.op, (ast.Add, ast.Sub)) and any(
|
||||
_is_constant_number(side) for side in (node.left, node.right)):
|
||||
return True
|
||||
return _is_an_absolute_limit(node.left) and _is_an_absolute_limit(node.right)
|
||||
return False
|
||||
|
||||
|
||||
def _reads_a_clock(node: ast.AST) -> bool:
|
||||
for sub in ast.walk(node):
|
||||
if isinstance(sub, ast.Call):
|
||||
name = _dotted(sub.func).rsplit(".", 1)[-1]
|
||||
if name in _CLOCKS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _is_a_duration(node: ast.AST) -> bool:
|
||||
if _reads_a_clock(node):
|
||||
return True
|
||||
return bool(_identifier_words(node) & _DURATION_WORDS)
|
||||
|
||||
|
||||
def _host_is_real(host: str) -> bool:
|
||||
host = host.strip().strip("[]").lower()
|
||||
if not host or host[0] in "{%$" or "{" in host or "%" in host:
|
||||
return False
|
||||
if "." not in host and ":" not in host: # http://x/, http://a/: not a name anyone owns
|
||||
return False
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return not _SAFE_HOST.search(host)
|
||||
return address.is_global # loopback, private, documentation, link-local: not the world
|
||||
|
||||
|
||||
class _Reader(ast.NodeVisitor):
|
||||
def __init__(self, file: str, tree: ast.Module, e2e_file: bool) -> None:
|
||||
self.file = file
|
||||
self.is_test_file = file.startswith("test_")
|
||||
self.e2e_file = e2e_file
|
||||
self.stack: List[str] = []
|
||||
self.assign: Optional[str] = None
|
||||
self.found: List[Tuple[str, str, int, str]] = [] # scope, rule, line, text
|
||||
self.exempt = 0
|
||||
self.module_marks = set()
|
||||
self.class_marks: List[Set[str]] = []
|
||||
self.post = file in POST_PUBLICATION
|
||||
self.server_depth = 0
|
||||
#: The functions this file hands to ``wait_until``/``watch``/``awatch`` by name: their body is the step between two looks of a wait with a deadline.
|
||||
self.pumps: Set[str] = set()
|
||||
for call in ast.walk(tree):
|
||||
if isinstance(call, ast.Call) and _dotted(call.func).rsplit(".", 1)[-1] in _PUMP_CALLEES:
|
||||
self.pumps.update(a.id for a in list(call.args) + [k.value for k in call.keywords] if isinstance(a, ast.Name))
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "pytestmark" for t in node.targets):
|
||||
self.module_marks |= _marks(node.value)
|
||||
#: The numbers the module names (``GOTO_MS = 30000``), so that ``timeout=GOTO_MS`` is read as what it is.
|
||||
self.numbers: Dict[str, float] = {}
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
|
||||
value = _number(node.value, self.numbers)
|
||||
if value is not None:
|
||||
self.numbers[node.targets[0].id] = value
|
||||
for parent in ast.walk(tree):
|
||||
for child in ast.iter_child_nodes(parent):
|
||||
child._parent = parent # type: ignore[attr-defined]
|
||||
self.visit(tree)
|
||||
|
||||
# -- scopes ---------------------------------------------------------------------------------------------------------------------------------
|
||||
@property
|
||||
def scope(self) -> str:
|
||||
if self.stack:
|
||||
return ".".join(self.stack)
|
||||
return "<module>." + self.assign if self.assign else "<module>"
|
||||
|
||||
def add(self, rule: str, node: ast.AST, text: str = "", line: Optional[int] = None) -> None:
|
||||
if self.exempt:
|
||||
return
|
||||
self.found.append((self.scope, rule, line or getattr(node, "lineno", 0), text))
|
||||
|
||||
def _enter_class(self, node: ast.ClassDef) -> None:
|
||||
marks = set()
|
||||
for stmt in node.body:
|
||||
if isinstance(stmt, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "pytestmark" for t in stmt.targets):
|
||||
marks |= _marks(stmt.value)
|
||||
marks |= set().union(*[_marks(d) for d in node.decorator_list]) if node.decorator_list else set()
|
||||
self.class_marks.append(marks)
|
||||
|
||||
def visit_ClassDef(self, node: ast.ClassDef) -> None:
|
||||
self._enter_class(node)
|
||||
self.stack.append(node.name)
|
||||
server = any(_SERVER_BASE.search(_dotted(b).rsplit(".", 1)[-1] or "") for b in node.bases)
|
||||
self.server_depth += 1 if server else 0
|
||||
for stmt in node.body:
|
||||
self.visit(stmt)
|
||||
self.server_depth -= 1 if server else 0
|
||||
self.stack.pop()
|
||||
self.class_marks.pop()
|
||||
|
||||
def _is_e2e_test(self, node: ast.AST) -> bool:
|
||||
marks = set(self.module_marks)
|
||||
for group in self.class_marks:
|
||||
marks |= group
|
||||
for decorator in getattr(node, "decorator_list", []):
|
||||
marks |= _marks(decorator)
|
||||
return "e2e" in marks
|
||||
|
||||
def _visit_function(self, node: ast.AST) -> None:
|
||||
name = node.name # type: ignore[attr-defined]
|
||||
skip = self.is_test_file and name.startswith("test_") and not self._is_e2e_test(node)
|
||||
self.stack.append(name)
|
||||
if skip:
|
||||
self.exempt += 1
|
||||
for decorator in node.decorator_list: # type: ignore[attr-defined]
|
||||
self.visit(decorator)
|
||||
self._visit_defaults(node)
|
||||
for stmt in node.body: # type: ignore[attr-defined]
|
||||
self.visit(stmt)
|
||||
for default in list(node.args.defaults) + [d for d in node.args.kw_defaults if d is not None]: # type: ignore[attr-defined]
|
||||
self.visit(default)
|
||||
if skip:
|
||||
self.exempt -= 1
|
||||
self.stack.pop()
|
||||
|
||||
visit_FunctionDef = _visit_function
|
||||
visit_AsyncFunctionDef = _visit_function
|
||||
|
||||
def visit_Assign(self, node: ast.Assign) -> None:
|
||||
in_module = not self.stack
|
||||
previous = self.assign
|
||||
if in_module and node.targets and isinstance(node.targets[0], ast.Name):
|
||||
self.assign = node.targets[0].id
|
||||
if in_module:
|
||||
for target in node.targets:
|
||||
if isinstance(target, ast.Name) and re.search(r"PORT$", target.id) and isinstance(node.value, ast.Constant) \
|
||||
and isinstance(node.value.value, int) and not isinstance(node.value.value, bool) and node.value.value != 0:
|
||||
self.add("port", node, "%s = %r" % (target.id, node.value.value))
|
||||
for target in node.targets:
|
||||
if self._is_environ_subscript(target):
|
||||
self.add("env", node, "os.environ[...] = ...")
|
||||
self.generic_visit(node)
|
||||
self.assign = previous
|
||||
|
||||
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
|
||||
previous = self.assign
|
||||
if not self.stack and isinstance(node.target, ast.Name):
|
||||
self.assign = node.target.id
|
||||
self.generic_visit(node)
|
||||
self.assign = previous
|
||||
|
||||
def visit_AugAssign(self, node: ast.AugAssign) -> None:
|
||||
if self._is_environ_subscript(node.target):
|
||||
self.add("env", node, "os.environ[...] op= ...")
|
||||
self.generic_visit(node)
|
||||
|
||||
def visit_Delete(self, node: ast.Delete) -> None:
|
||||
for target in node.targets:
|
||||
if self._is_environ_subscript(target):
|
||||
self.add("env", node, "del os.environ[...]")
|
||||
self.generic_visit(node)
|
||||
|
||||
@staticmethod
|
||||
def _is_environ_subscript(node: ast.AST) -> bool:
|
||||
return isinstance(node, ast.Subscript) and _dotted(node.value) in ("os.environ", "environ")
|
||||
|
||||
# -- strings --------------------------------------------------------------------------------------------------------------------------------
|
||||
def _is_docstring(self, node: ast.Constant) -> bool:
|
||||
parent = getattr(node, "_parent", None)
|
||||
if isinstance(parent, ast.Expr):
|
||||
return True
|
||||
return False
|
||||
|
||||
def visit_Constant(self, node: ast.Constant) -> None:
|
||||
if not isinstance(node.value, str) or self._is_docstring(node):
|
||||
return
|
||||
text = node.value
|
||||
for found in _TIMER.finditer(text):
|
||||
self.add("js-timer", node, found.group(0), line=node.lineno + text.count("\n", 0, found.start()))
|
||||
if not self.post:
|
||||
for found in _URL.finditer(text):
|
||||
if _host_is_real(found.group(1)) and not _NAMESPACE_OF.search(text[max(0, found.start() - 48):found.start()]):
|
||||
self.add("net", node, found.group(0), line=node.lineno + text.count("\n", 0, found.start()))
|
||||
if re.fullmatch(r"[\w.-]*port", text) is not None:
|
||||
pass
|
||||
|
||||
def visit_Dict(self, node: ast.Dict) -> None:
|
||||
for key, value in zip(node.keys, node.values):
|
||||
if isinstance(key, ast.Constant) and isinstance(key.value, str) and key.value.lower().endswith("port") \
|
||||
and isinstance(value, ast.Constant) and isinstance(value.value, int) and not isinstance(value.value, bool) and value.value != 0:
|
||||
self.add("port", node, "%s: %r" % (key.value, value.value))
|
||||
self.generic_visit(node)
|
||||
|
||||
# -- calls ----------------------------------------------------------------------------------------------------------------------------------
|
||||
def visit_Call(self, node: ast.Call) -> None:
|
||||
name = _dotted(node.func)
|
||||
leaf = name.rsplit(".", 1)[-1]
|
||||
if self._is_sleep(node, name, leaf) and not self._accepted_pause(node):
|
||||
self.add("sleep", node, "%s(%s)" % (name or leaf, ast.unparse(node.args[0]) if node.args else ""))
|
||||
self._ports_of(node, name, leaf)
|
||||
self._deadlines_of(node, leaf)
|
||||
if name in ("os.environ.pop", "os.environ.setdefault", "os.environ.update", "os.environ.clear", "os.putenv", "os.unsetenv",
|
||||
"environ.pop", "environ.setdefault", "environ.update", "environ.clear"):
|
||||
self.add("env", node, name)
|
||||
if not self.post and leaf in ("run", "check_call", "check_output", "Popen", "call") and name.startswith("subprocess."):
|
||||
installing = _PIP.search(" ".join(re.findall(r"'([^']*)'", ast.unparse(node))))
|
||||
if installing:
|
||||
self.add("net", node, "subprocess " + installing.group(0))
|
||||
if not self.post and (name in ("urllib.request.urlopen", "urlopen") or re.match(r"requests\.(get|post|put|head|request|delete)$", name)):
|
||||
self.add("net", node, name)
|
||||
self.generic_visit(node)
|
||||
|
||||
# -- deadlines ------------------------------------------------------------------------------------------------------------------------------
|
||||
def _deadlines_of(self, node: ast.Call, leaf: str) -> None:
|
||||
"""``timeout``: an explicit deadline under :data:`MIN_DEADLINE_S` on a wait for something that must happen."""
|
||||
leaf = node.func.attr if isinstance(node.func, ast.Attribute) else leaf
|
||||
receiver = _receiver(node.func)
|
||||
found: List[Tuple[ast.AST, str]] = []
|
||||
for keyword in node.keywords:
|
||||
if keyword.arg and _TIMEOUT_KEYWORD.search(keyword.arg):
|
||||
found.append((keyword.value, keyword.arg + "="))
|
||||
if leaf in ("set_default_timeout", "set_default_navigation_timeout") and node.args:
|
||||
found.append((node.args[0], ""))
|
||||
for value_node, label in found:
|
||||
value = _number(value_node, self.numbers)
|
||||
if value is None or value <= 0:
|
||||
continue # a variable (its own definition is read), None, or 0 (no deadline at all)
|
||||
driver = any(k.arg == "until" for k in node.keywords) # ``goto(url, until="load", timeout=30)``: the lifecycle of the driver, in seconds
|
||||
seconds = _deadline_seconds(value, leaf, label.rstrip("=") or "timeout", receiver, driver)
|
||||
if seconds >= MIN_DEADLINE_S or self._is_a_wait_for_nothing(node, value_node):
|
||||
continue
|
||||
self.add("timeout", node, "%s(%s%s)" % (leaf, label, ast.unparse(value_node)))
|
||||
|
||||
def _visit_defaults(self, node: ast.AST) -> None:
|
||||
"""The default of a parameter that is a deadline (``def wait(timeout=5)``): every call that leaves it out waits that long."""
|
||||
arguments = node.args # type: ignore[attr-defined]
|
||||
positional = list(arguments.posonlyargs) + list(arguments.args)
|
||||
pairs = list(zip(positional[len(positional) - len(arguments.defaults):], arguments.defaults)) + [
|
||||
(a, d) for a, d in zip(arguments.kwonlyargs, arguments.kw_defaults) if d is not None]
|
||||
for argument, default in pairs:
|
||||
if not _TIMEOUT_KEYWORD.search(argument.arg):
|
||||
continue
|
||||
value = _number(default, self.numbers)
|
||||
if value is None or value <= 0:
|
||||
continue
|
||||
if _deadline_seconds(value, node.name, argument.arg) < MIN_DEADLINE_S: # type: ignore[attr-defined]
|
||||
self.add("timeout", default, "def %s(%s=%s)" % (node.name, argument.arg, ast.unparse(default))) # type: ignore[attr-defined]
|
||||
|
||||
@staticmethod
|
||||
def _is_a_wait_for_nothing(call: ast.Call, limit: ast.AST) -> bool:
|
||||
"""A wait for something that must NOT happen, by its shape: a limit NAMED ``NEGATIVE...``; a call inside ``with pytest.raises(...)`` (the call is
|
||||
expected to run out of time); a call in the body of a ``try`` whose handler of a timeout goes on without failing. A slow machine can only make
|
||||
such a window a weaker check, never a red."""
|
||||
if isinstance(limit, ast.Name) and "NEGATIVE" in limit.id.upper():
|
||||
return True
|
||||
child: ast.AST = call
|
||||
parent: Optional[ast.AST] = getattr(call, "_parent", None)
|
||||
while parent is not None and not isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
|
||||
if isinstance(parent, (ast.With, ast.AsyncWith)) and child in parent.body:
|
||||
for item in parent.items:
|
||||
context = item.context_expr
|
||||
if isinstance(context, ast.Call) and _dotted(context.func).rsplit(".", 1)[-1] == "raises":
|
||||
return True
|
||||
if isinstance(parent, ast.Try) and child in parent.body:
|
||||
for handler in parent.handlers:
|
||||
caught = ast.unparse(handler.type) if handler.type is not None else ""
|
||||
fails = any(isinstance(sub, (ast.Raise, ast.Assert)) or (isinstance(sub, ast.Call) and _dotted(sub.func).rsplit(".", 1)[-1] in ("fail", "skip"))
|
||||
for sub in ast.walk(handler))
|
||||
if "Timeout" in caught and not fails:
|
||||
return True
|
||||
child, parent = parent, getattr(parent, "_parent", None)
|
||||
return False
|
||||
|
||||
def _is_sleep(self, node: ast.Call, name: str, leaf: str) -> bool:
|
||||
if leaf == "wait_for_timeout":
|
||||
return True
|
||||
if name in ("time.sleep", "asyncio.sleep") or (name == "sleep" and not isinstance(node.func, ast.Attribute)):
|
||||
argument = node.args[0] if node.args else None
|
||||
return not (isinstance(argument, ast.Constant) and argument.value == 0)
|
||||
return False
|
||||
|
||||
def _accepted_pause(self, node: ast.Call) -> bool:
|
||||
"""The shapes of a pause that is not a verdict on the speed of the machine."""
|
||||
function = None
|
||||
parent: Optional[ast.AST] = getattr(node, "_parent", None)
|
||||
lambda_of_a_pump = False
|
||||
loops: List[ast.AST] = []
|
||||
while parent is not None:
|
||||
if isinstance(parent, ast.Lambda):
|
||||
caller = getattr(parent, "_parent", None)
|
||||
if isinstance(caller, ast.keyword) and caller.arg in ("pump", "step", "pause"):
|
||||
lambda_of_a_pump = True
|
||||
elif isinstance(caller, ast.Call) and _dotted(caller.func).rsplit(".", 1)[-1] in _PUMP_CALLEES:
|
||||
lambda_of_a_pump = True
|
||||
if isinstance(parent, (ast.While, ast.For, ast.AsyncFor)):
|
||||
loops.append(parent)
|
||||
if isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
function = parent
|
||||
break
|
||||
parent = getattr(parent, "_parent", None)
|
||||
if lambda_of_a_pump:
|
||||
return True
|
||||
if function is not None and not function.name.startswith("test_") and (_POLLING_FUNCTIONS.match(function.name) or function.name in self.pumps):
|
||||
return True
|
||||
if self.server_depth > 0:
|
||||
return True
|
||||
for loop in loops:
|
||||
if self._is_a_poll_with_a_deadline(loop):
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _is_a_poll_with_a_deadline(loop: ast.AST) -> bool:
|
||||
"""A loop whose pause is the step of a wait that ends: a ``range`` of tries; or a comparison with a clock or a deadline that ends the loop, as its
|
||||
condition (``while not done and time.time() < deadline``), as an assertion inside it, or as a ``return``/``break``/``raise`` it leads to."""
|
||||
if isinstance(loop, (ast.For, ast.AsyncFor)) and isinstance(loop.iter, ast.Call) and _dotted(loop.iter.func) == "range":
|
||||
return any(isinstance(sub, (ast.Return, ast.Break, ast.Raise)) for sub in ast.walk(loop)) # N tries: the deadline is N pauses
|
||||
|
||||
def is_a_deadline(compare: ast.AST) -> bool:
|
||||
return isinstance(compare, ast.Compare) and (
|
||||
_reads_a_clock(compare) or any(_DEADLINE_NAMES.search(w) for w in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", ast.unparse(compare))))
|
||||
|
||||
if isinstance(loop, ast.While) and any(is_a_deadline(sub) for sub in ast.walk(loop.test)):
|
||||
return True
|
||||
if any(isinstance(sub, ast.Assert) and any(is_a_deadline(c) for c in ast.walk(sub.test)) for sub in ast.walk(loop)):
|
||||
return True
|
||||
leaves = any(isinstance(sub, (ast.Return, ast.Break, ast.Raise)) for sub in ast.walk(loop))
|
||||
return leaves and any(is_a_deadline(sub) for sub in ast.walk(loop))
|
||||
|
||||
def _ports_of(self, node: ast.Call, name: str, leaf: str) -> None:
|
||||
if leaf in ("bind", "create_server", "create_datagram_endpoint", "start_server", "serve") or leaf.endswith("Server") or leaf.endswith("Proxy"):
|
||||
for argument in node.args[:1]:
|
||||
if isinstance(argument, ast.Tuple) and len(argument.elts) == 2:
|
||||
port = argument.elts[1]
|
||||
if isinstance(port, ast.Constant) and isinstance(port.value, int) and not isinstance(port.value, bool) and port.value != 0:
|
||||
self.add("port", node, "%s(..., %r)" % (leaf, port.value))
|
||||
for keyword in node.keywords:
|
||||
if keyword.arg == "port" and isinstance(keyword.value, ast.Constant) and isinstance(keyword.value.value, int) \
|
||||
and not isinstance(keyword.value.value, bool) and keyword.value.value != 0:
|
||||
self.add("port", node, "port=%r" % keyword.value.value)
|
||||
|
||||
# -- asserts --------------------------------------------------------------------------------------------------------------------------------
|
||||
@staticmethod
|
||||
def _upper_bounds(test: ast.AST, violated: bool = False) -> List[ast.Compare]:
|
||||
"""The comparisons of ``test`` that bound a duration from above by an absolute limit; ``violated``: the test is the condition that is reported
|
||||
(``if took > LIMIT``), not the one that must hold (``assert took < LIMIT``)."""
|
||||
found: List[ast.Compare] = []
|
||||
for sub in ast.walk(test):
|
||||
if not isinstance(sub, ast.Compare):
|
||||
continue
|
||||
left = sub.left
|
||||
for op, right in zip(sub.ops, sub.comparators):
|
||||
above = (isinstance(op, (ast.Lt, ast.LtE)) and _is_an_absolute_limit(right) and _is_a_duration(left)) \
|
||||
or (isinstance(op, (ast.Gt, ast.GtE)) and _is_an_absolute_limit(left) and _is_a_duration(right))
|
||||
over = (isinstance(op, (ast.Gt, ast.GtE)) and _is_an_absolute_limit(right) and _is_a_duration(left)) \
|
||||
or (isinstance(op, (ast.Lt, ast.LtE)) and _is_an_absolute_limit(left) and _is_a_duration(right))
|
||||
if over if violated else above:
|
||||
found.append(sub)
|
||||
left = right
|
||||
return found
|
||||
|
||||
def visit_If(self, node: ast.If) -> None:
|
||||
"""``bound`` in a judge that hands its problems back as sentences instead of asserting: ``if wall > first + MARGIN_MS: problems.append(...)`` is the same verdict
|
||||
on the machine as the assert. Only an ``if`` that REPORTS (appends, raises, fails) counts: the other ifs of a test are its logic."""
|
||||
reports = any(isinstance(sub, ast.Raise) or (isinstance(sub, ast.Call) and _dotted(sub.func).rsplit(".", 1)[-1] in ("append", "fail"))
|
||||
for stmt in node.body for sub in ast.walk(stmt))
|
||||
if reports:
|
||||
for found in self._upper_bounds(node.test, violated=True):
|
||||
self.add("bound", node, ast.unparse(found)[:80])
|
||||
self.generic_visit(node)
|
||||
|
||||
def visit_Assert(self, node: ast.Assert) -> None:
|
||||
for found in self._upper_bounds(node.test):
|
||||
self.add("bound", node, ast.unparse(found)[:80])
|
||||
for sub in ast.walk(node.test):
|
||||
if not isinstance(sub, ast.Compare):
|
||||
continue
|
||||
left = sub.left
|
||||
for op, right in zip(sub.ops, sub.comparators):
|
||||
if isinstance(op, (ast.Eq, ast.NotEq)) and self.file not in COUNTING:
|
||||
for side in (left, right):
|
||||
if isinstance(side, ast.Call) and _dotted(side.func) in ("len", "sorted") and side.args \
|
||||
and _PROCESS_WORDS.search(ast.unparse(side.args[0])):
|
||||
self.add("count", node, ast.unparse(sub)[:80])
|
||||
left = right
|
||||
self.generic_visit(node)
|
||||
|
||||
|
||||
def _is_e2e_file(tree: ast.Module) -> bool:
|
||||
return any(isinstance(sub, ast.Attribute) and sub.attr == "e2e" and isinstance(sub.value, ast.Attribute) and sub.value.attr == "mark"
|
||||
for sub in ast.walk(tree))
|
||||
|
||||
|
||||
def analyze(source: str, file: str, *, force: bool = False) -> List[Violation]:
|
||||
"""The occurrences of ``source`` (the content of ``tests/<file>``). A test file with no ``e2e`` marker is not read, unless ``force`` (the helpers always are)."""
|
||||
tree = ast.parse(source)
|
||||
e2e = _is_e2e_file(tree) or not file.startswith("test_") or force
|
||||
if not e2e or file in SELF:
|
||||
return []
|
||||
reader = _Reader(file, tree, e2e)
|
||||
reader.found.sort(key=lambda item: item[2])
|
||||
counts: Dict[Tuple[str, str], int] = {}
|
||||
out: List[Violation] = []
|
||||
for scope, rule, line, text in reader.found:
|
||||
counts[(scope, rule)] = counts.get((scope, rule), 0) + 1
|
||||
out.append(Violation(file, scope, rule, counts[(scope, rule)], line, text))
|
||||
return out
|
||||
|
||||
|
||||
def analyze_conftest(source: str) -> List[Violation]:
|
||||
"""``egress``: the conftest declares the exit of the lab for the session, or every launch asks the internet."""
|
||||
tree = ast.parse(source)
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_the_lab_declares_the_exit":
|
||||
for decorator in node.decorator_list:
|
||||
if isinstance(decorator, ast.Call) and _dotted(decorator.func).endswith("fixture"):
|
||||
options = {kw.arg: getattr(kw.value, "value", None) for kw in decorator.keywords}
|
||||
if options.get("scope") == "session" and options.get("autouse") is True and "install" in ast.unparse(node):
|
||||
return []
|
||||
return [Violation("conftest.py", "<module>", "egress", 1, 1, "no autouse session fixture declares the exit of the lab")]
|
||||
|
||||
|
||||
def files(directory: Path = TESTS) -> Iterable[Path]:
|
||||
"""The python files of ``tests/`` (not the subfolders: ``gates/`` is data, ``playwright-upstream/`` is another suite)."""
|
||||
return sorted(p for p in directory.glob("*.py") if p.name not in SELF)
|
||||
|
||||
|
||||
def scan(directory: Path = TESTS) -> List[Violation]:
|
||||
"""Every occurrence of every file of ``tests/``."""
|
||||
out: List[Violation] = []
|
||||
for path in files(directory):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
out.extend(analyze(source, path.name))
|
||||
conftest = directory / "conftest.py"
|
||||
if conftest.is_file():
|
||||
out.extend(analyze_conftest(conftest.read_text(encoding="utf-8")))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
# The reviewed list: ``tests/gates/e2e_clock_exceptions.json``
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
GATE_FILE = TESTS / "gates" / "e2e_clock_exceptions.json"
|
||||
|
||||
#: Why an occurrence is deliberate, as a closed vocabulary:
|
||||
#:
|
||||
#: * ``negative-window``: a fixed window in which something must NOT happen; a slow machine can only make it a weaker check (a false green), never a red.
|
||||
#: * ``stimulus``: the time is the input the test gives: a page timer that fires the thing the product waits for, a server, relay or client that answers late on purpose,
|
||||
#: or a pause between two events the test generates. The product waits with a deadline; the verdict does not read when it fired.
|
||||
#: * ``instrument``: a measuring or a test-server tool: the test of ``wait_for_timeout`` itself, the pause that lets a value settle before it is READ back, the teardown of a
|
||||
#: test server's loop.
|
||||
#: * ``virtual-port``: a port number that is never bound: the gateway of the test answers for it by name.
|
||||
#: * ``post-publication``: the round after a publication (``tests/_post_publication.py``).
|
||||
#: * ``hang-detector``: the deadline of a wait for a thing that must happen (a timer, a step or a limit of 30 s or more that ends the wait of a condition), a limit as high as
|
||||
#: the product's own timeout, or a wait with no clock whose end is an event of the test's own server; it ends a hang, it judges no speed.
|
||||
#: * ``cpu-budget``: a bound on the CPU seconds of a process (user + kernel), not on a time that passes: a machine that is slow or stops stretches the clock and not the CPU,
|
||||
#: and the bound has a margin measured on the runner (it is not a structure, so the reason says the numbers).
|
||||
KINDS = ("negative-window", "stimulus", "instrument", "virtual-port", "post-publication", "hang-detector", "cpu-budget")
|
||||
|
||||
#: What a ``debt`` item says, by rule: why the occurrence can be red for a reason that is nobody's fault, and what replaces it.
|
||||
DEBT_REASON = {
|
||||
"sleep": "A fixed pause and then a read judges the speed of the machine: wait for the condition with a deadline (tests/_waits.py wait_until) and read after it.",
|
||||
"js-timer": "The verdict depends on when a timer of the test page fires against what the product does: let the test decide when the thing happens, then wait for it with a deadline.",
|
||||
"bound": "An absolute upper bound on a duration is a verdict on the machine: compare with a control measured in the same run, or assert the order of the events.",
|
||||
"port": "A literal port is shared by the workers that run at once and by whoever else holds it: bind port 0 and read the port back.",
|
||||
"env": "os.environ written directly is not undone when the test ends or fails: use monkeypatch.setenv, which restores it.",
|
||||
"net": "A real host in a gate is a third party: serve the page and the answer from the test's own server.",
|
||||
"count": "The number of processes is not something the product promises: count by site name or against the pool the product keeps (tests/_processes.py, tests/_waits.py).",
|
||||
"timeout": "A deadline under 30 s on a wait for something that must happen is a verdict on the machine: a loaded runner is slower than the one it was written on. Give it 30 s (or the deadline the product itself has), and read the result after it.",
|
||||
"egress": "The launch asks three services of the internet where it leaves from: declare the exit (tests/_lab_egress.py).",
|
||||
}
|
||||
|
||||
|
||||
def empty_document() -> Dict[str, object]:
|
||||
return {"version": 1, "entries": [], "debt": []}
|
||||
|
||||
|
||||
def load(path: Path = GATE_FILE) -> Dict[str, object]:
|
||||
import json
|
||||
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def dump(document: Dict[str, object]) -> str:
|
||||
"""The file as it is written: stable order, one item per line, a newline at the end (the same bytes whoever writes it)."""
|
||||
import json
|
||||
|
||||
def line(item: Dict[str, object]) -> str:
|
||||
return " " + json.dumps(item, ensure_ascii=False)
|
||||
|
||||
out = ["{", ' "version": %d,' % document["version"]]
|
||||
for name, last in (("entries", False), ("debt", True)):
|
||||
items = sorted(document[name], key=lambda i: (i["file"], i["scope"], i["rule"], i["nth"])) # type: ignore[index, union-attr]
|
||||
out.append(' "%s": [' % name)
|
||||
out.append(",\n".join(line(i) for i in items))
|
||||
out.append(" ]" + ("" if last else ","))
|
||||
out.append("}")
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def key_of(item: Dict[str, object]) -> Tuple[str, str, str, int]:
|
||||
return (str(item["file"]), str(item["scope"]), str(item["rule"]), int(item["nth"])) # type: ignore[call-overload]
|
||||
|
||||
|
||||
def compare(found: Iterable[Violation], document: Dict[str, object]) -> Dict[str, List[Tuple[str, str, str, int]]]:
|
||||
"""``new``: occurrences in no list; ``stale_entries`` / ``stale_debt``: items of a list that match no occurrence; ``both``: in the two lists."""
|
||||
seen = {v.key for v in found}
|
||||
entries = {key_of(i) for i in document["entries"]} # type: ignore[union-attr]
|
||||
debt = {key_of(i) for i in document["debt"]} # type: ignore[union-attr]
|
||||
return {"new": sorted(seen - entries - debt), "stale_entries": sorted(entries - seen), "stale_debt": sorted(debt - seen),
|
||||
"both": sorted(entries & debt)}
|
||||
|
||||
|
||||
def regenerate(document: Dict[str, object], found: Iterable[Violation], *, prune_entries: bool = False) -> Dict[str, object]:
|
||||
"""The document with its ``debt`` made again: every occurrence that no ``entries`` item covers. ``entries`` are reviewed by a person and stay as they
|
||||
are (``prune_entries`` drops the ones that match nothing any more: a correction that removed a deliberate pause)."""
|
||||
found = list(found)
|
||||
seen = {v.key for v in found}
|
||||
entries = [dict(i) for i in document["entries"]] # type: ignore[union-attr]
|
||||
if prune_entries:
|
||||
entries = [i for i in entries if key_of(i) in seen]
|
||||
covered = {key_of(i) for i in entries}
|
||||
# A debt item whose reason a person wrote (why it is not corrected YET, e.g. "waiting for the verdict on the product") keeps it while the
|
||||
# occurrence is there; every other one gets the reason of its rule.
|
||||
written = {key_of(i): i["reason"] for i in document.get("debt", []) # type: ignore[union-attr]
|
||||
if i.get("reason") and i["reason"] != DEBT_REASON.get(i.get("rule", ""))}
|
||||
debt = [{"file": v.file, "scope": v.scope, "rule": v.rule, "nth": v.nth, "class": v.klass, "reason": written.get(v.key, DEBT_REASON[v.rule])}
|
||||
for v in sorted(found, key=lambda v: v.key) if v.key not in covered]
|
||||
return {"version": document.get("version", 1), "entries": entries, "debt": debt}
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Verdicts the e2e tests give from what they recorded, as pure functions of it (so a unit test can feed them the red
|
||||
case and the green case without a browser).
|
||||
|
||||
A verdict here never reads a clock of the machine it runs on: it compares what happened to what happened, or to a
|
||||
control measured in the same launch.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
def cold_association_problem(associations: Sequence[Sequence[Optional[float]]],
|
||||
via: Iterable[Tuple[str, int, int, float]], host: str, born: float) -> Optional[str]:
|
||||
"""What is wrong with the way the first STUN datagram of a PeerConnection left, or None.
|
||||
|
||||
``associations`` are the UDP associations the gateway granted, ``[start, end]`` in seconds from its start (``end``
|
||||
None while unanswered; the first granted one is the core's own probe, made before the browser exists, and is no
|
||||
association of the engine); ``via`` are the datagrams the relay carried, ``(host, port, association index, time)``;
|
||||
``born`` is the birth of the PeerConnection on the gateway's clock.
|
||||
|
||||
The promise is that the first datagram leaves on an association that was ready before the PeerConnection was
|
||||
born, not that it leaves within some number of milliseconds: a cold association is made AFTER the birth, so the
|
||||
datagram that leaves on one is the defect, whatever the speed of the machine."""
|
||||
granted = [i for i, a in enumerate(associations) if a[1] is not None][1:]
|
||||
if not granted:
|
||||
return "the engine never asked the proxy for an association (only the core's probe did)"
|
||||
ready = [i for i in granted if associations[i][1] < born]
|
||||
if not ready:
|
||||
return ("no association was completed before the PeerConnection was born (granted at %s s from the gateway's "
|
||||
"start, the PeerConnection at %.3f s): the first ICE socket made its own, from scratch"
|
||||
% ([round(associations[i][1], 3) for i in granted], born))
|
||||
sent = sorted((t, index) for h, _port, index, t in via if h == host)
|
||||
if not sent:
|
||||
return "no STUN datagram of the PeerConnection reached the relay"
|
||||
at, index = sent[0]
|
||||
if index not in ready:
|
||||
return ("the first STUN datagram (at %.3f s) left on association #%d, granted at %s s, after the PeerConnection "
|
||||
"was born at %.3f s: a cold association, made from scratch (ready before the birth: %s)"
|
||||
% (at, index, associations[index][1] and round(associations[index][1], 3), born, ready))
|
||||
return None
|
||||
|
||||
|
||||
# ── the road of a TURN server written as a name ────────────────────────────────────────────────────────────────────────
|
||||
#
|
||||
# Two promises, and neither is a number of seconds. The first is CAUSAL: the test holds the handshakes that were begun after the
|
||||
# pool of associations was ready (the gateway answers nothing on them, whatever the speed of the machine) and the allocation has to
|
||||
# be answered all the same, while they are held; a handshake that waits for another leaves it waiting until the test lets them go.
|
||||
# The second is a COUNT: the exchanges the gateway, the DoH and the TURN server recorded from the birth of the PeerConnection to
|
||||
# the Allocate answered with credentials are no more than the protocols ask for. A slow machine makes each of them later, never more.
|
||||
|
||||
#: The exchanges of a SOCKS5 control connection (RFC 1928): the method negotiation (section 3) and the request with its reply
|
||||
#: (sections 4 and 6). With a user and a password (RFC 1929, section 2) the sub-negotiation is one more.
|
||||
SOCKS_EXCHANGES = 2
|
||||
SOCKS_AUTH_EXCHANGES = 1
|
||||
#: A name asked of the DoH by a resolver that was told the family it wants (`nriceresolver.cpp` passes RESOLVE_DISABLE_IPV6 for
|
||||
#: AF_INET, and a SOCKS5 UDP relay carries IPv4 here): ONE question, the A record, answered in one HTTP exchange (RFC 8484, section 4).
|
||||
DOH_QUESTIONS = 1
|
||||
#: The Allocate of a TURN client (RFC 8656, section 7.1, with the long-term credential mechanism of RFC 8489, section 9.2): the first
|
||||
#: request carries no credentials and is answered 401 with a REALM and a NONCE, the second carries them and is answered with the
|
||||
#: relayed address. A retransmission of one is the same transaction (same transaction id), so it is not counted twice.
|
||||
ALLOCATE_TRANSACTIONS = 2
|
||||
#: The control connection of the road after the birth that carries the question of the TURN name: ONE, the CONNECT to the DoH, and none
|
||||
#: when the connection that loaded the page is still open and carries it. A connection made again for a question that comes after
|
||||
#: the first one, or a second one for the same name, is a handshake nobody needs. Other connections of the browser (the page's own
|
||||
#: server, the DoH connections it opens in parallel for its own names) are not on this road: they are shown, they decide nothing.
|
||||
CONNECTS_AFTER_THE_BIRTH = 1
|
||||
|
||||
|
||||
def turn_road_connections(born: float, allocated_at: float, requests: Iterable[Tuple[float, int, str, str]],
|
||||
doh_questions: Sequence[Tuple[str, int, Optional[int]]]) -> Tuple[List[Tuple[float, int, str, str]],
|
||||
List[Tuple[float, int, str, str]]]:
|
||||
"""The CONNECTs of ``requests`` after the birth, split in (the ones that carried a question of the TURN name, the others).
|
||||
|
||||
``doh_questions`` are the (name, type, connection) of ``FakeDoh.question_connections`` for the TURN name: ``connection`` is the
|
||||
index of the control connection of the gateway that carried the CONNECT to the DoH, the same number as the second field of
|
||||
``Gateway.requests``. The match is by that number, exact: a connection that carried no question of the name is not on the road."""
|
||||
carried = {q[2] for q in doh_questions if q[2] is not None}
|
||||
after = [r for r in requests if r[2] == "connect" and born <= r[0] <= allocated_at]
|
||||
return [r for r in after if r[1] in carried], [r for r in after if r[1] not in carried]
|
||||
|
||||
|
||||
def turn_exchanges_most(auth: bool = False) -> int:
|
||||
"""The most exchanges the road may cost (see :func:`turn_exchanges_problem`): five with no user and password, six with them."""
|
||||
per_connection = SOCKS_EXCHANGES + (SOCKS_AUTH_EXCHANGES if auth else 0)
|
||||
return CONNECTS_AFTER_THE_BIRTH * per_connection + DOH_QUESTIONS + ALLOCATE_TRANSACTIONS
|
||||
|
||||
|
||||
def turn_exchanges(born: float, allocated_at: float, requests: Iterable[Tuple[float, int, str, str]],
|
||||
doh_questions: Sequence[Tuple[str, int, Optional[int]]], allocates: Sequence[Tuple[float, bytes, int, bool]],
|
||||
auth: bool = False) -> Tuple[int, List[str]]:
|
||||
"""The exchanges of the road from the birth to the Allocate answered with credentials, as (their number, what is more than the
|
||||
protocols ask for, in words). The control connection that carried the question of the TURN name costs its greeting and its
|
||||
CONNECT (and the authentication); every question costs one; every distinct Allocate transaction one."""
|
||||
road, _others = turn_road_connections(born, allocated_at, requests, doh_questions)
|
||||
transactions = [t for t in allocates if t[0] <= allocated_at]
|
||||
per_connection = SOCKS_EXCHANGES + (SOCKS_AUTH_EXCHANGES if auth else 0)
|
||||
found = []
|
||||
if len(road) > CONNECTS_AFTER_THE_BIRTH:
|
||||
found.append("%d SOCKS5 control connections made after the birth carried a question of the TURN name (%s), the design needs "
|
||||
"%d at most" % (len(road), [r[3] for r in road], CONNECTS_AFTER_THE_BIRTH))
|
||||
if len(doh_questions) > DOH_QUESTIONS:
|
||||
found.append("%d DoH questions for the name (%s), a resolver told its family asks %d"
|
||||
% (len(doh_questions), [(q[0], q[1]) for q in doh_questions], DOH_QUESTIONS))
|
||||
if len(transactions) > ALLOCATE_TRANSACTIONS:
|
||||
found.append("%d Allocate transactions (%s), the long-term credential asks %d: the one without credentials, answered 401, and "
|
||||
"the one with them" % (len(transactions), [("credentials" if t[3] else "no credentials") for t in transactions],
|
||||
ALLOCATE_TRANSACTIONS))
|
||||
return len(road) * per_connection + len(doh_questions) + len(transactions), found
|
||||
|
||||
|
||||
def turn_exchanges_problem(born: float, allocated_at: float, requests: Iterable[Tuple[float, int, str, str]],
|
||||
doh_questions: Sequence[Tuple[str, int, Optional[int]]],
|
||||
allocates: Sequence[Tuple[float, bytes, int, bool]], auth: bool = False) -> Optional[str]:
|
||||
"""What is wrong with the NUMBER of exchanges of the road, from the birth of the PeerConnection (``born``) to the Allocate answered
|
||||
with credentials (``allocated_at``), or None. The times are seconds on the gateway's clock and only ORDER the records: nothing
|
||||
here compares one with a duration, so a machine whose every stamp is later gives the same count.
|
||||
|
||||
``requests`` is ``Gateway.requests``; ``doh_questions`` the (name, type, connection) of every question the DoH heard for the TURN
|
||||
name (nothing else asks it, so the question is the PeerConnection's); ``allocates`` the transactions of
|
||||
``TurnServer.transactions()``.
|
||||
|
||||
The most the road may cost: the one SOCKS5 control connection that carried the question, with its CONNECT to the DoH
|
||||
(``SOCKS_EXCHANGES``, one more with a user and a password), the one DoH question, the two transactions of the Allocate. What the
|
||||
browser does on other connections (its page, the DoH for other names, in parallel) is not on the road: it is listed in the message
|
||||
as evidence and decides nothing. An ASSOCIATE is no exchange of this road either: the association that carries the Allocate is
|
||||
made before the birth (``cold_association_problem`` judges it, and the held handshakes of ``held_handshake_problem`` prove that
|
||||
nothing waits for one made after)."""
|
||||
requests = list(requests)
|
||||
seen, found = turn_exchanges(born, allocated_at, requests, doh_questions, allocates, auth)
|
||||
most = turn_exchanges_most(auth)
|
||||
if not found and seen <= most:
|
||||
return None
|
||||
_road, others = turn_road_connections(born, allocated_at, requests, doh_questions)
|
||||
return ("the road made %d exchanges from the birth to the Allocate answered with credentials, the protocols ask for %d at most "
|
||||
"(%d per SOCKS5 control connection that carried the question x %d, %d DoH question, %d Allocate transactions): %s; other "
|
||||
"CONNECTs after the birth, not counted: %s"
|
||||
% (seen, most, SOCKS_EXCHANGES + (SOCKS_AUTH_EXCHANGES if auth else 0), CONNECTS_AFTER_THE_BIRTH, DOH_QUESTIONS,
|
||||
ALLOCATE_TRANSACTIONS, "; ".join(found) or "more than that in all", [r[3] for r in others] or "none"))
|
||||
|
||||
|
||||
def held_handshake_problem(allocated_at: Optional[float], released_at: float, held: Sequence[float]) -> Optional[str]:
|
||||
"""What is wrong with the way the road behaved while the handshakes begun after the pool was ready were HELD, or None.
|
||||
|
||||
``held`` are the starts (seconds on the gateway's clock) of the associations whose answer the test held; ``released_at`` is the
|
||||
instant the test let them go (once the page had posted its srflx, or at its 30 s deadline); ``allocated_at`` is the moment the
|
||||
TURN server answered the Allocate that carried credentials (None: it never did).
|
||||
|
||||
The promise is an ORDER, read off two stamps of the same clock: the allocation was answered BEFORE the held handshakes were let
|
||||
go. A road whose Allocate needs no handshake made after the birth, and whose DoH connection does not wait behind one, does not
|
||||
notice them; one whose handshakes are made one after the other on the same thread (or whose Allocate leaves on an association
|
||||
made from scratch) is left waiting for the test, whatever the speed of the machine."""
|
||||
shown = [round(t, 3) for t in held]
|
||||
if allocated_at is None:
|
||||
return ("the TURN server never answered an Allocate that carried credentials, with %d association handshake(s) held after the "
|
||||
"pool was ready (begun at %s s): something of the road waits for a handshake" % (len(held), shown))
|
||||
if allocated_at > released_at:
|
||||
return ("the Allocate was answered at %.3f s, after the %d held association handshake(s) (begun at %s s) were let go at "
|
||||
"%.3f s: the road waited for a handshake it does not need, one handshake waits for another"
|
||||
% (allocated_at, len(held), shown, released_at))
|
||||
return None
|
||||
|
||||
|
||||
def turn_chain_problem(born: float, allocated_at: Optional[float], released_at: float, held: Sequence[float],
|
||||
requests: Iterable[Tuple[float, int, str, str]], doh_questions: Sequence[Tuple[str, int, Optional[int]]],
|
||||
allocates: Sequence[Tuple[float, bytes, int, bool]],
|
||||
associations: Sequence[Sequence[Optional[float]]], via: Iterable[Tuple[str, int, int, float]], host: str,
|
||||
auth: bool = False) -> Optional[str]:
|
||||
"""What is wrong with the road of a TURN server written as a name, or None: the allocation was answered while the later handshakes
|
||||
were held (:func:`held_handshake_problem`), it cost no exchange more than the protocols ask for (:func:`turn_exchanges_problem`),
|
||||
and the Allocate left on an association that was ready before the birth (:func:`cold_association_problem`). ``host`` is the
|
||||
address of the TURN server: the datagrams of the allocation are the ones judged. Nothing here reads a duration."""
|
||||
problem = held_handshake_problem(allocated_at, released_at, held)
|
||||
if problem is not None or allocated_at is None:
|
||||
return problem
|
||||
return (turn_exchanges_problem(born, allocated_at, requests, doh_questions, allocates, auth)
|
||||
or cold_association_problem(associations, via, host, born))
|
||||
|
||||
|
||||
#: The first retry of the mDNS responder: a name that does not come back opens a connection only after it.
|
||||
MDNS_RETRY_MS = 3000
|
||||
#: A page whose own loop did not run for this long (milliseconds) while it waited was stalled by the machine, not by the product.
|
||||
STALL_MS = 1000
|
||||
|
||||
|
||||
def opened_at_the_retry_problem(opened_ms: float, stalled_ms: float, retry_ms: float = MDNS_RETRY_MS, stall_ms: float = STALL_MS) -> Optional[str]:
|
||||
"""What is wrong with the time a connection took to open, or None. The promise is that it opens before the responder's retry (a name
|
||||
that did not come back is the slow road), and a clock cannot say it alone: a machine that stops for seconds opens late on the best of roads.
|
||||
``stalled_ms`` is the longest time the page's own loop did not run while it waited, read in the same run; a page that was stopped for
|
||||
``stall_ms`` or more says nothing of the road, so no time is judged then."""
|
||||
if opened_ms < retry_ms or stalled_ms >= stall_ms:
|
||||
return None
|
||||
return "opened after %d ms, at the responder's retry (%d ms), and the page's own loop was never stopped for %d ms (longest %d ms)" % (
|
||||
opened_ms, retry_ms, stall_ms, stalled_ms)
|
||||
+91
-26
@@ -11,7 +11,10 @@ The wrapper runs Fission the way retail Firefox does (strategy 1, one content pr
|
||||
frame of B inside a page of A runs in another process.
|
||||
|
||||
`assert_other_process` is how a test proves that, from inside the pages and with no help from the driver: the
|
||||
frame spins for 600 ms and the observer frame times a 10 ms timer, which stalls only when the two share a process.
|
||||
frame spins for 600 ms and the observer frame ticks a 10 ms timer: a tick that runs INSIDE the spin proves the two do
|
||||
not share a process (one thread cannot tick while it spins), and no amount of load can fake that. The absence of ticks
|
||||
proves nothing on a loaded machine (the observer may be starved for the whole spin), so the spin is repeated, up to six
|
||||
times, and the test is red only when no spin ever shows a tick inside it.
|
||||
A test file calls it at least once, so the suite cannot silently turn into a same-process suite.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -28,10 +31,8 @@ from _servers import LocalServer
|
||||
|
||||
HOSTS = {"A": "127.0.0.1", "B": "localhost", "C": "127.0.0.2"}
|
||||
|
||||
#: How long the frame keeps its main thread busy, and the longest gap of the observer's timer that still means
|
||||
#: "another process" (a process shared with the frame is stalled for about the whole spin).
|
||||
#: How long the frame keeps its main thread busy.
|
||||
SPIN_MS = 600
|
||||
OWN_PROCESS_GAP_MS = 300
|
||||
|
||||
HTML = "text/html; charset=utf-8"
|
||||
|
||||
@@ -63,19 +64,28 @@ class Sites:
|
||||
site = self.server.site
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.body = self.rfile.read(length) if length else b""
|
||||
sites.requests.append({"site": site, "path": url.path, "query": self.query,
|
||||
"method": self.command, "headers": dict(self.headers)})
|
||||
# `at` is when it arrived, `sent` the instant before its answer starts to be written (after the delay) and
|
||||
# `done` when the write returned (the clock of the test process). `sent` is the first instant the browser can
|
||||
# have seen the request end, so it is what says how long the network was quiet: `done` is taken by a thread
|
||||
# of the test process, which can lose the CPU or the GIL between the write and the stamp (the client runs in
|
||||
# this process), and is then later than the real end.
|
||||
entry = {"site": site, "path": url.path, "query": self.query, "method": self.command,
|
||||
"headers": dict(self.headers), "at": time.monotonic(), "sent": None, "done": None}
|
||||
sites.requests.append(entry)
|
||||
spec = sites._routes.get((site, url.path))
|
||||
if spec is None:
|
||||
entry["sent"] = time.monotonic()
|
||||
self.send_response(404)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
entry["done"] = time.monotonic()
|
||||
return
|
||||
body = spec["body"](self) if callable(spec["body"]) else spec["body"]
|
||||
if isinstance(body, str):
|
||||
body = body.encode("utf-8")
|
||||
if spec["delay"]:
|
||||
time.sleep(spec["delay"])
|
||||
entry["sent"] = time.monotonic()
|
||||
try:
|
||||
self.send_response(spec["status"])
|
||||
self.send_header("Content-Type", spec["ctype"])
|
||||
@@ -87,6 +97,7 @@ class Sites:
|
||||
self.wfile.write(body)
|
||||
except OSError:
|
||||
pass
|
||||
entry["done"] = time.monotonic()
|
||||
|
||||
do_GET = _answer
|
||||
do_POST = _answer
|
||||
@@ -155,37 +166,91 @@ def launch(binary, humanize=False, **kwargs):
|
||||
def new_page(browser, **context_kwargs):
|
||||
context = browser.new_context(**context_kwargs)
|
||||
page = context.new_page()
|
||||
page.set_default_timeout(8000)
|
||||
page.set_default_timeout(30000)
|
||||
page.set_default_navigation_timeout(30000)
|
||||
return context, page
|
||||
|
||||
|
||||
def longest_timer_gap(observer, frame, spin_ms=SPIN_MS):
|
||||
"""Make ``frame`` spin for ``spin_ms`` and return the longest gap (ms) between two ticks of a 10 ms timer that
|
||||
``observer`` (a frame) runs meanwhile."""
|
||||
def spin_trial(observer, frame, spin_ms=SPIN_MS):
|
||||
"""Make ``frame`` spin for ``spin_ms`` while ``observer`` (a frame) ticks a 10 ms timer, and return
|
||||
``(ticks, window)``: the wall-clock time (ms) of every tick, and the ``(start, end)`` of the spin, both read
|
||||
from ``Date.now()`` (one clock for every process)."""
|
||||
observer.evaluate("""() => {
|
||||
window.__gap = 0;
|
||||
let last = performance.now();
|
||||
window.__tick = setInterval(() => {
|
||||
const now = performance.now();
|
||||
window.__gap = Math.max(window.__gap, now - last);
|
||||
last = now;
|
||||
}, 10);
|
||||
window.__ticks = [];
|
||||
window.__tick = setInterval(() => window.__ticks.push(Date.now()), 10);
|
||||
}""")
|
||||
frame.evaluate("""(ms) => { setTimeout(() => {
|
||||
frame.evaluate("""(ms) => { window.__spin = null; setTimeout(() => {
|
||||
const start = Date.now();
|
||||
const end = performance.now() + ms;
|
||||
while (performance.now() < end) { /* spin */ }
|
||||
window.__spin = [start, Date.now()];
|
||||
}, 50); }""", spin_ms)
|
||||
observer.page.wait_for_timeout(spin_ms + 800)
|
||||
return observer.evaluate("() => { clearInterval(window.__tick); return window.__gap; }")
|
||||
# until the frame says its spin is over (a condition with a deadline, not spin_ms + 800 ms): the ticks of the whole spin are in the list by then
|
||||
window = wait_for_value(observer.page, lambda: frame.evaluate("window.__spin"))
|
||||
ticks = observer.evaluate("() => { clearInterval(window.__tick); return window.__ticks; }")
|
||||
return ticks, window
|
||||
|
||||
|
||||
def assert_other_process(observer, frame):
|
||||
"""``frame`` runs in a process of its own, not the one of ``observer``: a spin in it does not stall the timer."""
|
||||
gap = longest_timer_gap(observer, frame)
|
||||
assert gap < OWN_PROCESS_GAP_MS, (
|
||||
"the frame at %s shares the process of the observer at %s: a %d ms spin stalled the observer's timer for "
|
||||
"%.0f ms" % (frame.url, observer.url, SPIN_MS, gap))
|
||||
def wait_for_value(page, read, seconds=30.0):
|
||||
"""``read()`` once it is not None, with the client's events being read; None if it never is."""
|
||||
end = time.monotonic() + seconds
|
||||
value = read()
|
||||
while value is None and time.monotonic() < end:
|
||||
page.wait_for_timeout(100)
|
||||
value = read()
|
||||
return value
|
||||
|
||||
|
||||
#: A tick counts as "inside" the spin when it is this far (ms) from both ends of it, and the spin must hold this
|
||||
#: many of them. A page that shares the frame's process runs no tick in the spin at all.
|
||||
INSIDE_MARGIN_MS = 10
|
||||
INSIDE_TICKS = 3
|
||||
|
||||
|
||||
def ticks_inside(ticks, window):
|
||||
"""How many ``ticks`` ran strictly inside the spin ``window`` (start, end)."""
|
||||
if window is None:
|
||||
return 0
|
||||
start, end = window
|
||||
return sum(1 for tick in ticks if start + INSIDE_MARGIN_MS < tick < end - INSIDE_MARGIN_MS)
|
||||
|
||||
|
||||
def other_process_proved(trials):
|
||||
"""Whether any trial ``(ticks, window)`` shows the observer running while the frame spun.
|
||||
|
||||
The proof is one-sided on purpose. A frame that shares the observer's process spins ON the observer's thread, so
|
||||
no tick of the observer can run between the start and the end of the spin: in every trial, whatever the load,
|
||||
zero ticks are inside. A frame in another process leaves the observer free, and ticks run inside the spin unless
|
||||
the machine happens to starve the observer for the whole spin; a loaded machine does that now and then (stalls of
|
||||
2 s have been seen between two processes), so a trial where no tick ran says nothing, and the test asks again.
|
||||
What it cannot be is wrong the other way: a tick inside a spin is impossible in one process."""
|
||||
return any(ticks_inside(ticks, window) >= INSIDE_TICKS for ticks, window in trials)
|
||||
|
||||
|
||||
#: The spins of the proof that two frames share ONE process (``test_fission_identity_parity_e2e.py`` strategy 0): a frame that shares the observer's process shows no
|
||||
#: tick inside, in any spin (the absence is the proof), so a fixed number of spins is enough to say it, and there is no clock in it.
|
||||
TRIALS = 6
|
||||
#: The proof of ANOTHER process is one spin with ticks inside it, and a loaded machine starves the observer for a whole spin now and then: the spins go on until
|
||||
#: one shows them, within this many seconds (the deadline of the wait; no healthy run comes near it).
|
||||
PROOF_SECONDS = 30.0
|
||||
|
||||
|
||||
def assert_other_process(observer, frame, seconds=PROOF_SECONDS, clock=time.monotonic):
|
||||
"""``frame`` runs in a process of its own, not the one of ``observer``: the observer's timer ticks while the frame
|
||||
spins. Spins until one shows ticks inside it (a healthy machine needs one), for ``seconds``."""
|
||||
trials = []
|
||||
end = clock() + seconds
|
||||
while True:
|
||||
trials.append(spin_trial(observer, frame))
|
||||
if other_process_proved(trials):
|
||||
return
|
||||
if clock() >= end:
|
||||
break
|
||||
assert False, (
|
||||
"the frame at %s shares the process of the observer at %s: in %d spins of %d ms the observer's 10 ms timer never "
|
||||
"ticked inside a spin (a frame of another process leaves it free; here: ticks inside, ticks in all, spin ms) %s" % (
|
||||
frame.url, observer.url, len(trials), SPIN_MS,
|
||||
[(ticks_inside(t, w), len(t), (w[1] - w[0]) if w else None) for t, w in trials]))
|
||||
|
||||
|
||||
def js(value):
|
||||
|
||||
+11
-8
@@ -23,7 +23,7 @@ import threading
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
from _ports import bind_tcp_and_probe_udp
|
||||
from _ports import bind_tcp_and_hold_udp
|
||||
|
||||
|
||||
def _certificate(address: str, directory: Path):
|
||||
@@ -57,12 +57,13 @@ class _TcpServer(socketserver.ThreadingTCPServer):
|
||||
|
||||
|
||||
def _tcp_server_on_a_port_udp_binds(address: str):
|
||||
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``: the one picker of the harness (tests/_ports.py), which the
|
||||
"""A TCP server on a port number that UDP can bind too, with the UDP socket already bound to it, as ``(server, port, udp)``: the one picker of the harness (tests/_ports.py), which the
|
||||
witness and the resolver trap walk the same sequence of. The first try is the system's own pick (port 0); the others are drawn at random
|
||||
below the dynamic range, because Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP
|
||||
inside the same zone (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty consecutive picks refused, three tests red). Every refusal is
|
||||
kept with its code and the last three are in the error."""
|
||||
return bind_tcp_and_probe_udp(address, lambda host, number: _TcpServer((host, number), _TcpHandler), socket_module=socket)
|
||||
kept with its code and the last three are in the error. The UDP socket is NOT closed again: it goes to the QUIC server's loop, so that the
|
||||
number is held on UDP from the first look at it to its use (a probe that was closed left a window for any other bind of that number)."""
|
||||
return bind_tcp_and_hold_udp(address, lambda host, number: _TcpServer((host, number), _TcpHandler), socket_module=socket)
|
||||
|
||||
|
||||
class _TcpHandler(socketserver.BaseRequestHandler):
|
||||
@@ -145,8 +146,8 @@ class H3Server:
|
||||
"""TCP+TLS (HTTP/2) and QUIC (HTTP/3) on one port of `address`."""
|
||||
|
||||
def __init__(self, address: str):
|
||||
from aioquic.asyncio import serve
|
||||
from aioquic.asyncio.protocol import QuicConnectionProtocol
|
||||
from aioquic.asyncio.server import QuicServer
|
||||
from aioquic.h3.connection import H3_ALPN, H3Connection
|
||||
from aioquic.h3.events import HeadersReceived
|
||||
from aioquic.quic.configuration import QuicConfiguration
|
||||
@@ -169,10 +170,11 @@ class H3Server:
|
||||
server = self
|
||||
|
||||
# One port for both: the TCP port first, then the same number for UDP.
|
||||
tcp, port = _tcp_server_on_a_port_udp_binds(address)
|
||||
tcp, port, udp = _tcp_server_on_a_port_udp_binds(address)
|
||||
self.port = port
|
||||
#: What the TCP answer says about HTTP/3: the same port, for an hour.
|
||||
self.alt_svc = 'h3=":%d"; ma=3600' % port
|
||||
self._udp = udp
|
||||
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self._tls.load_cert_chain(str(cert), str(key))
|
||||
self._tls.set_alpn_protocols(["h2", "http/1.1"])
|
||||
@@ -209,8 +211,9 @@ class H3Server:
|
||||
|
||||
def run():
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._quic = self._loop.run_until_complete(
|
||||
serve(address, port, configuration=configuration, create_protocol=Protocol))
|
||||
# What ``aioquic.asyncio.serve(address, port)`` does (1.x), with the socket that already holds the number.
|
||||
_transport, self._quic = self._loop.run_until_complete(self._loop.create_datagram_endpoint(
|
||||
lambda: QuicServer(configuration=configuration, create_protocol=Protocol), sock=self._udp))
|
||||
started.set()
|
||||
try:
|
||||
self._loop.run_forever()
|
||||
|
||||
@@ -188,7 +188,7 @@ class HttpProxy:
|
||||
self._answer(conn, 403)
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
upstream = socket.create_connection((host, port), timeout=30)
|
||||
except OSError:
|
||||
self._record("CONNECT", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
@@ -209,7 +209,7 @@ class HttpProxy:
|
||||
self._answer(conn, 502)
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((address, port), timeout=10)
|
||||
upstream = socket.create_connection((address, port), timeout=30)
|
||||
except OSError:
|
||||
self._record("GET", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
"""The exit address of the lab: what a launch of an e2e test is told about where it leaves from, so that no test asks a service of the internet.
|
||||
|
||||
A launch (``InvisiblePlaywright(...)``, ``launch_server(...)``) composes its session in the core (``invisible_core.prepare_session_geo``), and the first step
|
||||
of it is ``invisible_core._geo.discover_egress_ip``: with no proxy, an HTTP request to three "what is my address" services (api.ipify.org, icanhazip.com,
|
||||
checkip.amazonaws.com, a budget of 15 s), whose answer is looked up in the GeoIP database for the zone, the language and the position of the session.
|
||||
Every e2e test that names neither ``timezone=`` nor ``proxy=`` (222 launches in 125 files), and every test that names only a zone, therefore depended on
|
||||
three services and on the network of the runner reaching them. The product is not wrong to ask: a user has no other way to know their exit. A TEST has one:
|
||||
it declares it.
|
||||
|
||||
This module is that declaration, made once per session by the autouse fixture of ``conftest.py`` (``_the_lab_declares_the_exit``):
|
||||
|
||||
* the question with NO proxy is answered :data:`LAB_EGRESS_IP`, a public address (so the core does not refuse it as unroutable) that the GeoIP database of
|
||||
the lab (``scripts/ci_lab_geoip.py``: one record for every public address that is not one of its six exits) maps to New York, en-US. The same session
|
||||
as before on every runner, whatever its address and whatever its network;
|
||||
* the question WITH a proxy is left to what answered it before: the local gateways of the tests answer ``api.ipify.org`` themselves
|
||||
(``tests/_socks_servers.py``), and a test that replaces the question (``tests/_udp_line.egress_by_proxy``) does it with ``monkeypatch`` for its own
|
||||
duration, which undoes to this answer and not to the network;
|
||||
* the database is the lab's too: when ``STEALTHFOX_GEOIP_MMDB`` is not set (a developer's machine; the CI legs set it) it is built here, from the same table
|
||||
and the same bytes, instead of the core asking GitHub which database is the latest.
|
||||
|
||||
A test that must prove the discovery itself asks for the fixture ``local_egress_echo``: the real function, against an echo service of its own on
|
||||
loopback. Nothing in a test goes to the internet to know an address.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def _address(*parts: int) -> str:
|
||||
return ".".join(str(part) for part in parts)
|
||||
|
||||
|
||||
#: The exit every e2e launch with no proxy declares. A public address that is in no reserved range and in none of the six exits of the lab database, so
|
||||
#: the lab database answers it with its one record for the rest of the public space (US, America/New_York, en-US), the same on every machine.
|
||||
LAB_EGRESS_IP = _address(8, 8, 8, 8)
|
||||
|
||||
|
||||
class DeclaredExit:
|
||||
"""The replacement of ``discover_egress_ip``: counts the questions it answers, and passes a proxied one on to what answered it before."""
|
||||
|
||||
def __init__(self, original: Callable[..., str], ip: str = LAB_EGRESS_IP) -> None:
|
||||
self.original = original
|
||||
self.ip = ip
|
||||
self.direct_questions = 0
|
||||
self.proxied_questions: List[Any] = []
|
||||
|
||||
def __call__(self, proxy: Optional[Dict[str, Any]] = None, *args: Any, **kwargs: Any) -> str:
|
||||
if not proxy:
|
||||
self.direct_questions += 1
|
||||
return self.ip
|
||||
self.proxied_questions.append(proxy.get("server") if isinstance(proxy, dict) else proxy)
|
||||
return self.original(proxy, *args, **kwargs)
|
||||
|
||||
|
||||
def lab_database_bytes() -> bytes:
|
||||
"""The GeoIP database of the lab, from ``scripts/ci_lab_geoip.py`` (the same bytes on every run)."""
|
||||
spec = importlib.util.spec_from_file_location("ci_lab_geoip_of_the_tests", ROOT / "scripts" / "ci_lab_geoip.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module.build_bytes()
|
||||
|
||||
|
||||
def use_the_lab_database(patch: Any, directory: Path, environ: Optional[Dict[str, str]] = None) -> Optional[Path]:
|
||||
"""Point ``STEALTHFOX_GEOIP_MMDB`` at the lab database when nothing does yet (a CI leg has set it, and its sha256 is the pin's). ``patch`` is a
|
||||
``pytest.MonkeyPatch``: the variable goes back with it. Returns the file written, or None when the variable was already set."""
|
||||
import os
|
||||
|
||||
seen = os.environ if environ is None else environ
|
||||
if seen.get("STEALTHFOX_GEOIP_MMDB"):
|
||||
return None
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / "geoip-aio-all.mmdb"
|
||||
path.write_bytes(lab_database_bytes())
|
||||
patch.setenv("STEALTHFOX_GEOIP_MMDB", str(path))
|
||||
return path
|
||||
|
||||
|
||||
def install(patch: Any, directory: Path) -> Optional[DeclaredExit]:
|
||||
"""Declare the exit of the lab for the duration of ``patch`` (a ``pytest.MonkeyPatch``). None when the core is not importable: the user-path e2e
|
||||
files run in an environment that has not got it and make their own."""
|
||||
try:
|
||||
import invisible_core
|
||||
from invisible_core import _geo
|
||||
except ImportError:
|
||||
return None
|
||||
declared = DeclaredExit(_geo.discover_egress_ip)
|
||||
patch.setattr(_geo, "discover_egress_ip", declared)
|
||||
patch.setattr(invisible_core, "discover_egress_ip", declared, raising=False)
|
||||
use_the_lab_database(patch, directory)
|
||||
return declared
|
||||
|
||||
|
||||
class EchoService:
|
||||
"""What the three services of the product answer, on loopback: the address of the caller as the body, and the number of questions it was asked."""
|
||||
|
||||
def __init__(self, answer: str = LAB_EGRESS_IP) -> None:
|
||||
owner = self
|
||||
self.answer = answer
|
||||
self.questions = 0
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self) -> None:
|
||||
owner.questions += 1
|
||||
body = owner.answer.encode("ascii")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args: Any, **kwargs: Any) -> None:
|
||||
pass
|
||||
|
||||
self._server = LocalServer(("127.0.0.1", 0), Handler)
|
||||
self.url = "http://127.0.0.1:%d/" % self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
def close(self) -> None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
+61
-4
@@ -60,9 +60,9 @@ def _paeth(a: int, b: int, c: int) -> int:
|
||||
return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
|
||||
|
||||
|
||||
def decode_png(png: bytes) -> Dict[str, Any]:
|
||||
"""{w, h, ct, sha256} of a non-interlaced 8-bit PNG (grey, RGB, grey+alpha, RGBA): the sha256 is over the unfiltered
|
||||
scanlines, so two files with the same pixels and different ancillary chunks or compression give the same answer."""
|
||||
def unfiltered(png: bytes) -> Dict[str, Any]:
|
||||
"""{w, h, ct, channels, data} of a non-interlaced 8-bit PNG (grey, RGB, grey+alpha, RGBA): `data` is the scanlines with their filters
|
||||
undone, `w * channels` bytes a row and `h` rows."""
|
||||
chunks = png_chunks(png)
|
||||
head = [d for t, d in chunks if t == b"IHDR"]
|
||||
if not head:
|
||||
@@ -102,7 +102,64 @@ def decode_png(png: bytes) -> Dict[str, Any]:
|
||||
raise NotAPng("filter type %d" % ftype)
|
||||
out += line
|
||||
prev = line
|
||||
return {"w": w, "h": h, "ct": ct, "sha256": hashlib.sha256(bytes(out)).hexdigest()}
|
||||
return {"w": w, "h": h, "ct": ct, "channels": channels, "data": bytes(out)}
|
||||
|
||||
|
||||
def decode_png(png: bytes) -> Dict[str, Any]:
|
||||
"""{w, h, ct, sha256} of a non-interlaced 8-bit PNG (grey, RGB, grey+alpha, RGBA): the sha256 is over the unfiltered
|
||||
scanlines, so two files with the same pixels and different ancillary chunks or compression give the same answer."""
|
||||
u = unfiltered(png)
|
||||
return {"w": u["w"], "h": u["h"], "ct": u["ct"], "sha256": hashlib.sha256(u["data"]).hexdigest()}
|
||||
|
||||
|
||||
def crop(image: Dict[str, Any], x: int, y: int, w: int, h: int) -> Dict[str, Any]:
|
||||
"""The box (x, y, w, h) of an `unfiltered` image, as an image of its own (same colour type). A box that is not inside it is an error:
|
||||
a crop that silently ends at the edge would compare less than it was asked to."""
|
||||
if w <= 0 or h <= 0 or x < 0 or y < 0 or x + w > image["w"] or y + h > image["h"]:
|
||||
raise ValueError("the box %r is not inside the %dx%d image" % ((x, y, w, h), image["w"], image["h"]))
|
||||
ch, stride = image["channels"], image["w"] * image["channels"]
|
||||
rows = [image["data"][(y + r) * stride + x * ch:(y + r) * stride + (x + w) * ch] for r in range(h)]
|
||||
return {"w": w, "h": h, "ct": image["ct"], "channels": ch, "data": b"".join(rows)}
|
||||
|
||||
|
||||
def encode_png(image: Dict[str, Any]) -> bytes:
|
||||
"""The PNG file of an `unfiltered`-shaped image (no filter, one IDAT): what a crop is kept as."""
|
||||
w, h, ch = image["w"], image["h"], image["channels"]
|
||||
stride = w * ch
|
||||
raw = b"".join(b"\x00" + image["data"][r * stride:(r + 1) * stride] for r in range(h))
|
||||
|
||||
def chunk(tag: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||
|
||||
return (PNG_SIGNATURE + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, image["ct"], 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def pixels_differ(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""How two images of the same size and colour type differ: {pixels, first: [x, y] | None, box: [x0, y0, x1, y1] | None}; a pixel
|
||||
differs when any of its channels does. Different sizes or colour types are an error, not a difference."""
|
||||
if (a["w"], a["h"], a["ct"]) != (b["w"], b["h"], b["ct"]):
|
||||
raise ValueError("%dx%d (colour type %d) against %dx%d (colour type %d)" % (a["w"], a["h"], a["ct"], b["w"], b["h"], b["ct"]))
|
||||
ch, w = a["channels"], a["w"]
|
||||
count, first, x0, y0, x1, y1 = 0, None, w, a["h"], -1, -1
|
||||
da, db = a["data"], b["data"]
|
||||
for i in range(0, len(da), ch):
|
||||
if da[i:i + ch] != db[i:i + ch]:
|
||||
x, y = (i // ch) % w, (i // ch) // w
|
||||
count += 1
|
||||
first = first or [x, y]
|
||||
x0, y0, x1, y1 = min(x0, x), min(y0, y), max(x1, x), max(y1, y)
|
||||
return {"pixels": count, "first": first, "box": [x0, y0, x1, y1] if count else None}
|
||||
|
||||
|
||||
def coloured_pixels(image: Dict[str, Any]) -> int:
|
||||
"""How many pixels of an RGB or RGBA image have a red, green and blue that are not equal: black text on white that is drawn with grey
|
||||
antialiasing has none, and one drawn with subpixel (LCD) antialiasing has them at its edges."""
|
||||
ch = image["channels"]
|
||||
if ch < 3:
|
||||
return 0
|
||||
d = image["data"]
|
||||
return sum(1 for i in range(0, len(d), ch) if not d[i] == d[i + 1] == d[i + 2])
|
||||
|
||||
|
||||
def png_bytes_of(value: Dict[str, Any]) -> Optional[bytes]:
|
||||
|
||||
@@ -7,6 +7,7 @@ receive.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from invisible_core.juggler import _pacing
|
||||
from invisible_playwright._juggler import pointer as pointer_mod
|
||||
from invisible_playwright._juggler.pointer import Pointer
|
||||
|
||||
@@ -52,6 +53,21 @@ class FakeActions:
|
||||
def move(self, x, y, steps=1):
|
||||
self._page.moves.append((round(x, 4), round(y, 4)))
|
||||
self.position = (x, y)
|
||||
self._page.singles.append(("move", steps))
|
||||
|
||||
def walk(self, events, *, origin=None, buttons=None, modifiers=0, emit_last=True, now=None, sleep=None):
|
||||
"""`Actions.walk`: the pacer's loop over the events, one stroke per call. The points land in `moves` and the notches in
|
||||
`wheels`, as the single commands did, and `walks` keeps what was handed over, so a test sees that a path left as a walk."""
|
||||
evs = list(events)
|
||||
self._page.walks.append({"events": evs, "origin": origin, "emit_last": emit_last})
|
||||
|
||||
def move(x, y, t_ms):
|
||||
self._page.moves.append((round(x, 4), round(y, 4)))
|
||||
self.position = (x, y)
|
||||
|
||||
def wheel(dx, dy, t_ms):
|
||||
self._page.wheels.append((dx, dy))
|
||||
return _pacing.drive(evs, move, emit_wheel=wheel, emit_last=emit_last, now=now, sleep=sleep, origin=origin, timed=True)
|
||||
|
||||
def wheel(self, dx, dy):
|
||||
self._page.wheels.append((dx, dy))
|
||||
@@ -83,6 +99,8 @@ class FakePage:
|
||||
self.hits = hits
|
||||
self.moves = []
|
||||
self.wheels = []
|
||||
self.walks = []
|
||||
self.singles = []
|
||||
self.hit_asked = []
|
||||
self.queried = []
|
||||
self.disposed = []
|
||||
|
||||
+17
-7
@@ -21,7 +21,7 @@ def who_holds(port: int) -> str:
|
||||
"""What the machine says about the sockets of `port` (ss, or netstat), for the message of a picker or a trap that found no number."""
|
||||
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=30)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
|
||||
@@ -37,11 +37,20 @@ def candidates(tries: int = TRIES, draw: Any = None):
|
||||
yield 0 if attempt == 0 else draw.randint(*DRAW_FROM)
|
||||
|
||||
|
||||
def bind_tcp_and_probe_udp(address: str, make_tcp: Callable[[str, int], Any], tries: int = TRIES, socket_module: Any = None,
|
||||
draw: Any = None) -> Tuple[Any, int]:
|
||||
def bind_tcp_and_hold_udp(address: str, make_tcp: Callable[[str, int], Any], tries: int = TRIES, socket_module: Any = None,
|
||||
draw: Any = None) -> Tuple[Any, int, Any]:
|
||||
"""``make_tcp(address, port)`` makes the TCP server (it binds, with port 0 for the system's pick; it has ``server_address`` and
|
||||
``server_close``). Returns ``(that server, its port)`` once UDP binds the same number too (the probe is closed again: whoever needs the UDP
|
||||
socket binds it next). Raises RuntimeError saying how many tries were made and the last refusals, codes included."""
|
||||
``server_close``). Returns ``(that server, its port, the UDP socket bound to the same number)`` once UDP binds that number too. Raises
|
||||
RuntimeError saying how many tries were made and the last refusals, codes included.
|
||||
|
||||
The caller owns the UDP socket and closes it, or hands it to the loop that serves it (``create_datagram_endpoint(sock=...)``): from the first
|
||||
look at the number to the use of it nobody else can bind it, on TCP or on UDP. (A picker that closed its UDP probe and left "whoever needs the
|
||||
socket binds it next" held the number on TCP only: another picker of the harness could not take it, but any other bind of that UDP number
|
||||
could, the system's own pick of an ephemeral port for another process first among them.)"""
|
||||
return _bind_both(address, make_tcp, tries, socket_module, draw)
|
||||
|
||||
|
||||
def _bind_both(address: str, make_tcp: Callable[[str, int], Any], tries: int, socket_module: Any, draw: Any) -> Tuple[Any, int, Any]:
|
||||
sock = socket_module or socket
|
||||
refusals: List[str] = []
|
||||
last = 0
|
||||
@@ -53,9 +62,10 @@ def bind_tcp_and_probe_udp(address: str, make_tcp: Callable[[str, int], Any], tr
|
||||
probe = sock.socket(sock.AF_INET, sock.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
finally:
|
||||
except BaseException:
|
||||
probe.close()
|
||||
return tcp, port
|
||||
raise
|
||||
return tcp, port, probe
|
||||
except OSError as exc:
|
||||
refusals.append("%s: %s" % (wanted or "system pick", exc))
|
||||
if tcp is not None:
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""The e2e files that need what exists only AFTER a publication: the index, GitHub releases, pip and uv.
|
||||
|
||||
``test_release_e2e.py`` installs the README's block from the real index (uv, pip), downloads the 110 MB binary from the GitHub release, walks every
|
||||
published version against the changelog and the GitHub API; ``test_upgrade_e2e.py`` upgrades from the previous release with pip. They are the one place that
|
||||
proves what a user receives, and for the same reason they can be red for a reason that is nobody's change: PyPI or GitHub down or slow, a rate limit, an index
|
||||
mirror that lags. A gate of a pull request or of a candidate must not wait on any of that (the rule of the project: no real site in a gate; the real ones are
|
||||
in the release round and the round after the publication), so they run only where ``user-install.yml`` runs them: named on the command line, after the upload.
|
||||
|
||||
How that is held, with no new pytest marker (the marker vocabulary is shared with ``invisible_core``, which compares the lists of the repositories):
|
||||
``tests/conftest.py`` deselects the ``e2e`` tests of these files from every run that does not NAME the file. ``scripts/run_e2e.py`` (the run of ``e2e.yml``,
|
||||
of the hunt and of a candidate) names none, the Windows legs build their lists from a collection that no longer holds them, and ``user-install.yml`` names both.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
FILES = ("test_release_e2e.py", "test_upgrade_e2e.py")
|
||||
|
||||
|
||||
def named(args: Iterable[str]) -> "set[Path]":
|
||||
"""The files a command line names (``path`` or ``path::test``), resolved."""
|
||||
return {Path(str(arg).split("::", 1)[0]).resolve() for arg in args}
|
||||
|
||||
|
||||
def is_left_out(path: "str | Path", args: Iterable[str]) -> bool:
|
||||
"""True for a test of a post-publication file in a run that does not name that file."""
|
||||
path = Path(str(path))
|
||||
return path.name in FILES and path.resolve() not in named(args)
|
||||
@@ -107,7 +107,7 @@ class ExitGateway(DohGateway):
|
||||
return
|
||||
self.connects.append((host, port))
|
||||
try:
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
upstream = socket.create_connection((host, port), timeout=30)
|
||||
except OSError:
|
||||
self._send(c, self._reply(5))
|
||||
return
|
||||
|
||||
@@ -41,10 +41,14 @@ class Stream:
|
||||
self.frames = []
|
||||
self.started = None # when `start()` returned, i.e. the reply was handled
|
||||
self.first = None # when the first frame reached the handler
|
||||
self.arrivals = [] # when each frame reached the handler (time.monotonic), in order
|
||||
self.stamps = [] # the engine's `timestamp` of each frame (seconds, stamped in the browser when it sent it)
|
||||
|
||||
def on_frame(frame):
|
||||
if self.first is None:
|
||||
self.first = time.monotonic()
|
||||
self.arrivals.append(time.monotonic())
|
||||
self.stamps.append(frame.get("timestamp") if isinstance(frame, dict) else getattr(frame, "timestamp", None))
|
||||
self.frames.append(frame)
|
||||
|
||||
self.on_frame = on_frame
|
||||
@@ -60,6 +64,16 @@ class Stream:
|
||||
return None
|
||||
return self.first - self.started
|
||||
|
||||
def rate(self, stamps=None):
|
||||
"""Frames a second between the first frame and the last one, on the ENGINE's stamps of the frames (default: all so
|
||||
far), or None with fewer than two stamped frames or no time between them. Not on the times the frames reached this
|
||||
process: a client that stalls receives the frames of the stall in one burst, and a burst is a rate the engine never
|
||||
produced (a cap of 2 fps read as 5). A rate of the frames that came, whatever the time they took to start."""
|
||||
stamps = [s for s in (self.stamps if stamps is None else stamps) if s]
|
||||
if len(stamps) < 2 or stamps[-1] <= stamps[0]:
|
||||
return None
|
||||
return (len(stamps) - 1) / (stamps[-1] - stamps[0])
|
||||
|
||||
def describe(self):
|
||||
delay = self.first_after_start()
|
||||
return "%s: %d frame(s), first frame %s" % (
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""The verdicts of ``test_a_second_goto_that_starts_while_the_first_changes_process_...`` (``test_navigation_across_processes_e2e.py``).
|
||||
|
||||
A first goto to b.test/partial changes process and has its response half there (the server holds the rest); a second goto to
|
||||
c.test/second starts as soon as the client has heard that response. Either may win, as in stock Firefox; what is judged is how
|
||||
each ended and where the page landed, read only once it has landed: when the first wins, the page commits /partial only after the
|
||||
server has sent the rest of it, so the address read before that is still the page that was left (a.test), which is not a defect.
|
||||
|
||||
The outcomes the engine gives (the hunt on the candidate of firefox-65, 200 runs per OS, run 43790642333; Linux / Windows):
|
||||
|
||||
* the second wins: the first is "interrupted by another navigation", the second commits, the page is at c.test/second (116 / 88);
|
||||
* the first wins: the first is "interrupted by another navigation" (the client ends a goto that waits when another one starts,
|
||||
even if its navigation goes on and wins), the second ends NS_BINDING_ABORTED, the page lands at b.test/partial (77 / 102);
|
||||
* the first wins and returns its commit (after the rest of /partial is sent), the second ends NS_BINDING_ABORTED, the page lands
|
||||
at b.test/partial (7 / 10).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Iterable, Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
#: What a goto that waits says when another navigation of its frame starts (the client's own end of it).
|
||||
INTERRUPTED = "is interrupted by another navigation"
|
||||
#: What a navigation replaced by another one ends with (the engine's).
|
||||
ABORTED = "NS_BINDING_ABORTED"
|
||||
#: What a goto that ended only at its deadline says: the defect, whoever won.
|
||||
_TIMEOUT_WORDS = ("timeout", "exceeded", "not reached")
|
||||
|
||||
#: Where each goto lands when it wins: (host, path).
|
||||
FIRST = ("b.test", "/partial")
|
||||
SECOND = ("c.test", "/second")
|
||||
|
||||
|
||||
def landed_on(url: str) -> Optional[str]:
|
||||
"""``"first"`` when the page is at the address of the first goto, ``"second"`` at that of the second, ``None`` anywhere else
|
||||
(still at the page it left: nothing has landed yet)."""
|
||||
parts = urlsplit(url or "")
|
||||
where = (parts.hostname, parts.path)
|
||||
if where == FIRST:
|
||||
return "first"
|
||||
if where == SECOND:
|
||||
return "second"
|
||||
return None
|
||||
|
||||
|
||||
def _told(error: Optional[str]) -> bool:
|
||||
return error is not None and (INTERRUPTED in error or ABORTED in error)
|
||||
|
||||
|
||||
def second_goto_problem(first: Optional[str], second: Optional[str], url: str, asked: Iterable[str]) -> Optional[str]:
|
||||
"""What is wrong with how the two gotos ended, or None.
|
||||
|
||||
``first`` and ``second`` are the errors the gotos raised (``None``: it returned its commit), ``url`` the address of the page once
|
||||
it has landed (or the deadline has passed), ``asked`` the paths the server was asked for.
|
||||
|
||||
* The request of the second goto reached the server (it did not wait behind the held response).
|
||||
* Neither goto ended at its timeout.
|
||||
* The page landed on the address of one of them; still at the page it left is red.
|
||||
* The second won (c.test/second): it returned its commit (an abort of the replaced first one taken for its end is the defect),
|
||||
and the first ended with an end the engine or the client tells (interrupted, or NS_BINDING_ABORTED).
|
||||
* The first won (b.test/partial): the second ended with an end that is told (NS_BINDING_ABORTED, or interrupted), and the first
|
||||
returned its commit or was interrupted by the client; NS_BINDING_ABORTED for the goto whose navigation landed is the abort of
|
||||
the process it left taken for the end of its navigation, red.
|
||||
"""
|
||||
detail = (first, second, url, sorted(asked))
|
||||
if "/second" not in set(asked):
|
||||
return "the request of the second goto never reached the server (it waited behind the held response): %r" % (detail,)
|
||||
for name, error in (("first", first), ("second", second)):
|
||||
text = (error or "").lower()
|
||||
if any(word in text for word in _TIMEOUT_WORDS):
|
||||
return "the %s goto ended only at its timeout: %r" % (name, detail)
|
||||
winner = landed_on(url)
|
||||
if winner is None:
|
||||
return ("the page landed on neither goto (it is still at %s after the rest of the first response was sent): %r"
|
||||
% (url, detail))
|
||||
if winner == "second":
|
||||
if second is not None:
|
||||
return "the page landed on the second goto, which did not return its commit but an error: %r" % (detail,)
|
||||
if not _told(first):
|
||||
return ("the page landed on the second goto and the first did not end interrupted or aborted: %r" % (detail,))
|
||||
return None
|
||||
if not _told(second):
|
||||
return ("the page landed on the first goto and the second did not end aborted or interrupted (it %s): %r"
|
||||
% ("returned a commit" if second is None else "ended otherwise", detail))
|
||||
if first is not None and INTERRUPTED not in first:
|
||||
return ("the page landed on the first goto, which ended with an error that is not the client's interruption: the abort of "
|
||||
"the process it left was taken for the end of its navigation: %r" % (detail,))
|
||||
return None
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The end of a session, for the e2e that count what a browser asks or connects to: the next test starts when this one's browser is gone.
|
||||
|
||||
⛔ THE KNOWN-BAD INPUT: `close()` returns when the BROWSER has exited (invisible-core's reaper), while the sender of the shutdown pings
|
||||
(`firefox --backgroundtask pingsender`) lives on for about half a second and asks the resolver of the machine for the telemetry host. The
|
||||
sessions without a proxy of the launch (`context_only`) may do that, and the test after them is a parametrized neighbour with a resolver trap
|
||||
(or a watcher of direct connections) of its own, started within milliseconds: it counted the question of the session before as its own, and five
|
||||
runs of `test_nothing_leaves_but_the_proxy_e2e.py` were red for a browser that was not theirs (measured by the kernel: the questions arrived 50-66
|
||||
ms after the next test began).
|
||||
|
||||
So a session of those tests ENDS before the test lets go of its place: `EndingPlaywright` is an `InvisiblePlaywright` whose `__exit__` waits for the
|
||||
launch's reaper (`wait_reaped(token)`: the sender is finished or ended, the launch released, the session's directories gone) and for the session's
|
||||
processes to be gone (`wait_until_gone`). The 30 s are a safety net, never a measure: the wait ends when the reaper does. A reaper that does not
|
||||
finish within them FAILS the test, with the processes that are left: going on in silence would put the next test back in the same room.
|
||||
|
||||
Every session of the e2e files that run a resolver trap or a watcher is made with this class (`tests/test_a_session_ends_before_the_next_test_starts.py`
|
||||
reads those files and fails on one that is not).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.process import SessionToken, find_processes, wait_until_gone
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright._juggler._reaped import wait_reaped
|
||||
|
||||
#: How long a session may take to end after its close, in seconds. A safety net: the wait ends when the reaper does.
|
||||
SAFETY_NET_S = 30.0
|
||||
|
||||
|
||||
def ensure_ended(token, *, timeout: float = SAFETY_NET_S) -> None:
|
||||
"""Waits until what follows the close of the session ``token`` is over: the reaper has finished and nothing carries the token.
|
||||
|
||||
Fails the test, with the reason, when it is not over within ``timeout`` seconds. An empty token (a session that never launched) is nothing to wait for."""
|
||||
token = SessionToken(getattr(token, "value", token))
|
||||
if not token:
|
||||
return
|
||||
if not wait_reaped(token, timeout=timeout):
|
||||
pytest.fail(
|
||||
"the session %r did not end within %s s of its close: the reaper of its launch has not finished (processes of the session still "
|
||||
"alive: %s). The next test would start with this one's processes alive and count what they ask." % (
|
||||
token, timeout, _left(token)), pytrace=False)
|
||||
if not wait_until_gone(token, timeout=timeout):
|
||||
pytest.fail(
|
||||
"the reaper of the session %r finished and processes of the session are still alive after %s s: %s" % (
|
||||
token, timeout, _left(token)), pytrace=False)
|
||||
|
||||
|
||||
def _left(token) -> list:
|
||||
"""(pid, name) of what still carries the token, for a message."""
|
||||
left = []
|
||||
for proc in find_processes(token):
|
||||
try:
|
||||
left.append((proc.pid, proc.name()))
|
||||
except Exception:
|
||||
left.append((getattr(proc, "pid", None), "?"))
|
||||
return left
|
||||
|
||||
|
||||
class EndingPlaywright(InvisiblePlaywright):
|
||||
"""An `InvisiblePlaywright` whose close returns when the session has ENDED, not when its browser has exited."""
|
||||
|
||||
#: The token of the launch, kept at its start: the teardown empties the session's own.
|
||||
_end_token = SessionToken()
|
||||
|
||||
def __enter__(self):
|
||||
try:
|
||||
return super().__enter__()
|
||||
finally:
|
||||
self._end_token = SessionToken(self._session_token.value)
|
||||
|
||||
def __exit__(self, *exc):
|
||||
try:
|
||||
return super().__exit__(*exc)
|
||||
finally:
|
||||
token, self._end_token = self._end_token, SessionToken()
|
||||
ensure_ended(token)
|
||||
+108
-28
@@ -50,7 +50,7 @@ import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from typing import List, Optional, Set, Tuple
|
||||
from typing import Callable, List, Optional, Set, Tuple
|
||||
|
||||
#: The name the product's STUN probe sends through the relay. The relay maps it
|
||||
#: to the fake STUN server; every other destination is forwarded for real.
|
||||
@@ -97,6 +97,11 @@ class FakeStun:
|
||||
# On the address the relay sends from: Windows sends neither from an address of the host to loopback (WinError 10049) nor
|
||||
# from loopback to an address of the host (10051), so a relay that leaves from the host's address needs its STUN there too.
|
||||
self._sock.bind((bind_host, 0))
|
||||
self._closing = False
|
||||
if hasattr(socket, "SIO_UDP_CONNRESET"):
|
||||
# Windows: an ICMP "port unreachable" to an answer (a client that already closed its socket) makes the NEXT recvfrom raise
|
||||
# WinError 10054; left on, the server that reads would end there and answer nobody afterwards. Off, as a real server has it.
|
||||
self._sock.ioctl(socket.SIO_UDP_CONNRESET, False)
|
||||
self.address: Tuple[str, int] = self._sock.getsockname()
|
||||
self._thread = threading.Thread(target=self._serve, daemon=True)
|
||||
self._thread.start()
|
||||
@@ -105,8 +110,12 @@ class FakeStun:
|
||||
while True:
|
||||
try:
|
||||
data, peer = self._sock.recvfrom(2048)
|
||||
except ConnectionResetError:
|
||||
continue # an earlier answer found nobody: that is that client's business, not the server's end
|
||||
except OSError:
|
||||
return
|
||||
if self._closing:
|
||||
return # the datagram `close` sent to wake this thread, or one that came after it
|
||||
if len(data) < 20 or data[0:2] != b"\x00\x01":
|
||||
continue
|
||||
self.requests += 1
|
||||
@@ -118,9 +127,25 @@ class FakeStun:
|
||||
try:
|
||||
self._sock.sendto(resp, peer)
|
||||
except OSError:
|
||||
return
|
||||
if self._closing:
|
||||
return
|
||||
continue # a send that failed (the peer is gone) does not end the server for the next client
|
||||
|
||||
def close(self) -> None:
|
||||
"""Ends the server and its thread. Closing the socket wakes a `recvfrom` blocked in another thread on Windows, not on Linux,
|
||||
where the thread would stay blocked for the rest of the process: so the server first sends itself one datagram, which wakes the
|
||||
thread to see `_closing`, waits for the thread, and only then closes the socket."""
|
||||
self._closing = True
|
||||
try:
|
||||
waker = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
waker.sendto(b"", self.address)
|
||||
finally:
|
||||
waker.close()
|
||||
except OSError:
|
||||
pass
|
||||
if self._thread is not threading.current_thread():
|
||||
self._thread.join(timeout=2)
|
||||
self._sock.close()
|
||||
|
||||
|
||||
@@ -149,6 +174,22 @@ class Gateway:
|
||||
#: Whether the TCP connections the gateway opens for a CONNECT also leave from ``exit_host`` (as its datagrams do): a server that
|
||||
#: is reachable DIRECT then tells a connection of the proxy from a connection of the browser by the source.
|
||||
self.tcp_from_exit = tcp_from_exit
|
||||
#: While this Event is set to a cleared state, every answer of the gateway on a control connection waits for it (a
|
||||
#: handshake the test holds, whatever the speed of the machine): None, the default, holds nothing. A test sets it after
|
||||
#: the launch (the core's own probe goes through the gateway before the browser exists) and opens it when it chooses.
|
||||
self.gate: Optional[threading.Event] = None
|
||||
#: The same hold, one control connection at a time: ``hold(index, kind)`` is asked before each answer of the gateway on a
|
||||
#: control connection, with the ``index`` of that connection in ``accepted`` and what it asked for (``kind``: None while only the
|
||||
#: greeting is known, then ``"connect"``, ``"associate"`` or ``"other"``), and returns the Event the answer waits for (or None: no
|
||||
#: hold). A test holds the handshakes it chooses (the ASSOCIATEs begun from an instant on, one connection by its index) and
|
||||
#: lets every other one run, whatever the speed of the machine; None, the default, holds nothing.
|
||||
self.hold: Optional[Callable[[int, Optional[str]], Optional[threading.Event]]] = None
|
||||
#: Every request the gateway read on a control connection, in order, as (seconds from t0, index of the connection in
|
||||
#: ``accepted``, kind, detail): ``"greeting"`` when the connection was accepted (the first bytes of the client), then
|
||||
#: ``"connect"`` (detail ``host:port``), ``"associate"`` (detail ``association #n`` of ``associations``, ``refused`` when
|
||||
#: UDP is refused) or ``"other"``. The EXCHANGES of a road, counted by what the gateway saw and not by how long they took.
|
||||
self.requests: List[Tuple[float, int, str, str]] = []
|
||||
self._local = threading.local()
|
||||
#: Whether each chunk of a forwarded TCP stream also waits half the round trip (a far gateway), as the datagrams do.
|
||||
self.tcp_data_delay = tcp_data_delay
|
||||
self.tcp_exit = tcp_exit
|
||||
@@ -168,6 +209,9 @@ class Gateway:
|
||||
self.associations: List[List[Optional[float]]] = []
|
||||
#: Every datagram the relay carried out, as (host as sent, port, address type, seconds from t0).
|
||||
self.datagram_log: List[Tuple[str, int, int, float]] = []
|
||||
#: Every datagram the relay carried out, as (host as sent, port, index in ``associations`` of the association it came
|
||||
#: on, seconds from t0): which association carried a datagram, not only when it left.
|
||||
self.datagram_via: List[Tuple[str, int, int, float]] = []
|
||||
#: Every datagram the relay carried out, as (host, port, payload).
|
||||
self.datagrams: List[Tuple[str, int, bytes]] = []
|
||||
#: The local port of the socket each granted association sends from: what a server behind the gateway sees as the port
|
||||
@@ -223,7 +267,20 @@ class Gateway:
|
||||
self.close()
|
||||
|
||||
# --- the TCP side --------------------------------------------------------
|
||||
def _request(self, kind: str, detail: str = "") -> None:
|
||||
"""Record a request of the client on the control connection of this thread, and what it asked for (``hold`` is told)."""
|
||||
self._local.kind = None if kind == "greeting" else kind
|
||||
self.requests.append((time.monotonic() - self.t0, getattr(self._local, "index", -1), kind, detail))
|
||||
|
||||
def _send(self, c: socket.socket, data: bytes) -> None:
|
||||
gate = self.gate
|
||||
if gate is not None:
|
||||
gate.wait(120)
|
||||
hold = self.hold
|
||||
if hold is not None:
|
||||
held = hold(getattr(self._local, "index", -1), getattr(self._local, "kind", None))
|
||||
if held is not None:
|
||||
held.wait(120)
|
||||
if self.rtt:
|
||||
time.sleep(self.rtt)
|
||||
c.sendall(data)
|
||||
@@ -234,8 +291,16 @@ class Gateway:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
index = len(self.accepted)
|
||||
self.accepted.append(time.monotonic() - self.t0)
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
threading.Thread(target=self._run, args=(conn, index), daemon=True).start()
|
||||
|
||||
def _run(self, conn: socket.socket, index: int) -> None:
|
||||
"""One control connection: remembers its index (for ``hold`` and ``requests``), then serves it."""
|
||||
self._local.index = index
|
||||
self._local.kind = None
|
||||
self.requests.append((self.accepted[index], index, "greeting", ""))
|
||||
self._handle(conn)
|
||||
|
||||
def _greet(self, c: socket.socket) -> bool:
|
||||
ver, n = _recv_exact(c, 2)
|
||||
@@ -284,10 +349,12 @@ class Gateway:
|
||||
ver, cmd, _rsv = _recv_exact(c, 3)
|
||||
host, port = self._read_address(c)
|
||||
if cmd == 1:
|
||||
self._request("connect", "%s:%d" % (host, port))
|
||||
self._connect(c, host, port)
|
||||
elif cmd == 3:
|
||||
self._associate(c)
|
||||
else:
|
||||
self._request("other", "command %d" % cmd)
|
||||
self._send(c, self._reply(7))
|
||||
except (OSError, ConnectionError):
|
||||
pass
|
||||
@@ -307,10 +374,10 @@ class Gateway:
|
||||
def _open_upstream(self, target: Tuple[str, int]) -> socket.socket:
|
||||
"""The TCP connection of a CONNECT: from ``exit_host`` when ``tcp_from_exit``, else from wherever the system chooses."""
|
||||
if not self.tcp_from_exit:
|
||||
return socket.create_connection(target, timeout=10)
|
||||
return socket.create_connection(target, timeout=30)
|
||||
up = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
up.settimeout(10)
|
||||
up.settimeout(30)
|
||||
up.bind((self.exit_host, 0))
|
||||
up.connect(target)
|
||||
except OSError:
|
||||
@@ -409,10 +476,13 @@ class Gateway:
|
||||
def _associate(self, c: socket.socket) -> None:
|
||||
self.associates += 1
|
||||
if self.udp == "refuse":
|
||||
self._request("associate", "refused")
|
||||
self._send(c, self._reply(7))
|
||||
return
|
||||
record: List[Optional[float]] = [time.monotonic() - self.t0, None]
|
||||
self.associations.append(record)
|
||||
index = next(i for i, r in enumerate(self.associations) if r is record)
|
||||
self._request("associate", "association #%d" % index)
|
||||
relay = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
relay.bind((self.relay_host, 0))
|
||||
out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
@@ -433,6 +503,12 @@ class Gateway:
|
||||
self._deliver(relay, client[0], host, port, data)
|
||||
|
||||
def inbound() -> None: # client -> world
|
||||
# The port of the exit socket is read ONCE: asked at every datagram it fell on a socket the teardown had already closed
|
||||
# (OSError WinError 10038 in a thread nobody joins). An OSError of the body is the association ending, not a failure.
|
||||
try:
|
||||
out_port = out.getsockname()[1]
|
||||
except OSError:
|
||||
return
|
||||
while True:
|
||||
try:
|
||||
d, peer = relay.recvfrom(65536)
|
||||
@@ -440,28 +516,32 @@ class Gateway:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
if len(d) < 10 or d[2] != 0:
|
||||
continue
|
||||
client[0] = peer
|
||||
atyp, i = d[3], 4
|
||||
if atyp == 1:
|
||||
host, i = socket.inet_ntoa(d[i:i + 4]), i + 4
|
||||
elif atyp == 3:
|
||||
n = d[i]
|
||||
host, i = d[i + 1:i + 1 + n].decode(), i + 1 + n
|
||||
else:
|
||||
host, i = socket.inet_ntop(socket.AF_INET6, d[i:i + 16]), i + 16
|
||||
dport = struct.unpack("!H", d[i:i + 2])[0]
|
||||
payload = d[i + 2:]
|
||||
self.datagrams.append((host, dport, payload))
|
||||
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
|
||||
routed = self._route(host, dport, atyp, payload, out.getsockname()[1], answer)
|
||||
if routed is None:
|
||||
continue
|
||||
target, reported = routed
|
||||
if reported is not None:
|
||||
asked_at[target] = reported
|
||||
self._later(lambda p=payload, t=target: out.sendto(p, t), "the datagram to %s:%d" % target)
|
||||
try:
|
||||
if len(d) < 10 or d[2] != 0:
|
||||
continue
|
||||
client[0] = peer
|
||||
atyp, i = d[3], 4
|
||||
if atyp == 1:
|
||||
host, i = socket.inet_ntoa(d[i:i + 4]), i + 4
|
||||
elif atyp == 3:
|
||||
n = d[i]
|
||||
host, i = d[i + 1:i + 1 + n].decode(), i + 1 + n
|
||||
else:
|
||||
host, i = socket.inet_ntop(socket.AF_INET6, d[i:i + 16]), i + 16
|
||||
dport = struct.unpack("!H", d[i:i + 2])[0]
|
||||
payload = d[i + 2:]
|
||||
self.datagrams.append((host, dport, payload))
|
||||
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
|
||||
self.datagram_via.append((host, dport, index, time.monotonic() - self.t0))
|
||||
routed = self._route(host, dport, atyp, payload, out_port, answer)
|
||||
if routed is None:
|
||||
continue
|
||||
target, reported = routed
|
||||
if reported is not None:
|
||||
asked_at[target] = reported
|
||||
self._later(lambda p=payload, t=target: out.sendto(p, t), "the datagram to %s:%d" % target)
|
||||
except OSError:
|
||||
return
|
||||
|
||||
def outbound() -> None: # world -> client
|
||||
while True:
|
||||
@@ -598,7 +678,7 @@ class Socks5TcpOnly:
|
||||
conn.close()
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((addr, port), timeout=15)
|
||||
upstream = socket.create_connection((addr, port), timeout=30)
|
||||
except OSError:
|
||||
conn.sendall(b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00") # host unreachable
|
||||
conn.close()
|
||||
|
||||
+37
-9
@@ -21,8 +21,8 @@ that address, by SOCKS5 address type 1, through the UDP relay. The gateway resol
|
||||
loopback address), so the TURN server sees a source that is not the browser's own: if it sees the browser's, the road was
|
||||
not the gateway's.
|
||||
* :class:`Page` - the page and the verdict, with the shape of a leak test's logic: a tick of 2 seconds after the page starts that
|
||||
marks TIMEOUT, cleared only after a POST made when a server-reflexive candidate arrives; the server compares the address
|
||||
of that candidate with the source the TURN saw.
|
||||
marks TIMEOUT, cleared the moment a server-reflexive candidate arrives (before the POST, so the verdict does not depend on
|
||||
the POST coming back within the tick); the server compares the address of that candidate with the source the TURN saw.
|
||||
|
||||
The names and the addresses are RFC 2606 / RFC 5737: nothing in a test can be mistaken for a real host.
|
||||
"""
|
||||
@@ -55,6 +55,8 @@ EXIT_HOST = "127.0.0.2"
|
||||
#: The exit of a lab that a browser accepts as a real one: a documentation address (RFC 5737, TEST-NET-2, like the TURN server's) that
|
||||
#: the host holds on its loopback interface (`lab_exit_address`). A mapped address in 127/8 is thrown away by nICEr as bogus.
|
||||
LAB_EXIT = "198.51.100.9"
|
||||
#: The path of an empty page of the page server (no PeerConnection): see :attr:`Page.warm_url`.
|
||||
WARM_PATH = "/warm"
|
||||
MAGIC = 0x2112A442
|
||||
PASSWORD = "qwerty"
|
||||
REALM = "hermetic"
|
||||
@@ -111,6 +113,8 @@ def _message(mtype: int, tid: bytes, attrs: bytes, key: Optional[bytes] = None)
|
||||
|
||||
class TurnServer:
|
||||
"""UDP TURN server on 127.0.0.1. ``seen`` is every datagram as (source ip, source port, STUN type), in order;
|
||||
``requests`` the same datagrams as (monotonic time, transaction id, STUN type, carries credentials): a retransmission has the
|
||||
transaction id of the request it repeats, so the TRANSACTIONS of a road are the distinct ids (:meth:`transactions`);
|
||||
``allocations`` the successful Allocates as (source ip, source port, username, time)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
@@ -119,9 +123,18 @@ class TurnServer:
|
||||
self.address: Tuple[str, int] = self.sock.getsockname()
|
||||
self.seen: List[Tuple[str, int, int]] = []
|
||||
self.allocations: List[Tuple[str, int, str, float]] = []
|
||||
self.requests: List[Tuple[float, bytes, int, bool]] = []
|
||||
self._closed = False
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def transactions(self, mtype: int = 0x0003) -> List[Tuple[float, bytes, int, bool]]:
|
||||
"""The first datagram of each transaction of type ``mtype`` (Allocate by default), in order: a retransmission is not another one."""
|
||||
first: Dict[bytes, Tuple[float, bytes, int, bool]] = {}
|
||||
for request in list(self.requests):
|
||||
if request[2] == mtype:
|
||||
first.setdefault(request[1], request)
|
||||
return sorted(first.values(), key=lambda r: r[0])
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
self.sock.close()
|
||||
@@ -137,6 +150,7 @@ class TurnServer:
|
||||
mtype, tid = struct.unpack("!H", data[:2])[0], data[8:20]
|
||||
self.seen.append((src[0], src[1], mtype))
|
||||
attrs = _attrs(data)
|
||||
self.requests.append((time.monotonic(), tid, mtype, 0x0008 in attrs and 0x0006 in attrs))
|
||||
if mtype == 0x0003: # Allocate
|
||||
if 0x0008 not in attrs or 0x0006 not in attrs: # no credentials: 401 with a realm and a nonce
|
||||
err = _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
|
||||
@@ -257,7 +271,7 @@ class Chain(DohGateway):
|
||||
why = "the TURN server heard the browser but no Allocate was answered with credentials: the 401 round trip did not finish"
|
||||
elif result.get("status") == "TIMEOUT":
|
||||
ends = [e for _s, e in self.associations if e is not None]
|
||||
why = ("the allocation succeeded but too late for the tick of 2000 ms: the association handshakes alone ended at %s s"
|
||||
why = ("the allocation succeeded but the page read no server-reflexive candidate: the association handshakes ended at %s s"
|
||||
% ", ".join("%.2f" % e for e in ends))
|
||||
else:
|
||||
why = "the srflx of the page is not the address the TURN server saw (%s)" % [("%s:%d" % (a[0], a[1])) for a in self.turn.allocations]
|
||||
@@ -274,8 +288,12 @@ let status = 'PENDING';
|
||||
const finish = (s) => { status = s; window.__result.status = s; window.__done = true; };
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
mark('dom');
|
||||
// the tick of a leak test: 2 seconds after the page starts. It is cleared only after the POST made on a srflx.
|
||||
// the tick of a leak test: 2 seconds after the page starts. It stops the moment a srflx arrives, before the POST: what the
|
||||
// test asks is whether the srflx came before the tick, not whether the POST came back within it. The tick is the model of the
|
||||
// page and decides nothing: a srflx that comes after it is still read and posted (`late`), and the test judges the road by the
|
||||
// stamps of the gateway, the DoH and the TURN server.
|
||||
const tick = setInterval(() => { if (status === 'PENDING') { mark('tick'); finish('TIMEOUT'); } clearInterval(tick); }, 2000);
|
||||
window.__result.born = Date.now();
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: ['turn:%(turn)s:%(port)d?transport=udp'], username: 'challenge-' + Date.now(), credential: '%(password)s'}]});
|
||||
pc.createDataChannel('x');
|
||||
mark('pc');
|
||||
@@ -284,14 +302,18 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
pc.onicecandidate = async (e) => {
|
||||
if (!e.candidate) return;
|
||||
window.__result.candidates.push(e.candidate.candidate);
|
||||
if (e.candidate.candidate.indexOf(' typ srflx ') < 0 || status !== 'PENDING') return;
|
||||
if (e.candidate.candidate.indexOf(' typ srflx ') < 0 || window.__result.srflx) return;
|
||||
window.__result.late = status !== 'PENDING';
|
||||
clearInterval(tick);
|
||||
mark('srflx');
|
||||
window.__result.srflx = e.candidate.candidate;
|
||||
const r = await fetch('/verdict', {method: 'POST', body: JSON.stringify({srflx: e.candidate.candidate})});
|
||||
const ok = (await r.json()).ok;
|
||||
// `posted` and the final status are set in one step, after the last await: a test that waits for `posted` and reads the status never reads
|
||||
// the one of a page whose verdict has not been read yet (PENDING or the tick's TIMEOUT).
|
||||
mark('posted');
|
||||
if (status !== 'PENDING') return;
|
||||
clearInterval(tick);
|
||||
finish((await r.json()).ok ? 'DONE' : 'REFUSED');
|
||||
window.__result.posted = true;
|
||||
finish(ok ? 'DONE' : 'REFUSED');
|
||||
};
|
||||
pc.createOffer().then((o) => pc.setLocalDescription(o));
|
||||
});
|
||||
@@ -315,7 +337,8 @@ class Page:
|
||||
|
||||
def do_GET(self):
|
||||
outer.hits.append((self.headers.get("Host", ""), self.path))
|
||||
body = (PAGE_HTML % {"turn": TURN_NAME, "port": TURN_PORT, "password": PASSWORD}).encode()
|
||||
body = (b"<!doctype html><meta charset=utf-8><title>warm</title>" if self.path == WARM_PATH else
|
||||
(PAGE_HTML % {"turn": TURN_NAME, "port": TURN_PORT, "password": PASSWORD}).encode())
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
@@ -346,5 +369,10 @@ class Page:
|
||||
def url(self) -> str:
|
||||
return "http://%s:%d/" % (PAGE_NAME, self.port)
|
||||
|
||||
@property
|
||||
def warm_url(self) -> str:
|
||||
"""An empty page of the same server: opened first, it makes the browser learn the proxy and fill its pool of associations."""
|
||||
return "http://%s:%d%s" % (PAGE_NAME, self.port, WARM_PATH)
|
||||
|
||||
def close(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
@@ -88,6 +88,39 @@ def declared_udp(proxy: Dict[str, Any], servers: Sequence[str]) -> str:
|
||||
return entry[1]
|
||||
|
||||
|
||||
def declared_udp_or_absent(proxy: Dict[str, Any], servers: Sequence[str]) -> Optional[str]:
|
||||
""":func:`declared_udp`, or None when the launch measured nothing for ``proxy`` (a report must say that, not raise)."""
|
||||
try:
|
||||
return declared_udp(proxy, servers)
|
||||
except AssertionError:
|
||||
return None
|
||||
|
||||
|
||||
def udp_measure_sentence(declared: Optional[str], rtt_ms: int) -> str:
|
||||
"""What the core declared for the proxy of a bench, as a sentence of the verdict of a failed test. A measurement that is
|
||||
not ``coherent`` is said outright: the engine then never sends the page's UDP to the relay, and the test fails for a reason
|
||||
that is the measurement's (the budget of the core against the round trip of the gateway), not the page's."""
|
||||
if declared == "coherent":
|
||||
return "UDP verdict the core declared for this proxy: coherent"
|
||||
if declared is None:
|
||||
return ("the core measured nothing for this proxy: the UDP measure of the core did not finish in its budget "
|
||||
"with rtt %d ms (no verdict was declared)" % rtt_ms)
|
||||
return ("the UDP measure of the core did not finish coherent in its budget with rtt %d ms: it declared %r for this proxy, "
|
||||
"so the engine had no relay to use" % (rtt_ms, declared))
|
||||
|
||||
|
||||
def bench_report(gateway: Any, rtt_ms: int, declared: Optional[str]) -> str:
|
||||
"""What the bench saw, as one string for the verdict of a failed test: the datagrams the relay carried with their times
|
||||
(seconds from the start of the gateway), the sends that failed, the CONNECTs, the TCP connections accepted, the UDP
|
||||
ASSOCIATEs and their start and end, and what the core declared for the proxy. Nothing here changes an outcome."""
|
||||
log = ["%s:%d atyp=%d t=%.3fs" % (host, port, atyp, at) for host, port, atyp, at in list(gateway.datagram_log)]
|
||||
associations = [[None if x is None else round(x, 3) for x in record] for record in list(gateway.associations)]
|
||||
return ("%s; gateway send errors: %s; CONNECTs the gateway saw: %s; TCP connections it accepted: %d; "
|
||||
"associations (start, end in s from its start): %s; datagram log with times: %s"
|
||||
% (udp_measure_sentence(declared, rtt_ms), list(gateway.send_errors), list(gateway.connects),
|
||||
len(gateway.accepted), associations, log))
|
||||
|
||||
|
||||
def visits_for(road: str) -> int:
|
||||
"""How many times the page is visited on ``road``: three with no proxy, :data:`PROXY_VISITS` behind any proxy."""
|
||||
if road == _DIRECT_ROAD:
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
"""What the e2e tests wait for: a CONDITION with a deadline, and a record of what was seen while waiting.
|
||||
|
||||
A test that sleeps a fixed time and then reads the state judges the speed of the machine it runs on: on a loaded
|
||||
Windows runner the event arrives after the sleep and the test is red, while the product did nothing wrong. A test
|
||||
that waits until the condition holds (or a deadline that is far beyond any healthy run) is red only when the
|
||||
condition never holds, and it says what it saw on the way, so a red run tells a slow machine from a lost event.
|
||||
|
||||
* :func:`wait_until` and :func:`awatch` poll a condition; ``pump`` is what lets the events of a sync client be
|
||||
read (``page.wait_for_timeout``) or a coroutine yield. The deadline is the only clock the verdict depends on, and
|
||||
it is the one the test names.
|
||||
* :class:`Timeline` is a list of events with the time each was heard, relative to a start the test chooses.
|
||||
* :func:`without_end` says which requests began and never ended.
|
||||
* :func:`quiet_problem` judges a `networkidle` from the server's own stamps of each request.
|
||||
* :func:`spare_processes` is the pool of preallocated content processes retail Firefox keeps (see its docstring).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import Counter
|
||||
from typing import Any, Callable, Iterable, List, Optional, Tuple
|
||||
|
||||
|
||||
class Watch:
|
||||
"""The outcome of a wait: ``ok`` (the condition held before the deadline) and ``history``, the sampled value each
|
||||
time it changed, as ``(seconds since the wait began, value)``."""
|
||||
|
||||
def __init__(self, ok: bool, history: List[Tuple[float, Any]], took: float) -> None:
|
||||
self.ok = ok
|
||||
self.history = history
|
||||
self.took = took
|
||||
|
||||
def render(self) -> str:
|
||||
return "; ".join("+%.2fs %r" % (at, value) for at, value in self.history) or "nothing sampled"
|
||||
|
||||
|
||||
def wait_until(condition: Callable[[], Any], seconds: float, pump: Callable[[], Any],
|
||||
clock: Callable[[], float] = time.monotonic) -> bool:
|
||||
"""Until ``condition()`` is true, calling ``pump()`` between two looks; False if ``seconds`` pass first."""
|
||||
return watch(lambda: bool(condition()), lambda value: value, seconds, pump, clock).ok
|
||||
|
||||
|
||||
def watch(sample: Callable[[], Any], done: Callable[[Any], Any], seconds: float, pump: Callable[[], Any],
|
||||
clock: Callable[[], float] = time.monotonic) -> Watch:
|
||||
"""Until ``done(sample())``, calling ``pump()`` between two looks. The deadline is ``seconds`` from the start; the
|
||||
last look is taken AT the deadline, so a condition that became true during the last pump is not missed."""
|
||||
began = clock()
|
||||
history: List[Tuple[float, Any]] = []
|
||||
while True:
|
||||
value = sample()
|
||||
now = clock()
|
||||
if not history or history[-1][1] != value:
|
||||
history.append((now - began, value))
|
||||
if done(value):
|
||||
return Watch(True, history, now - began)
|
||||
if now - began >= seconds:
|
||||
return Watch(False, history, now - began)
|
||||
pump()
|
||||
|
||||
|
||||
async def awatch(sample: Callable[[], Any], done: Callable[[Any], Any], seconds: float,
|
||||
pump: Callable[[], Any], clock: Callable[[], float] = time.monotonic) -> Watch:
|
||||
""":func:`watch` for an async client: ``pump`` is awaited."""
|
||||
began = clock()
|
||||
history: List[Tuple[float, Any]] = []
|
||||
while True:
|
||||
value = sample()
|
||||
now = clock()
|
||||
if not history or history[-1][1] != value:
|
||||
history.append((now - began, value))
|
||||
if done(value):
|
||||
return Watch(True, history, now - began)
|
||||
if now - began >= seconds:
|
||||
return Watch(False, history, now - began)
|
||||
await pump()
|
||||
|
||||
|
||||
class Timeline:
|
||||
"""Events with the time each was heard, relative to ``start`` (set by the test just before the action)."""
|
||||
|
||||
def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:
|
||||
self._clock = clock
|
||||
self.start = clock()
|
||||
self.events: List[Tuple[float, str, str]] = []
|
||||
|
||||
def begin(self) -> None:
|
||||
self.start = self._clock()
|
||||
|
||||
def add(self, kind: str, what: str) -> None:
|
||||
self.events.append((self._clock() - self.start, kind, what))
|
||||
|
||||
def of(self, *kinds: str) -> List[str]:
|
||||
return [what for _at, kind, what in self.events if kind in kinds]
|
||||
|
||||
def render(self) -> str:
|
||||
return "\n".join(" +%.3fs %-9s %s" % (at, kind, what) for at, kind, what in sorted(self.events)) or " no event"
|
||||
|
||||
|
||||
def without_end(started: Iterable[str], ended: Iterable[str]) -> List[str]:
|
||||
"""The requests that began and never ended: each url as many times as it began more than it ended."""
|
||||
return sorted((Counter(started) - Counter(ended)).elements())
|
||||
|
||||
|
||||
def spare_processes(total_memory_bytes: Optional[int], lowmem_mb: int = 4096, fission_number: int = 3) -> int:
|
||||
"""How many preallocated content processes retail Firefox keeps beside the ones that host pages.
|
||||
|
||||
With Fission on (the wrapper's strategy 1), `PreallocatedProcessManagerImpl::RereadPrefs`
|
||||
(dom/ipc/PreallocatedProcessManager.cpp) keeps a pool of `dom.ipc.processPrelaunch.fission.number` processes
|
||||
(StaticPrefList.yaml: 3 on desktop), and 1 on a machine whose memory is at or under
|
||||
`dom.ipc.processPrelaunch.lowmem_mb` (4096 MB). The pool is refilled one process at a time, each after
|
||||
`dom.ipc.processPrelaunch.delayMs` (1000 ms) and when the loop is idle, so how many of them exist at the moment a
|
||||
test looks depends on how long ago the last page took one."""
|
||||
if total_memory_bytes and total_memory_bytes <= lowmem_mb * 1024 * 1024:
|
||||
return 1
|
||||
return fission_number
|
||||
|
||||
|
||||
#: What `networkidle` promises: no request in flight, and this many seconds since the last request ended
|
||||
#: (`IDLE_QUIET = 0.5`, invisible_core/juggler/lifecycle.py:56, the core the wrapper pins: the timer is the core's, not this
|
||||
#: package's).
|
||||
NETWORKIDLE_PROMISE = 0.5
|
||||
|
||||
|
||||
def quiet_needed(clock: str = "monotonic") -> float:
|
||||
"""The silence a `networkidle` is asked for: the promise less the resolution the clock in use declares, and nothing else.
|
||||
|
||||
The timer that decides `networkidle` is `Lifecycle._settle` in invisible_core/juggler/lifecycle.py (the core pinned by
|
||||
this wrapper; the wrapper's server only forwards the state, `_juggler/server.py` `_hear_lifecycle`). It reads
|
||||
`time.monotonic()` (lifecycle.py:340) and compares it with the instant of the last request event, also
|
||||
`time.monotonic()` (lifecycle.py:541 for a request that begins, :551 for one that ends), against `IDLE_QUIET`
|
||||
(lifecycle.py:352). The stamps of the tests are `time.monotonic()` too, in the same process. A clock that advances in
|
||||
steps of `r` (`time.get_clock_info("monotonic").resolution`: 15.625 ms on Windows, `GetTickCount64`) makes two readings
|
||||
differ from the true interval by less than `r`, so the product that waited the whole promise can be measured up to `r`
|
||||
short. That is a property of the instrument, read from the clock, not an estimate of how loaded a runner is."""
|
||||
return NETWORKIDLE_PROMISE - time.get_clock_info(clock).resolution
|
||||
|
||||
|
||||
def quiet_problem(stamps: Iterable[Tuple[str, float, Optional[float]]], returned: float,
|
||||
clock: str = "monotonic") -> Optional[str]:
|
||||
"""What is wrong with a `networkidle` that came at ``returned`` (None if nothing), from ``(path, arrival, sent)``
|
||||
stamps of the requests of the page on the server's clock (``sent`` None: its answer was not yet being written).
|
||||
|
||||
`networkidle` promises that no request is in flight and that half a second has passed since the last one ended.
|
||||
``sent`` is the first instant the browser can have seen a request end: the server takes it after its delay and
|
||||
BEFORE it writes the answer. Judging on it, never on a stamp taken after the write, is what makes the verdict true under
|
||||
any load: a thread of the test process that loses the CPU or the GIL between the write and a later stamp makes that
|
||||
stamp late and the silence measured shorter than it was, while a correct product returns at least half a second
|
||||
after ``sent`` whatever the load, and one that ignores a request of a frame returns sooner. A late request that has
|
||||
not even arrived is no reason to complain when the network really was quiet before ``returned``; a request not yet
|
||||
sent at ``returned``, or an end too near, is."""
|
||||
# a request that arrived after the return was not in flight at the return, and is no complaint (on a slow machine it can
|
||||
# arrive between the return and the read of the stamps)
|
||||
stamps = [stamp for stamp in stamps if stamp[1] <= returned]
|
||||
in_flight = [path for path, _arrival, sent in stamps if sent is None or sent > returned]
|
||||
if in_flight:
|
||||
return "networkidle came while %s was in flight" % in_flight
|
||||
if not stamps:
|
||||
return "no request of the page was seen at all"
|
||||
since = returned - max(sent for _path, _arrival, sent in stamps)
|
||||
if since < quiet_needed(clock):
|
||||
return "networkidle came after only %.3f s without network (it promises %s)" % (since, NETWORKIDLE_PROMISE)
|
||||
return None
|
||||
+96
-7
@@ -96,6 +96,18 @@ def pytest_runtest_teardown(item, nextitem):
|
||||
faulthandler.cancel_dump_traceback_later()
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
"""The e2e tests of the post-publication files (``tests/_post_publication.py``: pip, uv, PyPI, GitHub) belong to the round after a publication: a run
|
||||
that does not NAME their file does not run them. ``user-install.yml`` names both files; ``scripts/run_e2e.py`` and every PR or candidate leg do not."""
|
||||
import _post_publication
|
||||
|
||||
left = [item for item in items
|
||||
if item.get_closest_marker("e2e") is not None and _post_publication.is_left_out(item.path, config.args)]
|
||||
if left:
|
||||
items[:] = [item for item in items if item not in left]
|
||||
config.hook.pytest_deselected(items=left)
|
||||
|
||||
|
||||
def pytest_unconfigure(config):
|
||||
global _watchdog_handle
|
||||
if _watchdog_handle is not None:
|
||||
@@ -115,12 +127,12 @@ def pytest_unconfigure(config):
|
||||
# is a clear message about one test rather than a collection error covering the
|
||||
# whole run.
|
||||
try:
|
||||
from invisible_playwright._fpforge import generate_profile
|
||||
from invisible_playwright.constants import BINARY_ENTRY_REL
|
||||
from invisible_core._fpforge import generate_profile
|
||||
from invisible_core.seal import DEFAULT_ENTRY_REL
|
||||
_IMPORT_ERROR = None
|
||||
except Exception as exc: # pragma: no cover - only in the e2e-only environment
|
||||
generate_profile = None
|
||||
BINARY_ENTRY_REL = None
|
||||
DEFAULT_ENTRY_REL = None
|
||||
_IMPORT_ERROR = exc
|
||||
|
||||
|
||||
@@ -151,6 +163,83 @@ def _offline_session_geo(request, monkeypatch):
|
||||
monkeypatch.setattr(_session, "session_geo", lambda *_a, **_k: geo)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _a_unit_test_asks_mozilla_for_no_intermediates_list(request, monkeypatch):
|
||||
"""Outside the e2e, a launch declares no intermediates list and starts no check of it.
|
||||
|
||||
The core's `write_user_js` (every launch the server makes) declares Mozilla's list: on a cold cache it downloads it in line, on a warm one the launch starts a
|
||||
background check, and the line it writes would differ with the cache of whoever runs the test. The two functions are stubbed, as the core's own suite does
|
||||
(tests/conftest.py of invisible-core): no list, no thread, no request. The tests of `fetch` set their own; a test marked `e2e` gets the real ones (the CI legs
|
||||
point them at the empty file of `ci/intermediates.json`)."""
|
||||
if request.node.get_closest_marker("e2e") is not None:
|
||||
return
|
||||
try:
|
||||
import invisible_core._intermediates as _im
|
||||
except Exception: # the package is absent: the tests that need it say so
|
||||
return
|
||||
monkeypatch.setattr(_im, "ensure_intermediates", lambda *a, **kw: None)
|
||||
monkeypatch.setattr(_im, "refresh_intermediates_in_background", lambda *a, **kw: None)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _a_unit_test_does_not_depend_on_the_seal_of_whoever_runs_it(request, monkeypatch):
|
||||
"""Outside the e2e, a test does not read ``INVISIBLE_SEAL_FILE``.
|
||||
|
||||
The CI jobs export it (a LOCAL seal of the candidate, with no published assets) for the e2e tests that launch the engine under test. A unit test
|
||||
that composes a launch (``build_env``, ``launch_persistent_context``, a second browser served by a virtual display) reaches ``ensure_binary`` and
|
||||
died with ``SealError: the active seal ... is a LOCAL seal with no published assets`` only because of where it ran. Here the variable is taken out
|
||||
of the test's environment (``monkeypatch`` puts it back), and the seal the process had already resolved is dropped, so the test resolves the
|
||||
packaged one; a test that wants a seal sets the variable itself, after this. The e2e tests, which are the ones that need it, keep it."""
|
||||
if request.node.get_closest_marker("e2e") is not None:
|
||||
yield
|
||||
return
|
||||
try:
|
||||
from invisible_core.seal import _reset_active_seal_for_tests
|
||||
except Exception: # the package is absent: the tests that need it say so
|
||||
_reset_active_seal_for_tests = None
|
||||
monkeypatch.delenv("INVISIBLE_SEAL_FILE", raising=False)
|
||||
if _reset_active_seal_for_tests is not None:
|
||||
_reset_active_seal_for_tests()
|
||||
yield
|
||||
if _reset_active_seal_for_tests is not None:
|
||||
_reset_active_seal_for_tests()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _the_lab_declares_the_exit(request, tmp_path_factory):
|
||||
"""Where an e2e launch leaves from is DECLARED, not asked of three services of the internet.
|
||||
|
||||
A launch with no proxy asks the core's ``discover_egress_ip`` for its exit, which asks api.ipify.org, icanhazip.com and checkip.amazonaws.com: a
|
||||
third party in every one of the 222 launches that name neither ``timezone=`` nor ``proxy=``. For a session in which an e2e test is selected, the
|
||||
question with no proxy is answered the exit of the lab (``tests/_lab_egress.py``), and the GeoIP database is the lab's when no leg set one. SESSION
|
||||
scope, because the module-scoped browsers of several files launch before any function-scoped fixture; a test that replaces the question (an exit
|
||||
behind its own gateway) does it with ``monkeypatch`` and goes back to this answer. A session with no e2e test selected is left as it is: the unit
|
||||
tests of the discovery call the real function."""
|
||||
if not any(item.get_closest_marker("e2e") is not None for item in request.session.items):
|
||||
yield None
|
||||
return
|
||||
import _lab_egress
|
||||
|
||||
with pytest.MonkeyPatch.context() as patch:
|
||||
yield _lab_egress.install(patch, tmp_path_factory.mktemp("lab-geoip"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def local_egress_echo(monkeypatch):
|
||||
"""The REAL discovery of the exit, for the test that must prove it, against an echo service of its own on loopback: the three services of the
|
||||
product are replaced by one that answers :data:`_lab_egress.LAB_EGRESS_IP` and counts its questions. Nothing goes to the internet."""
|
||||
from invisible_core import _geo
|
||||
|
||||
import _lab_egress
|
||||
|
||||
current = _geo.discover_egress_ip
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", getattr(current, "original", current))
|
||||
echo = _lab_egress.EchoService()
|
||||
monkeypatch.setattr(_geo, "_IP_ECHO_ENDPOINTS", (echo.url,))
|
||||
yield echo
|
||||
echo.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deterministic_rng():
|
||||
"""Seeded RNG for reproducible tests."""
|
||||
@@ -187,7 +276,7 @@ def firefox_binary():
|
||||
|
||||
1. ``INVPW_BINARY_PATH`` env var - point the whole suite at a local build
|
||||
or a freshly-extracted release (this is how the full-suite gate runs).
|
||||
2. Cached binary under ``cache_dir_for_version()`` (post ``fetch``).
|
||||
2. Cached binary under ``cache_dir_for_seal()`` (post ``fetch``).
|
||||
3. Skip - we never trigger an implicit multi-hundred-MB network download
|
||||
inside a test run.
|
||||
"""
|
||||
@@ -201,10 +290,10 @@ def firefox_binary():
|
||||
# `in None` answered a TypeError that hid the reason - measured 2026-10-25
|
||||
# with a core whose version the wrapper's pin did not name.
|
||||
_require_package()
|
||||
if sys.platform not in BINARY_ENTRY_REL:
|
||||
if sys.platform not in DEFAULT_ENTRY_REL:
|
||||
pytest.skip(f"unsupported platform: {sys.platform}")
|
||||
from invisible_playwright.download import cache_dir_for_version
|
||||
entry = cache_dir_for_version() / BINARY_ENTRY_REL[sys.platform]
|
||||
from invisible_core.download import cache_dir_for_seal
|
||||
entry = cache_dir_for_seal() / DEFAULT_ENTRY_REL[sys.platform]
|
||||
if not entry.exists():
|
||||
pytest.skip(
|
||||
"patched Firefox binary not cached and INVPW_BINARY_PATH unset; "
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
{
|
||||
"os": "linux",
|
||||
"source": "GitHub Actions run 43661728392 (workflow page-bytes-reference-hunt, runner image ubuntu24 20261111.370.1), wrapper commit 455d5619e5, invisible-core 64.71.0, engine firefox-64_159.0_20261114003728, seed 42, locale en-US, timezone Europe/Rome, headless=True; 2 launches, every key below is equal in all of them. `pngs`: the PNG keys, compared on their length and decoded pixels because every PNG carries a per-launch chunk.",
|
||||
"keys": {
|
||||
"c2d.composite.getImageData": {
|
||||
"h": "df65ebe03bf31",
|
||||
"n": 131072
|
||||
},
|
||||
"c2d.composite.jpeg": {
|
||||
"h": "1c1b75006c5984",
|
||||
"n": 11535
|
||||
},
|
||||
"c2d.composite.webp": {
|
||||
"h": "182ab2238ae6c0",
|
||||
"n": 5431
|
||||
},
|
||||
"c2d.gradtext.getImageData": {
|
||||
"h": "ba9fb4487cdea",
|
||||
"n": 352800
|
||||
},
|
||||
"c2d.image.getImageData": {
|
||||
"h": "8218d41a1794c",
|
||||
"n": 76800
|
||||
},
|
||||
"c2d.image.jpeg": {
|
||||
"h": "125de65c968e30",
|
||||
"n": 7315
|
||||
},
|
||||
"c2d.image.webp": {
|
||||
"h": "26ea5dc80f98c",
|
||||
"n": 5659
|
||||
},
|
||||
"c2d.measure": {
|
||||
"h": "14a71ef40cb01c",
|
||||
"n": 9488
|
||||
},
|
||||
"c2d.offscreen.getImageData": {
|
||||
"h": "5a93b1c32ab60",
|
||||
"n": 51200
|
||||
},
|
||||
"c2d.scale.high.getImageData": {
|
||||
"h": "10d3beda5ba224",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.scale.low.getImageData": {
|
||||
"h": "10d3beda5ba224",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.scale.medium.getImageData": {
|
||||
"h": "10d3beda5ba224",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.scale.off.getImageData": {
|
||||
"h": "c673134829639",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.shapes.getImageData": {
|
||||
"h": "18fe9a0f7336da",
|
||||
"n": 163840
|
||||
},
|
||||
"c2d.shapes.jpeg": {
|
||||
"h": "18d82802030ab3",
|
||||
"n": 6975
|
||||
},
|
||||
"c2d.shapes.webp": {
|
||||
"h": "1ec9fa4e39f8de",
|
||||
"n": 3287
|
||||
},
|
||||
"c2d.text.getImageData": {
|
||||
"h": "e141df45718e",
|
||||
"n": 856960
|
||||
},
|
||||
"c2d.text.jpeg": {
|
||||
"h": "23b24c30781ee",
|
||||
"n": 41751
|
||||
},
|
||||
"c2d.text.webp": {
|
||||
"h": "1b0cc3c21c4f0f",
|
||||
"n": 26215
|
||||
},
|
||||
"dom.fonts_check": {
|
||||
"s": "[[\"16px sans-serif\",true],[\"20px serif\",true],[\"18px monospace\",true],[\"bold 16px Arial\",true],[\"italic 15px 'Segoe UI'\",true],[\"16px 'Times New Roman'\",true],[\"16px Calibri\",true],[\"14px Consolas\",true],[\"16px Verdana\",true],[\"16px Tahoma\",true],[\"17px Georgia\",true],[\"16px 'Segoe UI Emoji'\",true],[\"16px 'Microsoft YaHei'\",true],[\"16px 'Yu Gothic'\",true]]"
|
||||
},
|
||||
"dom.paragraphs": {
|
||||
"s": "[[\"16px sans-serif\",200,21],[\"15px 'Times New Roman'\",200,20],[\"14px Consolas\",200,19]]"
|
||||
},
|
||||
"dom.span_boxes": {
|
||||
"h": "1435dcc5a321d6",
|
||||
"n": 5864
|
||||
},
|
||||
"dom.system_colors": {
|
||||
"s": "[[\"Canvas\",\"rgb(255, 255, 255)\"],[\"CanvasText\",\"rgb(0, 0, 0)\"],[\"ButtonFace\",\"rgb(233, 233, 237)\"],[\"ButtonText\",\"rgb(0, 0, 0)\"],[\"ButtonBorder\",\"rgb(129, 127, 132)\"],[\"Field\",\"rgb(255, 255, 255)\"],[\"FieldText\",\"rgb(0, 0, 0)\"],[\"Highlight\",\"rgb(0, 120, 215)\"],[\"HighlightText\",\"rgb(255, 255, 255)\"],[\"GrayText\",\"rgb(109, 109, 109)\"],[\"LinkText\",\"rgb(0, 0, 238)\"],[\"VisitedText\",\"rgb(85, 26, 139)\"],[\"ActiveText\",\"rgb(238, 0, 0)\"],[\"Mark\",\"rgb(255, 255, 0)\"],[\"MarkText\",\"rgb(0, 0, 0)\"],[\"AccentColor\",\"rgb(0, 96, 223)\"],[\"AccentColorText\",\"rgb(255, 255, 255)\"],[\"SelectedItem\",\"rgb(0, 120, 215)\"],[\"SelectedItemText\",\"rgb(255, 255, 255)\"]]"
|
||||
},
|
||||
"env.dpr": {
|
||||
"s": "1"
|
||||
},
|
||||
"env.hw": {
|
||||
"s": "8"
|
||||
},
|
||||
"env.lang": {
|
||||
"s": "[\"en-US\",\"en\"]"
|
||||
},
|
||||
"env.mq": {
|
||||
"s": "[true,false,false,false,false,false,false]"
|
||||
},
|
||||
"env.oscpu": {
|
||||
"s": "Windows NT 10.0; Win64; x64"
|
||||
},
|
||||
"env.platform": {
|
||||
"s": "Win32"
|
||||
},
|
||||
"env.screen": {
|
||||
"s": "[1920,1080,1920,1032,24,24]"
|
||||
},
|
||||
"env.ua": {
|
||||
"s": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0"
|
||||
},
|
||||
"gl1.anisotropy": {
|
||||
"s": "16"
|
||||
},
|
||||
"gl1.antialias.false.readPixels": {
|
||||
"h": "abed055e93fb8",
|
||||
"n": 36864
|
||||
},
|
||||
"gl1.antialias.false.samples": {
|
||||
"s": "0"
|
||||
},
|
||||
"gl1.antialias.true.readPixels": {
|
||||
"h": "155744fc8af4b9",
|
||||
"n": 36864
|
||||
},
|
||||
"gl1.antialias.true.samples": {
|
||||
"s": "4"
|
||||
},
|
||||
"gl1.attributes": {
|
||||
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
|
||||
},
|
||||
"gl1.blend.readPixels": {
|
||||
"h": "cfef8e9072c0c",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.depth_stencil.readPixels": {
|
||||
"h": "eaa3d5d41cfb",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.extension_objects": {
|
||||
"s": "[[\"ANGLE_instanced_arrays\",4],[\"EXT_blend_minmax\",2],[\"EXT_clip_control\",7],[\"EXT_color_buffer_half_float\",4],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_frag_depth\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_shader_texture_lod\",0],[\"EXT_sRGB\",4],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"OES_element_index_uint\",0],[\"OES_fbo_render_mipmap\",0],[\"OES_standard_derivatives\",1],[\"OES_texture_float\",0],[\"OES_texture_float_linear\",0],[\"OES_texture_half_float\",1],[\"OES_texture_half_float_linear\",0],[\"OES_vertex_array_object\",5],[\"WEBGL_color_buffer_float\",4],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_depth_texture\",1],[\"WEBGL_draw_buffers\",35],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
|
||||
},
|
||||
"gl1.extensions": {
|
||||
"s": "[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
|
||||
},
|
||||
"gl1.lines_points.readPixels": {
|
||||
"h": "1841f80a258941",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.math.highp.readPixels": {
|
||||
"h": "14f93cecd95f86",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.math.mediump.readPixels": {
|
||||
"h": "14f93cecd95f86",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.params": {
|
||||
"s": "{\"VERSION\":\"WebGL 1.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 1.0\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4}"
|
||||
},
|
||||
"gl1.precision": {
|
||||
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
|
||||
},
|
||||
"gl1.texture.linear.readPixels": {
|
||||
"h": "5fdcdb999f3e0",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.texture.mip.readPixels": {
|
||||
"h": "5fdcdb999f3e0",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.texture.nearest.readPixels": {
|
||||
"h": "160f810aa6835f",
|
||||
"n": 16384
|
||||
},
|
||||
"gl1.triangle.drawImage": {
|
||||
"h": "81a61d733e561",
|
||||
"n": 36864
|
||||
},
|
||||
"gl1.triangle.readPixels": {
|
||||
"h": "12bb7ce7d2f21",
|
||||
"n": 36864
|
||||
},
|
||||
"gl1.triangle.toDataURL_jpeg": {
|
||||
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vT67/5/5nl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/zufI4tRn8LO4ijq3FHXmsvjPU3iKRrbRMejohJH5kj9KpzeKNZmiaNr5wp6lFVD+YAIprh/HVPicV83+iPncRldSts0j1e+02HUrCW0uQxilGDtOCOcgj6ECvHdb0yfSNSmtLhWBU/IxGN654YfX/wCt2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/2Q=="
|
||||
},
|
||||
"gl1.unmasked": {
|
||||
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
|
||||
},
|
||||
"gl2.anisotropy": {
|
||||
"s": "16"
|
||||
},
|
||||
"gl2.antialias.false.readPixels": {
|
||||
"h": "abed055e93fb8",
|
||||
"n": 36864
|
||||
},
|
||||
"gl2.antialias.false.samples": {
|
||||
"s": "0"
|
||||
},
|
||||
"gl2.antialias.true.readPixels": {
|
||||
"h": "155744fc8af4b9",
|
||||
"n": 36864
|
||||
},
|
||||
"gl2.antialias.true.samples": {
|
||||
"s": "4"
|
||||
},
|
||||
"gl2.attributes": {
|
||||
"s": "{\"alpha\":true,\"antialias\":true,\"depth\":true,\"failIfMajorPerformanceCaveat\":false,\"powerPreference\":\"default\",\"premultipliedAlpha\":true,\"preserveDrawingBuffer\":true,\"stencil\":false}"
|
||||
},
|
||||
"gl2.blend.readPixels": {
|
||||
"h": "cfef8e9072c0c",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.depth_stencil.readPixels": {
|
||||
"h": "eaa3d5d41cfb",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.extension_objects": {
|
||||
"s": "[[\"EXT_clip_control\",7],[\"EXT_color_buffer_float\",0],[\"EXT_depth_clamp\",1],[\"EXT_float_blend\",0],[\"EXT_polygon_offset_clamp\",2],[\"EXT_texture_compression_bptc\",4],[\"EXT_texture_compression_rgtc\",4],[\"EXT_texture_filter_anisotropic\",2],[\"EXT_texture_mirror_clamp_to_edge\",1],[\"EXT_texture_norm16\",8],[\"OES_draw_buffers_indexed\",7],[\"OES_texture_float_linear\",0],[\"OVR_multiview2\",5],[\"WEBGL_compressed_texture_s3tc\",4],[\"WEBGL_compressed_texture_s3tc_srgb\",4],[\"WEBGL_debug_renderer_info\",2],[\"WEBGL_debug_shaders\",1],[\"WEBGL_lose_context\",2],[\"WEBGL_provoking_vertex\",4]]"
|
||||
},
|
||||
"gl2.extensions": {
|
||||
"s": "[\"EXT_clip_control\",\"EXT_color_buffer_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_polygon_offset_clamp\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"EXT_texture_norm16\",\"OES_draw_buffers_indexed\",\"OES_texture_float_linear\",\"OVR_multiview2\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"]"
|
||||
},
|
||||
"gl2.float_target.readPixels": {
|
||||
"h": "1ba8f4b0bbe2d8",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.lines_points.readPixels": {
|
||||
"h": "1841f80a258941",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.math.highp.readPixels": {
|
||||
"h": "14f93cecd95f86",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.math.mediump.readPixels": {
|
||||
"h": "14f93cecd95f86",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.msaa_resolve.readPixels": {
|
||||
"h": "1a2cbef856e591",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.params": {
|
||||
"s": "{\"VERSION\":\"WebGL 2.0\",\"SHADING_LANGUAGE_VERSION\":\"WebGL GLSL ES 3.00\",\"VENDOR\":\"Mozilla\",\"RENDERER\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"MAX_TEXTURE_SIZE\":16384,\"MAX_CUBE_MAP_TEXTURE_SIZE\":16384,\"MAX_RENDERBUFFER_SIZE\":16384,\"MAX_VIEWPORT_DIMS\":[32767,32767],\"ALIASED_LINE_WIDTH_RANGE\":[1,1],\"ALIASED_POINT_SIZE_RANGE\":[1,1024],\"MAX_VERTEX_ATTRIBS\":16,\"MAX_VARYING_VECTORS\":30,\"MAX_COMBINED_TEXTURE_IMAGE_UNITS\":32,\"MAX_VERTEX_TEXTURE_IMAGE_UNITS\":16,\"MAX_TEXTURE_IMAGE_UNITS\":16,\"MAX_VERTEX_UNIFORM_VECTORS\":4096,\"MAX_FRAGMENT_UNIFORM_VECTORS\":1024,\"RED_BITS\":8,\"GREEN_BITS\":8,\"BLUE_BITS\":8,\"ALPHA_BITS\":8,\"DEPTH_BITS\":24,\"STENCIL_BITS\":0,\"SAMPLES\":4,\"SAMPLE_BUFFERS\":1,\"SUBPIXEL_BITS\":4,\"MAX_3D_TEXTURE_SIZE\":2048,\"MAX_ARRAY_TEXTURE_LAYERS\":2048,\"MAX_COLOR_ATTACHMENTS\":8,\"MAX_DRAW_BUFFERS\":8,\"MAX_ELEMENTS_INDICES\":2147483647,\"MAX_ELEMENTS_VERTICES\":2147483647,\"MAX_FRAGMENT_INPUT_COMPONENTS\":120,\"MAX_FRAGMENT_UNIFORM_BLOCKS\":12,\"MAX_FRAGMENT_UNIFORM_COMPONENTS\":4096,\"MAX_PROGRAM_TEXEL_OFFSET\":7,\"MAX_SAMPLES\":8,\"MAX_SERVER_WAIT_TIMEOUT\":0,\"MAX_TEXTURE_LOD_BIAS\":2,\"MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS\":120,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS\":4,\"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS\":4,\"MAX_UNIFORM_BLOCK_SIZE\":65536,\"MAX_UNIFORM_BUFFER_BINDINGS\":24,\"MAX_VARYING_COMPONENTS\":120,\"MAX_VERTEX_OUTPUT_COMPONENTS\":120,\"MAX_VERTEX_UNIFORM_BLOCKS\":12,\"MAX_VERTEX_UNIFORM_COMPONENTS\":16384,\"MIN_PROGRAM_TEXEL_OFFSET\":-8,\"MAX_COMBINED_UNIFORM_BLOCKS\":24,\"MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS\":200704,\"MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS\":212992,\"UNIFORM_BUFFER_OFFSET_ALIGNMENT\":256}"
|
||||
},
|
||||
"gl2.precision": {
|
||||
"s": "[[\"VERTEX_SHADER\",\"LOW_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"VERTEX_SHADER\",\"LOW_INT\",31,30,0],[\"VERTEX_SHADER\",\"MEDIUM_INT\",31,30,0],[\"VERTEX_SHADER\",\"HIGH_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"LOW_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"MEDIUM_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"HIGH_FLOAT\",127,127,23],[\"FRAGMENT_SHADER\",\"LOW_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"MEDIUM_INT\",31,30,0],[\"FRAGMENT_SHADER\",\"HIGH_INT\",31,30,0]]"
|
||||
},
|
||||
"gl2.texture.linear.readPixels": {
|
||||
"h": "5fdcdb999f3e0",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.texture.mip.readPixels": {
|
||||
"h": "5fdcdb999f3e0",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.texture.nearest.readPixels": {
|
||||
"h": "160f810aa6835f",
|
||||
"n": 16384
|
||||
},
|
||||
"gl2.triangle.drawImage": {
|
||||
"h": "81a61d733e561",
|
||||
"n": 36864
|
||||
},
|
||||
"gl2.triangle.readPixels": {
|
||||
"h": "12bb7ce7d2f21",
|
||||
"n": 36864
|
||||
},
|
||||
"gl2.triangle.toDataURL_jpeg": {
|
||||
"s": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxKiiivTPOCiiigAopDwOaro5MpfnB7e1enl+V1ceqjp/ZV/V9vnqJuyuWaKKK81pp2YwooopAFFFFABRRRQAUUUUAMlPy4HU0RR05U3NmrMUdfdZXbBYZR6vV/wBeR1VaHJTV9yMxHZkdqjrTijqre25hYMPuN+h9K8LOKMZT9vT67/5/5nl0qtpezl8itRRRXhHUFFFFABRRRQAUqjJxSVYt4+MnvW+GipVE3sjvy7CvE1kui1YsUdW4o6WKOrcUdevUx3mehjqe4kUdWTbrLEyOPlYYp8UdW4o64KuNvofG46DTujj7y3a1uGifnHIOOoqGu01LTRfW2wELIpyjEd/Q+1cYysjFXBVgcEEYINeepxk9DfB4pV42fxLf/MSiiimdgUUUUAOiQu4UfjWpFHjFQafD8pc9+BWnFHWM8Uqd0j7zJsv9hg1Vkvenr8un+fzEijq3FHSxR1bijriqY7zPPx1PcSKOrcUdLFHVuKOuCpjvM+Nx1PcSKOsHxdpDPF9ugUl0GJVUD7v978On0+ldTFHVuKOuVZk6U1JHys608LVVWHT8Txyit/xboR0m7WSBXNnL91jyEb+7n9Rn9cGsCvp6FeFeCqU3dM+qoV4YimqlN6MKdGhkdUXqTim1p6PAGLSnnHyipxNdYek6jPaybLpZljIYdbPf0W/9dy/DEFAAHAGBVuKOlijqYyQQsFmmjRsZwzAGvk54yU3Zas/VsfCFOOtkvuJIo6txR1SbUrCDbvuYzn+5838s0kniHT4du1pJc9didPzxWXLiqnwU2/kz4jH1qKuudfebMUdW4o65iTxbaogMFtM755DkKMfUZqGbxpNsAtrKNHzyZHLjH0GKn+zsfU2hb1a/zufI4tRn8LO4ijq3FHXmsvjPU3iKRrbRMejohJH5kj9KpzeKNZmiaNr5wp6lFVD+YAIprh/HVPicV83+iPncRldSts0j1e+02HUrCW0uQxilGDtOCOcgj6ECvHdb0yfSNSmtLhWBU/IxGN654YfX/wCt2ok1fUpI2jk1C8eNgVZWnYgg9QRmqNe7lGWYjAOSnUTi+luve9/0Ncsy6rgpSvO8X0t17hUiTyooVJZFA7BiKjor25RUlaSue3TqzpO9OTT8tB0kjyHMjs5xjLHNNooppJKyJlJzfNJ3YUUUUCCiiigAooooAKKKKAP/2Q=="
|
||||
},
|
||||
"gl2.unmasked": {
|
||||
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
|
||||
},
|
||||
"gpu.webgpu.features": {
|
||||
"s": "{\"depth-clip-control\":true,\"depth32float-stencil8\":true,\"texture-compression-bc\":true,\"texture-compression-bc-sliced-3d\":true,\"texture-compression-etc2\":false,\"texture-compression-astc\":false,\"texture-compression-astc-sliced-3d\":false,\"timestamp-query\":true,\"indirect-first-instance\":true,\"shader-f16\":true,\"rg11b10ufloat-renderable\":true,\"bgra8unorm-storage\":true,\"float32-filterable\":true,\"float32-blendable\":true,\"clip-distances\":false,\"dual-source-blending\":true,\"subgroups\":false}"
|
||||
},
|
||||
"gpu.webgpu.info": {
|
||||
"s": "{\"vendor\":\"\",\"architecture\":\"\",\"device\":\"\",\"description\":\"\"}"
|
||||
},
|
||||
"gpu.webgpu.limits": {
|
||||
"s": "{\"maxTextureDimension1D\":16384,\"maxTextureDimension2D\":16384,\"maxTextureDimension3D\":2048,\"maxTextureArrayLayers\":2048,\"maxBindGroups\":8,\"maxBindGroupsPlusVertexBuffers\":24,\"maxBindingsPerBindGroup\":4294967295,\"maxDynamicUniformBuffersPerPipelineLayout\":8,\"maxDynamicStorageBuffersPerPipelineLayout\":4,\"maxSampledTexturesPerShaderStage\":64,\"maxSamplersPerShaderStage\":64,\"maxStorageBuffersPerShaderStage\":64,\"maxStorageTexturesPerShaderStage\":64,\"maxUniformBuffersPerShaderStage\":64,\"maxUniformBufferBindingSize\":65536,\"maxStorageBufferBindingSize\":2147483644,\"minUniformBufferOffsetAlignment\":256,\"minStorageBufferOffsetAlignment\":32,\"maxVertexBuffers\":16,\"maxBufferSize\":2147483644,\"maxVertexAttributes\":30,\"maxVertexBufferArrayStride\":2048,\"maxInterStageShaderVariables\":31,\"maxColorAttachments\":8,\"maxColorAttachmentBytesPerSample\":128,\"maxComputeWorkgroupStorageSize\":32768,\"maxComputeInvocationsPerWorkgroup\":1024,\"maxComputeWorkgroupSizeX\":1024,\"maxComputeWorkgroupSizeY\":1024,\"maxComputeWorkgroupSizeZ\":64,\"maxComputeWorkgroupsPerDimension\":65535}"
|
||||
},
|
||||
"worker.webgl": {
|
||||
"s": "{\"vendor\":\"Mozilla\",\"renderer\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"unmasked\":[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"],\"exts\":[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"],\"px\":[64,128,191,255,64,128,191,255,64,128,191,255,64,128,191,255]}"
|
||||
}
|
||||
},
|
||||
"pngs": {
|
||||
"c2d.composite.png": {
|
||||
"n": 2414,
|
||||
"w": 256,
|
||||
"h": 128,
|
||||
"ct": 6,
|
||||
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
|
||||
},
|
||||
"c2d.composite.toBlob": {
|
||||
"n": 1794,
|
||||
"w": 256,
|
||||
"h": 128,
|
||||
"ct": 6,
|
||||
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
|
||||
},
|
||||
"c2d.gradtext.png": {
|
||||
"n": 56850,
|
||||
"w": 420,
|
||||
"h": 210,
|
||||
"ct": 6,
|
||||
"sha256": "a294763c6eca0c9178d09052cfaa5ac92932d8cf32909f31bbb387810d473310"
|
||||
},
|
||||
"c2d.image.png": {
|
||||
"n": 19502,
|
||||
"w": 160,
|
||||
"h": 120,
|
||||
"ct": 6,
|
||||
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
|
||||
},
|
||||
"c2d.image.toBlob": {
|
||||
"n": 14610,
|
||||
"w": 160,
|
||||
"h": 120,
|
||||
"ct": 6,
|
||||
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
|
||||
},
|
||||
"c2d.offscreen.convertToBlob": {
|
||||
"n": 2687,
|
||||
"w": 160,
|
||||
"h": 80,
|
||||
"ct": 6,
|
||||
"sha256": "38b7fa4aa1d61a5bae5b92e8b9216ff61ce4d4a8d15cc0fa6d8a8c8441a3fdb8"
|
||||
},
|
||||
"c2d.scale.high.png": {
|
||||
"n": 47314,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
|
||||
},
|
||||
"c2d.scale.low.png": {
|
||||
"n": 47314,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
|
||||
},
|
||||
"c2d.scale.medium.png": {
|
||||
"n": 47314,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
|
||||
},
|
||||
"c2d.scale.off.png": {
|
||||
"n": 20890,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "c28700e28636d69dfe9bf293fadebae1fdf970949ac90147836ab1837065f46d"
|
||||
},
|
||||
"c2d.shapes.png": {
|
||||
"n": 19226,
|
||||
"w": 256,
|
||||
"h": 160,
|
||||
"ct": 6,
|
||||
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
|
||||
},
|
||||
"c2d.shapes.toBlob": {
|
||||
"n": 14402,
|
||||
"w": 256,
|
||||
"h": 160,
|
||||
"ct": 6,
|
||||
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
|
||||
},
|
||||
"c2d.text.png": {
|
||||
"n": 51610,
|
||||
"w": 520,
|
||||
"h": 412,
|
||||
"ct": 6,
|
||||
"sha256": "1c56511f78721be0423bbcef100bf7b52e9997da498bd1f771d0d8348a791d3b"
|
||||
},
|
||||
"c2d.text.toBlob": {
|
||||
"n": 38691,
|
||||
"w": 520,
|
||||
"h": 412,
|
||||
"ct": 6,
|
||||
"sha256": "1c56511f78721be0423bbcef100bf7b52e9997da498bd1f771d0d8348a791d3b"
|
||||
},
|
||||
"gl1.triangle.toDataURL": {
|
||||
"n": 7470,
|
||||
"w": 96,
|
||||
"h": 96,
|
||||
"ct": 6,
|
||||
"sha256": "3f24afcf21a411e18ef9256e558a30ec589bbb51923fedf485cd0e6a2dcd9919"
|
||||
},
|
||||
"gl2.triangle.toDataURL": {
|
||||
"n": 7470,
|
||||
"w": 96,
|
||||
"h": 96,
|
||||
"ct": 6,
|
||||
"sha256": "3f24afcf21a411e18ef9256e558a30ec589bbb51923fedf485cd0e6a2dcd9919"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"os": "windows",
|
||||
"source": "GitHub Actions run 43652292533 (workflow 'cpu render path hunt vm', job on windows-2022), arm `ours` = the published engine firefox-64_159.0_20261114003728 with the core the branch installed from the index (before the declaration of software compositing), seed 42, locale en-US, timezone Europe/Rome, headless=True; launched twice, and the arm `ours_vmretail` (the VM decisions of the new core) twice more: every key below is equal in the four launches. `pngs`: the PNG keys, whose bytes differ in a 16-byte chunk `deBG` in every launch; their length, and the pixels they decode to where the hunt kept the bytes (a data URL longer than 3000 characters was kept as hash and length only: those five entries have no `sha256` and are written by the first run of tests/test_the_bytes_a_page_reads_do_not_change_e2e.py on the engine of the reference). The keys of c2d.scale.*, c2d.gradtext.*, gpu.webgpu.features and gpu.webgpu.limits were added to the probe after that run (in it the WebGPU read threw `Xray wrapping of iterators not supported`, key gpu.webgpu.error, dropped here) and are in no reference yet.",
|
||||
"source": "GitHub Actions run 43661728392 (workflow page-bytes-reference-hunt, runner image win22 20261112.366.7), wrapper commit 455d5619e5, invisible-core 64.71.0, engine firefox-64_159.0_20261114003728, seed 42, locale en-US, timezone Europe/Rome, headless=True; 2 launches, every key below is equal in all of them. `pngs`: the PNG keys, compared on their length and decoded pixels because every PNG carries a per-launch chunk.",
|
||||
"keys": {
|
||||
"c2d.composite.getImageData": {
|
||||
"h": "df65ebe03bf31",
|
||||
@@ -14,6 +14,10 @@
|
||||
"h": "182ab2238ae6c0",
|
||||
"n": 5431
|
||||
},
|
||||
"c2d.gradtext.getImageData": {
|
||||
"h": "42edf4d4d5394",
|
||||
"n": 352800
|
||||
},
|
||||
"c2d.image.getImageData": {
|
||||
"h": "8218d41a1794c",
|
||||
"n": 76800
|
||||
@@ -34,6 +38,22 @@
|
||||
"h": "1d9666b372acb1",
|
||||
"n": 51200
|
||||
},
|
||||
"c2d.scale.high.getImageData": {
|
||||
"h": "10d3beda5ba224",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.scale.low.getImageData": {
|
||||
"h": "10d3beda5ba224",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.scale.medium.getImageData": {
|
||||
"h": "10d3beda5ba224",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.scale.off.getImageData": {
|
||||
"h": "c673134829639",
|
||||
"n": 114400
|
||||
},
|
||||
"c2d.shapes.getImageData": {
|
||||
"h": "18fe9a0f7336da",
|
||||
"n": 163840
|
||||
@@ -259,9 +279,15 @@
|
||||
"gl2.unmasked": {
|
||||
"s": "[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"]"
|
||||
},
|
||||
"gpu.webgpu.features": {
|
||||
"s": "{\"depth-clip-control\":true,\"depth32float-stencil8\":true,\"texture-compression-bc\":true,\"texture-compression-bc-sliced-3d\":true,\"texture-compression-etc2\":false,\"texture-compression-astc\":false,\"texture-compression-astc-sliced-3d\":false,\"timestamp-query\":true,\"indirect-first-instance\":true,\"shader-f16\":true,\"rg11b10ufloat-renderable\":true,\"bgra8unorm-storage\":true,\"float32-filterable\":true,\"float32-blendable\":true,\"clip-distances\":false,\"dual-source-blending\":true,\"subgroups\":false}"
|
||||
},
|
||||
"gpu.webgpu.info": {
|
||||
"s": "{\"vendor\":\"\",\"architecture\":\"\",\"device\":\"\",\"description\":\"\"}"
|
||||
},
|
||||
"gpu.webgpu.limits": {
|
||||
"s": "{\"maxTextureDimension1D\":16384,\"maxTextureDimension2D\":16384,\"maxTextureDimension3D\":2048,\"maxTextureArrayLayers\":2048,\"maxBindGroups\":8,\"maxBindGroupsPlusVertexBuffers\":24,\"maxBindingsPerBindGroup\":4294967295,\"maxDynamicUniformBuffersPerPipelineLayout\":8,\"maxDynamicStorageBuffersPerPipelineLayout\":4,\"maxSampledTexturesPerShaderStage\":64,\"maxSamplersPerShaderStage\":64,\"maxStorageBuffersPerShaderStage\":64,\"maxStorageTexturesPerShaderStage\":64,\"maxUniformBuffersPerShaderStage\":64,\"maxUniformBufferBindingSize\":65536,\"maxStorageBufferBindingSize\":2147483644,\"minUniformBufferOffsetAlignment\":256,\"minStorageBufferOffsetAlignment\":32,\"maxVertexBuffers\":16,\"maxBufferSize\":2147483644,\"maxVertexAttributes\":30,\"maxVertexBufferArrayStride\":2048,\"maxInterStageShaderVariables\":31,\"maxColorAttachments\":8,\"maxColorAttachmentBytesPerSample\":128,\"maxComputeWorkgroupStorageSize\":32768,\"maxComputeInvocationsPerWorkgroup\":1024,\"maxComputeWorkgroupSizeX\":1024,\"maxComputeWorkgroupSizeY\":1024,\"maxComputeWorkgroupSizeZ\":64,\"maxComputeWorkgroupsPerDimension\":65535}"
|
||||
},
|
||||
"worker.webgl": {
|
||||
"s": "{\"vendor\":\"Mozilla\",\"renderer\":\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\",\"unmasked\":[\"Google Inc. (Intel)\",\"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar\"],\"exts\":[\"ANGLE_instanced_arrays\",\"EXT_blend_minmax\",\"EXT_clip_control\",\"EXT_color_buffer_half_float\",\"EXT_depth_clamp\",\"EXT_float_blend\",\"EXT_frag_depth\",\"EXT_polygon_offset_clamp\",\"EXT_shader_texture_lod\",\"EXT_sRGB\",\"EXT_texture_compression_bptc\",\"EXT_texture_compression_rgtc\",\"EXT_texture_filter_anisotropic\",\"EXT_texture_mirror_clamp_to_edge\",\"OES_element_index_uint\",\"OES_fbo_render_mipmap\",\"OES_standard_derivatives\",\"OES_texture_float\",\"OES_texture_float_linear\",\"OES_texture_half_float\",\"OES_texture_half_float_linear\",\"OES_vertex_array_object\",\"WEBGL_color_buffer_float\",\"WEBGL_compressed_texture_s3tc\",\"WEBGL_compressed_texture_s3tc_srgb\",\"WEBGL_debug_renderer_info\",\"WEBGL_debug_shaders\",\"WEBGL_depth_texture\",\"WEBGL_draw_buffers\",\"WEBGL_lose_context\",\"WEBGL_provoking_vertex\"],\"px\":[64,128,191,255,64,128,191,255,64,128,191,255,64,128,191,255]}"
|
||||
}
|
||||
@@ -281,8 +307,19 @@
|
||||
"ct": 6,
|
||||
"sha256": "fb585f18240eb1a787a5b146d6332a0376dae76f8c8716e99f68fbbf9eff905e"
|
||||
},
|
||||
"c2d.gradtext.png": {
|
||||
"n": 55210,
|
||||
"w": 420,
|
||||
"h": 210,
|
||||
"ct": 6,
|
||||
"sha256": "1ce15c9ea557be69b62b4893b148345a694a93222c721b1bbb21cdcedebba5a0"
|
||||
},
|
||||
"c2d.image.png": {
|
||||
"n": 19502
|
||||
"n": 19502,
|
||||
"w": 160,
|
||||
"h": 120,
|
||||
"ct": 6,
|
||||
"sha256": "51bc3789f2e238dfbf8899eb7a965a4f04d3e0e7f2246b1bd3cfdc9597bd2a77"
|
||||
},
|
||||
"c2d.image.toBlob": {
|
||||
"n": 14610,
|
||||
@@ -298,8 +335,40 @@
|
||||
"ct": 6,
|
||||
"sha256": "55b4c78cd7b05627e9b2767477d61063b6849a7636c5be2ce0a62c6a2c6c9cc4"
|
||||
},
|
||||
"c2d.scale.high.png": {
|
||||
"n": 47314,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
|
||||
},
|
||||
"c2d.scale.low.png": {
|
||||
"n": 47314,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
|
||||
},
|
||||
"c2d.scale.medium.png": {
|
||||
"n": 47314,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "8672b8676f90d662b4809e56c55da58e05be4e72b2f7c543b33da4bdafb0ce21"
|
||||
},
|
||||
"c2d.scale.off.png": {
|
||||
"n": 20890,
|
||||
"w": 220,
|
||||
"h": 130,
|
||||
"ct": 6,
|
||||
"sha256": "c28700e28636d69dfe9bf293fadebae1fdf970949ac90147836ab1837065f46d"
|
||||
},
|
||||
"c2d.shapes.png": {
|
||||
"n": 19226
|
||||
"n": 19226,
|
||||
"w": 256,
|
||||
"h": 160,
|
||||
"ct": 6,
|
||||
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
|
||||
},
|
||||
"c2d.shapes.toBlob": {
|
||||
"n": 14402,
|
||||
@@ -309,7 +378,11 @@
|
||||
"sha256": "89ee57c100f4682099bd3a5f2de56c5b31091dae253bd7e3db4f254fb8b9e6a3"
|
||||
},
|
||||
"c2d.text.png": {
|
||||
"n": 42670
|
||||
"n": 42670,
|
||||
"w": 520,
|
||||
"h": 412,
|
||||
"ct": 6,
|
||||
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
|
||||
},
|
||||
"c2d.text.toBlob": {
|
||||
"n": 31986,
|
||||
@@ -319,10 +392,18 @@
|
||||
"sha256": "93d6fc37d2263e52e7b1b46f77c65d9e607faf577eb7c255dc38cbce8b7d7602"
|
||||
},
|
||||
"gl1.triangle.toDataURL": {
|
||||
"n": 7474
|
||||
"n": 7474,
|
||||
"w": 96,
|
||||
"h": 96,
|
||||
"ct": 6,
|
||||
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
|
||||
},
|
||||
"gl2.triangle.toDataURL": {
|
||||
"n": 7474
|
||||
"n": 7474,
|
||||
"w": 96,
|
||||
"h": 96,
|
||||
"ct": 6,
|
||||
"sha256": "9989d00c92e8ae035dede9b81b1c9942223799c0ccc4d4875c8eca9efaca776c"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,15 @@ humanised pointer, computed with the CLIENT-SIDE code of commit 5d9ad70
|
||||
|
||||
Run against the OLD tree only:
|
||||
PYTHONPATH=<worktree at 5d9ad70>/src python gen_golden.py > pointer_golden.json
|
||||
(`--from-old-client`, below, is that run: on any later tree `_cursor._approach` does not exist and the script refuses, naming
|
||||
the four sessions it cannot make.)
|
||||
|
||||
THE CURRENT SERVER'S RUN, to a file, never over the golden:
|
||||
PYTHONPATH=<this tree>/src python tests/data/pointer_golden_origin.py --from-current OUT.json
|
||||
It plays every session of the file through the current `PageDispatcher` on a virtual clock that is BOTH the sleeps AND the core's
|
||||
`time.monotonic` (a stroke counts its instants on it), drops the `stroke` and `at` tags the old client did not send, writes the file
|
||||
in the golden's own layout and says, per session, whether it is the golden's. The golden is the old client's walk; this is the check
|
||||
that the current path still draws it, and it refuses to write onto `pointer_golden.json` itself.
|
||||
|
||||
REVISION 1 (feat/rt-dblmove): the `explicit_pointer` session, the only one with
|
||||
a `Mouse.click`, no longer carries the duplicate the client's `Mouse._click`
|
||||
@@ -309,7 +318,7 @@ def dump_golden(g):
|
||||
out.append(" ]")
|
||||
out.append(" }" + ("," if n < len(names) - 1 else ""))
|
||||
out += [" }", "}"]
|
||||
return "\r\n".join(out) + "\r\n"
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def _server_session(spec, name):
|
||||
@@ -319,14 +328,17 @@ def _server_session(spec, name):
|
||||
|
||||
clock = T.VirtualClock()
|
||||
pointer_mod._CLOCK = clock
|
||||
# the clock of the sleeps AND of `time.monotonic`: a stroke waits "until instant X" on the latter
|
||||
core_actions.time = SimpleNamespace(
|
||||
sleep=clock.sleep, monotonic=time.monotonic,
|
||||
sleep=clock.sleep, monotonic=clock.now,
|
||||
perf_counter=time.perf_counter)
|
||||
page = T.build_page(clock, T._boxes_of(name), seed=spec["seed"],
|
||||
number=spec["number"], budget=spec["budget"],
|
||||
hits=spec.get("hits", "all"))
|
||||
T.play(page, clock, spec["ops"])
|
||||
return json.loads(json.dumps(page.log))
|
||||
# `stroke` and `at` are the tags of the core's strokes, which the old client did not send
|
||||
return [{k: v for k, v in e.items() if k not in ("stroke", "at")}
|
||||
for e in json.loads(json.dumps(page.log))]
|
||||
|
||||
|
||||
def _shape(evs): # the latency is a draw per event ordinal, not an event
|
||||
@@ -397,6 +409,33 @@ def revise_standstill(path):
|
||||
})
|
||||
|
||||
|
||||
def from_current(out_path):
|
||||
"""The current server's run of every session of the golden, written to `out_path` in the golden's layout. Never over the
|
||||
golden itself. True when every session is what the golden holds, event for event, latency included."""
|
||||
import pathlib
|
||||
root = pathlib.Path(__file__).resolve().parents[2]
|
||||
if str(root) not in sys.path:
|
||||
sys.path.insert(0, str(root))
|
||||
gp = pathlib.Path(__file__).with_name("pointer_golden.json").resolve()
|
||||
if pathlib.Path(out_path).resolve() == gp:
|
||||
sys.exit("refusing: the golden is the old client's walk, not what the current server draws; write to another file")
|
||||
with open(gp, newline="", encoding="utf-8") as fh:
|
||||
text = fh.read()
|
||||
g = json.loads(text)
|
||||
same = True
|
||||
for name, sc in g["scenarios"].items():
|
||||
new = _server_session(sc["spec"], name)
|
||||
ok = new == sc["engine_events"]
|
||||
same = same and ok
|
||||
print("%-22s %3d events, golden %3d: %s" % (name, len(new), len(sc["engine_events"]),
|
||||
"identical" if ok else "DIFFERS"))
|
||||
sc["engine_events"] = new
|
||||
with open(out_path, "w", newline="", encoding="utf-8") as fh:
|
||||
fh.write(dump_golden(g))
|
||||
print("written %s; byte for byte the golden's: %s" % (out_path, dump_golden(g) == text))
|
||||
return same
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import pathlib
|
||||
for flag, fn in (("--revise-mouse-click", revise_mouse_click),
|
||||
@@ -406,6 +445,19 @@ if __name__ == "__main__":
|
||||
fn(sys.argv[i + 1] if len(sys.argv) > i + 1 else
|
||||
pathlib.Path(__file__).with_name("pointer_golden.json"))
|
||||
sys.exit(0)
|
||||
if "--from-current" in sys.argv:
|
||||
i = sys.argv.index("--from-current")
|
||||
if len(sys.argv) <= i + 1:
|
||||
sys.exit("--from-current needs the file to write")
|
||||
sys.exit(0 if from_current(sys.argv[i + 1]) else 1)
|
||||
if "--from-old-client" not in sys.argv:
|
||||
sys.exit("nothing to do: pass --from-current OUT.json (the current server's run, to a file), --revise-mouse-click or "
|
||||
"--revise-standstill (explicit_pointer, in place), or --from-old-client (the old tree only)")
|
||||
if not hasattr(_cursor, "_approach"):
|
||||
sys.exit("refusing: `_cursor._approach` and the client-side wrappers of the walk do not exist in this tree, so none of "
|
||||
"the sessions %s can be made from the old client here. They are the golden because commit 5d9ad70 made them; "
|
||||
"run this against that tree, or use --from-current to check the current server against the file."
|
||||
% ", ".join(sorted(SCENARIOS)))
|
||||
out = {name: {"spec": spec, "engine_events": scenario(spec)}
|
||||
for name, spec in SCENARIOS.items()}
|
||||
json.dump(out, sys.stdout, indent=1)
|
||||
@@ -0,0 +1,97 @@
|
||||
{
|
||||
"version": 1,
|
||||
"entries": [
|
||||
{"file": "_doh_servers.py", "scope": "<module>.DOH_PORT", "rule": "port", "nth": 1, "kind": "virtual-port", "reason": "A port number that nothing binds: the gateway of the test answers for the name or address by itself, so no worker can collide on it."},
|
||||
{"file": "_doh_servers.py", "scope": "DohGateway._handle", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "_doh_servers.py", "scope": "FakeDoh._serve_h1", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "_doh_servers.py", "scope": "relay", "rule": "timeout", "nth": 1, "kind": "instrument", "reason": "Teardown of the test's own server: join(timeout=N) returns as soon as the thread ends, and a thread that is late is a daemon the process leaves behind; no verdict reads whether it ended in time, so a slow machine can never make it red."},
|
||||
{"file": "_fission_frames.py", "scope": "spin_trial", "rule": "js-timer", "nth": 1, "kind": "instrument", "reason": "The 10 ms ticker of the observer frame is the measuring tool of the proof: what is judged is how many of its ticks ran inside the spin of the other frame, and the spins go on until one shows ticks (30 s), so a starved spin is a trial that proves nothing and never a red."},
|
||||
{"file": "_fission_frames.py", "scope": "spin_trial", "rule": "js-timer", "nth": 2, "kind": "stimulus", "reason": "The spin of the other frame starts 50 ms after the call that asks for it has returned, so that call does not block on its own spin; the test then waits for the frame to say the spin is over, with a deadline of 30 s, and no verdict reads when the timer fired."},
|
||||
{"file": "_h3_server.py", "scope": "H3Server.__init__.run", "rule": "sleep", "nth": 1, "kind": "instrument", "reason": "The pause lets the loop of the test's own HTTP/3 server end at its close; it is teardown of the instrument and no verdict is based on it."},
|
||||
{"file": "_leaks.py", "scope": "Watcher.stop", "rule": "timeout", "nth": 1, "kind": "instrument", "reason": "Teardown of the test's own server: join(timeout=N) returns as soon as the thread ends, and a thread that is late is a daemon the process leaves behind; no verdict reads whether it ended in time, so a slow machine can never make it red."},
|
||||
{"file": "_page_work.py", "scope": "<module>.CASES", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "_page_work.py", "scope": "<module>.CASES", "rule": "js-timer", "nth": 2, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "_realness_support.py", "scope": "<module>.PAGE_JS", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "_socks_servers.py", "scope": "<module>.STUN_PORT", "rule": "port", "nth": 1, "kind": "virtual-port", "reason": "A port number that nothing binds: the gateway of the test answers for the name or address by itself, so no worker can collide on it."},
|
||||
{"file": "_socks_servers.py", "scope": "FakeStun.close", "rule": "timeout", "nth": 1, "kind": "instrument", "reason": "Teardown of the test's own server: join(timeout=N) returns as soon as the thread ends, and a thread that is late is a daemon the process leaves behind; no verdict reads whether it ended in time, so a slow machine can never make it red."},
|
||||
{"file": "_socks_servers.py", "scope": "Gateway._connect", "rule": "timeout", "nth": 1, "kind": "instrument", "reason": "Teardown of the test's own server: join(timeout=N) returns as soon as the thread ends, and a thread that is late is a daemon the process leaves behind; no verdict reads whether it ended in time, so a slow machine can never make it red."},
|
||||
{"file": "_socks_servers.py", "scope": "Gateway._send", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "The round trip of a gateway that is far away (rtt_ms) is the input of the tests that use it: they judge what the gateway recorded (which association carried a datagram, in which order, how many rounds the road cost), never how long a step took, and every wait that leads up to a verdict has a deadline of 30 s."},
|
||||
{"file": "_turn_chain.py", "scope": "<module>.PAGE_HTML", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The 2 s tick is the model of a leak test's page and decides nothing: a srflx that comes after it is still read and posted, the status of the page is final (DONE or REFUSED) in the same step that says `posted`, and the verdict is read from the stamps of the gateway, the DoH and the TURN server, never from when the tick fired."},
|
||||
{"file": "_turn_chain.py", "scope": "<module>.TURN_PORT", "rule": "port", "nth": 1, "kind": "virtual-port", "reason": "A port number that nothing binds: the gateway of the test answers for the name or address by itself, so no worker can collide on it."},
|
||||
{"file": "test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "scope": "<module>.READ", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s only ends a read of the position that never answers: the answer is a position or an error as soon as the engine gives one, and no verdict reads when the timer fired."},
|
||||
{"file": "test_a_page_cannot_probe_the_juggler_e2e.py", "scope": "<module>._CHANNELS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The 30 s of each channel are the deadline of its wait (`no answer` is a channel that stays silent). Every channel of a URL is asked at once and a name that is nowhere answers all of them, so on a healthy run no silence is waited for, and a stall of the machine cannot make one URL answer and the other not."},
|
||||
{"file": "test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "scope": "<module>._GATHER_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s is the deadline of the wait for the end of the ICE gathering: the wait ends when the page says `complete`, a gathering that never completes returns what it has and fails the assertions on the candidates, and no verdict reads when the timer fired."},
|
||||
{"file": "test_a_page_that_moves_on_e2e.py", "scope": "_replace_after_load", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The page's own timer moves the page 0, 50 or 300 ms after the load, and the reads made while it moves accept both states (the page before the move or the page it moved to) and never an engine error; nothing reads when the timer fired, and the waits that lead up to the reads have a deadline of 30 s."},
|
||||
{"file": "test_a_page_that_moves_on_e2e.py", "scope": "test_reads_wait_as_playwright_s_do", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The page's own timer adds the element 500 ms after the call; the read waits for it with a deadline of 30 s, and the verdict is the text read, never when the timer fired."},
|
||||
{"file": "test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "scope": "test_a_destination_that_commits_nothing_gives_no_popup_event.body", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "A fixed observation window for something that must NOT happen: a slow machine can only make this check weaker (a false green), it cannot make it red."},
|
||||
{"file": "test_a_popup_of_a_link_reaches_the_client_e2e.py", "scope": "_router.route", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py", "scope": "<module>._PROBE_JS", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "scope": "<module>.TURN_PORT", "rule": "port", "nth": 1, "kind": "virtual-port", "reason": "A port number that nothing binds: the gateway of the test answers for the name or address by itself, so no worker can collide on it."},
|
||||
{"file": "test_caller_world_handles_e2e.py", "scope": "test_a_node_that_appears_later_ends_the_wait", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_caller_world_handles_e2e.py", "scope": "test_a_wait_for_function_object_handle_reads_in_the_page_world", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_declared_host_network_e2e.py", "scope": "<module>._GATHER_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s is the deadline of the wait for the end of the ICE gathering: the wait ends when the page says `complete`, a gathering that never completes returns what it has and fails the assertions on the candidates, and no verdict reads when the timer fired."},
|
||||
{"file": "test_declared_host_network_e2e.py", "scope": "<module>._LOOPBACK_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The 5 ms step of the page's own wait for the data channel to open and echo, which ends at 30 s; the same loop keeps the longest time it did not run, so the time the connection took is judged only when the page itself was not stopped by the machine (`_e2e_verdicts.opened_at_the_retry_problem`)."},
|
||||
{"file": "test_detectors_e2e.py", "scope": "test_enumerate_devices_resolves_promptly", "rule": "bound", "nth": 1, "kind": "hang-detector", "reason": "The limit is the larger of 30 s and 2000 times a load reference (microtasks) measured in the same page just before, and never reaches the 120 s at which the call is held to be hung, so it ends a call that never comes and is relative to the machine's own load."},
|
||||
{"file": "test_detectors_e2e.py", "scope": "test_enumerate_devices_resolves_promptly", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_doh_through_the_proxy_e2e.py", "scope": "test_no_helper_process_starts", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "A fixed observation window for something that must NOT happen: a slow machine can only make this check weaker (a false green), it cannot make it red."},
|
||||
{"file": "test_doh_through_the_proxy_e2e.py", "scope": "test_no_helper_process_starts", "rule": "sleep", "nth": 2, "kind": "negative-window", "reason": "A fixed observation window for something that must NOT happen: a slow machine can only make this check weaker (a false green), it cannot make it red."},
|
||||
{"file": "test_fingerprint_consistency.py", "scope": "_worker_navigator_dict", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s only ends a worker that never answers: the answer is the worker's message as soon as it runs, and no verdict reads when the timer fired."},
|
||||
{"file": "test_fission_frames_dialogs_downloads_popups_e2e.py", "scope": "test_a_dialog_of_a_frame_reaches_the_page_and_the_answer_goes_back", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_fission_frames_dialogs_downloads_popups_e2e.py", "scope": "test_two_dialogs_one_after_the_other_from_different_frames", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_fission_frames_dialogs_downloads_popups_e2e.py", "scope": "test_two_dialogs_one_after_the_other_from_different_frames", "rule": "js-timer", "nth": 2, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_fission_frames_history_and_processes_e2e.py", "scope": "traverse", "rule": "timeout", "nth": 1, "kind": "negative-window", "reason": "The call is EXPECTED to give up with a TimeoutError when the entry belongs to a frame (no navigation of the main frame follows, as in stock Firefox), so 3 s is the window in which that navigation must NOT come; a slow machine can only make it a weaker check, and the tests judge where the page and its frame are after."},
|
||||
{"file": "test_fission_frames_route_and_bindings_e2e.py", "scope": "test_networkidle_waits_for_the_late_requests_of_a_frame_of_another_site", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_fission_frames_tree_input_and_pixels_e2e.py", "scope": "<module>.LATE", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The three timers of the test's own page add, hide and show elements 300 ms, 700 ms and 1 s after the load; every wait that reads them has a deadline of 30 s and takes the element whether it was there already or not, so no verdict reads when a timer fired."},
|
||||
{"file": "test_fission_frames_tree_input_and_pixels_e2e.py", "scope": "<module>.LATE", "rule": "js-timer", "nth": 2, "kind": "stimulus", "reason": "The three timers of the test's own page add, hide and show elements 300 ms, 700 ms and 1 s after the load; every wait that reads them has a deadline of 30 s and takes the element whether it was there already or not, so no verdict reads when a timer fired."},
|
||||
{"file": "test_fission_frames_tree_input_and_pixels_e2e.py", "scope": "<module>.LATE", "rule": "js-timer", "nth": 3, "kind": "stimulus", "reason": "The three timers of the test's own page add, hide and show elements 300 ms, 700 ms and 1 s after the load; every wait that reads them has a deadline of 30 s and takes the element whether it was there already or not, so no verdict reads when a timer fired."},
|
||||
{"file": "test_fission_frames_workers_storage_and_special_frames_e2e.py", "scope": "<module>.SERVICE_WORKER_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s only ends a service worker that never registers or answers; the outcome is read as soon as the worker says it, and no verdict reads when the timer fired."},
|
||||
{"file": "test_fission_frames_workers_storage_and_special_frames_e2e.py", "scope": "<module>.SHARED_WORKER_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s only ends a shared worker that never answers; the outcome is read as soon as the worker says it, and no verdict reads when the timer fired."},
|
||||
{"file": "test_fission_frames_workers_storage_and_special_frames_e2e.py", "scope": "<module>.WORKER_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s only ends a dedicated worker that never answers; the identity is read as soon as the worker posts it, and no verdict reads when the timer fired."},
|
||||
{"file": "test_fission_identity_parity_e2e.py", "scope": "<module>.SPIN_PROBE_JS", "rule": "js-timer", "nth": 1, "kind": "instrument", "reason": "The 10 ms ticker of the top document is the measuring tool of the proof: strategy 1 needs ticks inside the spin of the iframe and the spins go on until one shows them (30 s); strategy 0 asserts there is none in any spin, which no machine can fake because one thread cannot tick while it spins."},
|
||||
{"file": "test_fission_identity_parity_e2e.py", "scope": "<module>.SPIN_PROBE_JS", "rule": "js-timer", "nth": 2, "kind": "hang-detector", "reason": "The timer of 30 s ends a spin the iframe never reports (an empty trial that proves nothing, and the spins go on until one shows ticks or 30 s have passed); the spin ends the trial as soon as the iframe says so, with no further timer."},
|
||||
{"file": "test_goto_and_every_way_it_is_stopped_e2e.py", "scope": "_hold", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "The server keeps the answer of the goto that must LAND for 1.5 s on purpose, so the goto is in flight while the old page acts; the verdict reads only a lower bound on how long the goto waited (a slow machine cannot make that red) and where the page ended."},
|
||||
{"file": "test_goto_and_every_way_it_is_stopped_e2e.py", "scope": "_when_the_goto_arrives", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The 50 ms poll only asks the server whether the request of the goto has arrived. For the cases that must be stopped the server keeps the goto's page until the test has seen the goto return, so a late poll lengthens the wait and cannot let the goto land (it ends at its timeout of 30 s); for the cases that must land, what the poll does changes where the goto ends and the assertions accept both."},
|
||||
{"file": "test_http3_through_the_proxy_e2e.py", "scope": "_visits", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "The pause spaces the visits of a page the way the retail method does (visit, pause, visit); it is the minimum between two events the test generates, the UDP-free roads wait for the browser's own QUIC connection as a condition (30 s) before it, and the protocols the visits read do not depend on a longer pause."},
|
||||
{"file": "test_injected_node_surface.py", "scope": "<module>.PAGE", "rule": "js-timer", "nth": 1, "kind": "instrument", "reason": "The watcher of the page (an interval of 50 ms) is the measuring tool: it counts its own looks in window.__looks, and each test waits for the count to move past the call it checks, so no verdict is read before the watcher has looked at the page as the call left it."},
|
||||
{"file": "test_input_is_born_before_the_page_sees_it_e2e.py", "scope": "test_every_key_and_move_is_born_before_its_handler_runs", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "The pause between two events the test generates is part of the stimulus; the assertion reads the events after every call has returned, not the time between them."},
|
||||
{"file": "test_juggler_injected.py", "scope": "test_OUR_CLIENT_DOES_NOT_CROSS_into_the_page_realm.read", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "A fixed observation window for something that must NOT happen: a slow machine can only make this check weaker (a false green), it cannot make it red."},
|
||||
{"file": "test_juggler_transport.py", "scope": "test_the_public_API_WAITS_for_an_element_that_arrives_late", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The timer is started by the test AFTER it has seen the element absent, and the wait for the element has a deadline of 30 s: nothing arrives before the check, and the verdict is the element's text, never when the timer fired."},
|
||||
{"file": "test_navigation_across_processes_e2e.py", "scope": "test_a_goto_to_another_site_stopped_by_the_page_it_leaves_raises_aborted.scenario", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The 50 ms poll only asks the server whether the request of the goto has arrived, and the server holds that request until the test has seen the goto return, so a late poll lengthens the wait and cannot let the goto land; the goto ends at its timeout of 30 s and the verdict is the error it raised and where the page is."},
|
||||
{"file": "test_navigation_across_processes_e2e.py", "scope": "test_an_iframe_removed_while_it_loads_is_aborted_then_gone.scenario", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The page removes the iframe 1 s after inserting it while the server holds the frame's document for 3 s; the test waits (30 s) for the frame to have been attached and detached and for the page to be the only frame, which is the same end whether the removal came before or after the document loaded, so no verdict reads when the timer fired."},
|
||||
{"file": "test_networkidle_through_a_served_browser_with_routes_e2e.py", "scope": "_router.route", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "test_networkidle_through_a_served_browser_with_routes_e2e.py", "scope": "test_a_plain_route_handler_is_not_poisoned_by_a_request_the_page_cancelled.plain", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "test_networkidle_through_a_served_browser_with_routes_e2e.py", "scope": "test_networkidle_arrives_when_the_client_answers_all_requests_concurrently_and_slowly.run.route", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "test_nothing_leaves_but_the_proxy_e2e.py", "scope": "test_a_kind_of_page_work_leaves_only_through_the_proxy_of_its_context", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "A fixed observation window for something that must NOT happen: a slow machine can only make this check weaker (a false green), it cannot make it red."},
|
||||
{"file": "test_nothing_leaves_but_the_proxy_e2e.py", "scope": "test_a_kind_of_page_work_leaves_only_through_the_proxy_of_its_context", "rule": "sleep", "nth": 2, "kind": "negative-window", "reason": "A fixed observation window for something that must NOT happen: a slow machine can only make this check weaker (a false green), it cannot make it red."},
|
||||
{"file": "test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py", "scope": "<module>._WINDOW_ICE_JS", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_popup_pages.py", "scope": "test_a_popup_the_site_closes_is_closed", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "The window of 300 ms is left only for a SECOND close event, after the test has waited (30 s) for the popup to be closed; a slow machine only makes the window weaker, never red."},
|
||||
{"file": "test_popup_pages.py", "scope": "test_popup_document_reaches_the_context", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "The window of 500 ms is left only for a DUPLICATE of the document's request or response, after the test has waited (30 s) for the first of each to be heard; a slow machine only makes the window weaker, never red."},
|
||||
{"file": "test_popup_pages.py", "scope": "test_window_open_with_a_size_keeps_that_size", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "The pause of 1 s is the window in which a LATE resize of the popup (the defect) would show: the size read before it and after it must be the same, and both are read after the popup's load was waited for with a deadline of 30 s; a slow machine only makes the window weaker in effect, it cannot change either size."},
|
||||
{"file": "test_popups_reach_the_client_e2e.py", "scope": "test_a_popup_reaches_the_client", "rule": "timeout", "nth": 1, "kind": "hang-detector", "reason": "The 10 s is the promise under test: a popup's page event reaches the client within 10 s (asserted below with arrived < 10); the old defect held it for 20 s behind a page that never said ready, so a longer wait would hide it."},
|
||||
{"file": "test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "scope": "_remote_types", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "The window of 10 s (only in the case that asks for the preload off) in which a privileged-about process that must NOT be born would show, left after the log of the engine already holds lines (a condition waited for with a deadline of 30 s); a slow machine only makes the window weaker, never red."},
|
||||
{"file": "test_requestless_navigation.py", "scope": "test_navigation_wait", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The page's own timer starts the navigation 100 ms after the call, and wait_for_url waits for the destination with a deadline of 30 s; the verdict is where the page is, never when the timer fired."},
|
||||
{"file": "test_screencast_stop_e2e.py", "scope": "test_every_screencast_stop_returns_and_the_browser_still_answers", "rule": "bound", "nth": 1, "kind": "hang-detector", "reason": "The 30 s budget of one start or stop of a screencast only ends the wait on a browser that is wedged (a call that answers takes well under a tenth of a second, measured over hundreds); it judges a hang, never a speed."},
|
||||
{"file": "test_screencast_stop_e2e.py", "scope": "test_every_screencast_stop_returns_and_the_browser_still_answers.drive", "rule": "sleep", "nth": 1, "kind": "stimulus", "reason": "Slowness on purpose: this test server, relay or client answers late as the input of the test, and the product waits for it under a deadline; nothing here judges the machine."},
|
||||
{"file": "test_scroll_into_view.py", "scope": "test_it_scrolls_ONLY_IF_NEEDED_and_then_centres", "rule": "timeout", "nth": 1, "kind": "hang-detector", "reason": "The 15 s is the detector of the defect under test: scroll_into_view_if_needed answers at once, the regression it covers waited 30 s and then passed, so the deadline has to stay under that wait; 15 s is half of it and far beyond a healthy run."},
|
||||
{"file": "test_scroll_into_view.py", "scope": "test_it_scrolls_ONLY_IF_NEEDED_and_then_centres", "rule": "timeout", "nth": 2, "kind": "hang-detector", "reason": "The 15 s is the detector of the defect under test: scroll_into_view_if_needed answers at once, the regression it covers waited 30 s and then passed, so the deadline has to stay under that wait; 15 s is half of it and far beyond a healthy run."},
|
||||
{"file": "test_scroll_into_view.py", "scope": "test_scroll_into_view_puts_the_element_in_the_viewport", "rule": "timeout", "nth": 1, "kind": "hang-detector", "reason": "The 15 s is the detector of the defect under test: scroll_into_view_if_needed answers at once, the regression it covers waited 30 s and then passed, so the deadline has to stay under that wait; 15 s is half of it and far beyond a healthy run."},
|
||||
{"file": "test_software_compositing_is_declared_e2e.py", "scope": "<module>.SCENE", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s is the limit of the scene's wait for the end of the ICE gathering of a PeerConnection with no servers; the scene resolves as soon as the gathering completes, and the test asserts the states reached (`complete` in every round), which no clock decides."},
|
||||
{"file": "test_software_compositing_is_declared_e2e.py", "scope": "test_the_gpu_process_is_idle_on_a_fixed_scene", "rule": "bound", "nth": 1, "kind": "cpu-budget", "reason": "The bound is on the CPU seconds of the GPU process (user + kernel, over ten scenes), not on elapsed time: 1.5 s is 4.7 times what the declared engine used on the Windows runner (0.32 s, run 43652292533) and 0.55 times the least the undeclared one used (2.7 s), so a runner that stops or is slow stretches the clock and not the CPU."},
|
||||
{"file": "test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "scope": "<module>._PC_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The 5 ms step of the page's wait for the server-reflexive candidate, which ends at 30 s; the verdict compares which association carried the first datagram with the moment the PeerConnection was born (an order of events the gateway recorded), not how long the candidate took."},
|
||||
{"file": "test_the_callers_code_runs_once_e2e.py", "scope": "test_a_read_declared_free_of_effects_answers_from_the_page_that_replaced_it", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_the_callers_code_runs_once_e2e.py", "scope": "test_eval_on_selector_all_interrupted_by_its_navigation_runs_once", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_the_callers_code_runs_once_e2e.py", "scope": "test_evaluate_interrupted_by_its_navigation_runs_once", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_the_callers_code_runs_once_e2e.py", "scope": "test_wait_for_function_goes_on_through_a_navigation", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The page's own timer navigates 300 ms after the call, and wait_for_function waits for the new document with a deadline of 30 s; the verdict is the title of the page, never when the timer fired."},
|
||||
{"file": "test_the_favicon_stays_out_of_sight_e2e.py", "scope": "test_the_favicon_goes_to_the_site_and_nothing_of_it_to_the_client", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "The window of 500 ms is left only for an event about the favicon that must NOT reach the client, after the test has waited (30 s) for the site to have written the answer; a slow machine only makes the window weaker, never red."},
|
||||
{"file": "test_the_hosts_file_of_the_host_is_never_read_e2e.py", "scope": "test_the_hosts_file_of_the_host_is_never_read", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "A fixed observation window for something that must NOT happen: a slow machine can only make this check weaker (a false green), it cannot make it red."},
|
||||
{"file": "test_the_socket_process_is_sandboxed_e2e.py", "scope": "test_the_socket_process_and_a_tab_process_have_a_seccomp_filter", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."},
|
||||
{"file": "test_turn_over_tcp_is_tried_for_real_e2e.py", "scope": "<module>._JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer is the deadline of the wait for the end of the gathering (30 s, DEADLINE_MS), which ends after the TURN error; the verdict is the order of the events the page records, never when the timer fired."},
|
||||
{"file": "test_voices_e2e.py", "scope": "<module>.READ", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s only ends a read of the voices that is never told the list changed (`voiceschanged`); the list is read as soon as the engine has it, and no verdict reads when the timer fired."},
|
||||
{"file": "test_wait_for_timeout.py", "scope": "test_the_wait_takes_the_time_it_was_asked_for", "rule": "sleep", "nth": 1, "kind": "instrument", "reason": "This is the test of wait_for_timeout itself: the pause is the behaviour under test and the assertion is made on the pause it asked for."},
|
||||
{"file": "test_webrtc_realness.py", "scope": "<module>._PROBE_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s is the deadline of the wait for the end of the gathering (what the page reads is the whole of it); the wait ends when the page says `complete`, and no verdict depends on when the timer fired."},
|
||||
{"file": "test_webrtc_realness.py", "scope": "<module>._RELAY_PROBE_JS", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "A timer of the test's own page is the stimulus (the thing appears later); the product waits for it with a deadline and the verdict does not read when it fired."}
|
||||
],
|
||||
"debt": [
|
||||
{"file": "_udp_line.py", "scope": "judge_visits", "rule": "bound", "nth": 1, "class": "B", "reason": "An absolute upper bound on a duration is a verdict on the machine: compare with a control measured in the same run, or assert the order of the events."}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"description": "The pages the real-sites round visits with one browser at a time (scripts/run_real_sites.py), judged by scripts/judge_real_sites.py: the published wrapper against stock Firefox driven by stock Playwright, on the same runner. Only URL, marker and class are kept here.",
|
||||
"fields": {
|
||||
"classes": "The kinds of page a site may be.",
|
||||
"sites": "The list, at most 20 sites and at most 4 of the class protetta. The judge asks for information from half of them, rounded up (8 of 15): there is no minimum written in this file, and a file that has one is not a list.",
|
||||
"id": "Per site. A short unique name made of lowercase letters, digits and hyphens. It keys the cells of both browsers.",
|
||||
"url": "Per site. The page to open, https, without a login. The document is the page the status is read from.",
|
||||
"marker": "Per site. A CSS selector that matches something only when the real page arrived (not an error page, not a block page, not a consent wall).",
|
||||
"class": "Per site. One of the classes: calma (a quiet page), giornale (a newspaper full of advertising), negozio (a shop), applicazione (a single-page application or a search), protetta (a page behind protection)."
|
||||
},
|
||||
"classes": ["calma", "giornale", "negozio", "applicazione", "protetta"],
|
||||
"sites": [
|
||||
{"id": "developer-mozilla", "url": "https://developer.mozilla.org/en-US/", "marker": "#content", "class": "calma"},
|
||||
{"id": "python", "url": "https://www.python.org/", "marker": "[role=\"main\"]", "class": "calma"},
|
||||
{"id": "it-wikipedia", "url": "https://it.wikipedia.org/wiki/Pagina_principale", "marker": "#mw-content-text", "class": "calma"},
|
||||
{"id": "en-wikipedia", "url": "https://en.wikipedia.org/wiki/Italy", "marker": "#mw-content-text", "class": "calma"},
|
||||
{"id": "lemonde", "url": "https://www.lemonde.fr/", "marker": "main", "class": "giornale"},
|
||||
{"id": "lefigaro", "url": "https://www.lefigaro.fr/", "marker": "main", "class": "giornale"},
|
||||
{"id": "spiegel", "url": "https://www.spiegel.de/", "marker": "main", "class": "giornale"},
|
||||
{"id": "ikea", "url": "https://www.ikea.com/it/it/", "marker": "main", "class": "negozio"},
|
||||
{"id": "otto", "url": "https://www.otto.de/", "marker": "#avContent", "class": "negozio"},
|
||||
{"id": "apple", "url": "https://www.apple.com/it/store", "marker": "[role=\"main\"]", "class": "negozio"},
|
||||
{"id": "mediamarkt", "url": "https://www.mediamarkt.de/", "marker": "main", "class": "negozio"},
|
||||
{"id": "duckduckgo", "url": "https://duckduckgo.com/", "marker": "#searchbox_homepage", "class": "applicazione"},
|
||||
{"id": "bing", "url": "https://www.bing.com/search?q=wikipedia", "marker": "#b_results", "class": "applicazione"},
|
||||
{"id": "openstreetmap", "url": "https://www.openstreetmap.org/", "marker": "#map", "class": "applicazione"},
|
||||
{"id": "walmart", "url": "https://www.walmart.com/", "marker": "main", "class": "protetta"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"""A test that needs a stock Firefox bundled with Playwright on the machine that runs it.
|
||||
|
||||
``test_real_stock_firefox_via_binary_path_is_refused`` looks for ``ms-playwright/firefox-*`` in the user's cache; a clean CI runner has none, so the test
|
||||
skips, and a skip is red in the whole unit suite of the candidate. It lives in its own file, out of ``tests/test_seal_binary_path.py`` (whose other
|
||||
cases build their own tree and run everywhere), and is a file of the environment of ``tests/test_the_unit_suite_is_accounted_for.py``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.seal import EngineMismatch, read_engine_identity
|
||||
from invisible_playwright import _engine
|
||||
|
||||
from test_seal_binary_path import ENTRY_REL, active # noqa: F401 (``active`` is a fixture)
|
||||
|
||||
|
||||
def test_real_stock_firefox_via_binary_path_is_refused(active): # noqa: F811 (the fixture imported above)
|
||||
"""The cell as it exists on this machine, not a synthetic stand-in. Read
|
||||
only; skips cleanly when no bundled Playwright Firefox is present."""
|
||||
local = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData/Local")
|
||||
roots = [Path(local) / "ms-playwright", Path.home() / ".cache" / "ms-playwright"]
|
||||
entries = [d / "firefox" / ENTRY_REL for root in roots if root.is_dir()
|
||||
for d in sorted(root.glob("firefox-*"))]
|
||||
entries = [e for e in entries if e.exists()]
|
||||
if not entries:
|
||||
pytest.skip("no bundled stock Firefox on this machine")
|
||||
for entry in entries:
|
||||
ident = read_engine_identity(entry)
|
||||
with pytest.raises(EngineMismatch):
|
||||
_engine.resolve_executable(entry)
|
||||
assert ident.marked_entries == 0, f"{entry} unexpectedly carries our marker"
|
||||
@@ -8,8 +8,8 @@ BrowserContext now waits a few seconds for the processes of its container once i
|
||||
ones that stay.
|
||||
|
||||
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
|
||||
(at least one: the page's, or the count would prove nothing), and once `close` has answered it waits, with a deadline of 30 s
|
||||
that only a process that never goes reaches, 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 of the page's site are counted, asked for by name (tests/_processes.py): the browser is
|
||||
launched with `fission.processSiteNames`, which names a content process by the site it hosts (the page is served
|
||||
from `http://127.0.0.1:<port>`; a site never includes the port). The browser starts processes of its own, and
|
||||
@@ -26,7 +26,6 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -35,6 +34,7 @@ from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
from _processes import NAMED_BY_SITE, site_processes_below # noqa: E402
|
||||
from _servers import LocalServer # noqa: E402
|
||||
from _waits import awatch # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
@@ -89,6 +89,13 @@ class _Client:
|
||||
await self.call("", "initialize", {"sdkLanguage": "python"})
|
||||
self.browser = [g for g, o in self.objects.items() if o["type"] == "Browser"][0]
|
||||
|
||||
async def evaluate(self, frame, expression):
|
||||
"""The value of a JavaScript expression in the frame (a promise is awaited by the protocol)."""
|
||||
result = await self.call(frame, "evaluateExpression", {
|
||||
"expression": expression, "isFunction": False, "arg": {"value": {"v": "undefined"}, "handles": []}})
|
||||
value = result["value"]
|
||||
return value["b"] if "b" in value else value # the protocol's own tag of a boolean
|
||||
|
||||
async def new_page(self):
|
||||
context = (await self.call(self.browser, "newContext", {}))["context"]["guid"]
|
||||
page = (await self.call(context, "newPage", {}))["page"]["guid"]
|
||||
@@ -96,6 +103,13 @@ class _Client:
|
||||
return context, frame
|
||||
|
||||
|
||||
#: A deadline no healthy run comes near: every wait below ends on its condition, not on this.
|
||||
DEADLINE_S = 30
|
||||
|
||||
#: The page asked for a service worker and the browser has taken it (the install handler is the endless loop).
|
||||
REGISTERED = ("navigator.serviceWorker.getRegistration().then(r => !!r && !!(r.installing || r.waiting || r.active))")
|
||||
|
||||
|
||||
def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(firefox_binary, engine_at_least):
|
||||
engine_at_least(ENGINE_WITH_THE_FIX)
|
||||
from invisible_playwright import launch_server
|
||||
@@ -116,13 +130,24 @@ def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(f
|
||||
for i in range(5):
|
||||
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
|
||||
opened.append(len(sites()))
|
||||
# the worker is registered (asked of the page, not slept for), so its install loop is running
|
||||
state = {"registered": False}
|
||||
|
||||
async def ask():
|
||||
state["registered"] = await client.evaluate(frame, REGISTERED)
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
known = await awatch(lambda: state["registered"], bool, DEADLINE_S, ask)
|
||||
assert known.ok, "the service worker of the page was never registered (round %d): %s" % (i, known.render())
|
||||
|
||||
async def look():
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
seen = await awatch(lambda: len(sites()), lambda n: n > 0, DEADLINE_S, look)
|
||||
opened.append(seen.history[-1][1])
|
||||
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()))
|
||||
gone = await awatch(lambda: len(sites()), lambda n: n == 0, DEADLINE_S, lambda: asyncio.sleep(0.25))
|
||||
left.append(gone.history[-1][1])
|
||||
return opened, left
|
||||
|
||||
try:
|
||||
|
||||
@@ -14,6 +14,7 @@ from http.server import BaseHTTPRequestHandler
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
@@ -93,7 +94,20 @@ def test_the_client_hears_the_document_and_the_fetches_and_no_preflight(firefox_
|
||||
page = context.new_page()
|
||||
page.on("request", lambda r: heard.append((r.method, r.url.rsplit("/", 1)[-1] or "page")))
|
||||
page.goto(two_origins, wait_until="load")
|
||||
page.wait_for_timeout(2000) # the events of a sync client are delivered while it calls the browser
|
||||
def pump():
|
||||
page.wait_for_timeout(100) # the events of a sync client are delivered while it calls the browser
|
||||
|
||||
# The fetches are the page's own; each one's preflight reaches the server BEFORE its GET, so once the server
|
||||
# has seen both GETs every OPTIONS the browser would make has been made.
|
||||
assert wait_until(lambda: sum(1 for m, _ in list(_Api.hits) if m == "GET") >= 2, 30, pump), (
|
||||
"the page's two fetches never reached the server: %r" % _Api.hits)
|
||||
# An absence is asserted after a sentinel: a request made only now, after everything above. The client hears
|
||||
# its events in the order they happened, so when it hears the sentinel it has heard every event before it, and
|
||||
# a preflight that was going to be reported is in `heard` by then (no clock decides what "nothing came" means).
|
||||
page.evaluate("() => fetch('/sentinel').then((r) => r.status)") # same origin as the page: no preflight
|
||||
assert wait_until(lambda: any(name == "sentinel" for _m, name in heard), 30, pump), (
|
||||
"the client never heard the sentinel request; it heard %r" % heard)
|
||||
heard[:] = [(m, name) for m, name in heard if name != "sentinel"]
|
||||
assert ("OPTIONS", "/one") in _Api.hits or ("OPTIONS", "/two") in _Api.hits, "the browser made no preflight: %r" % _Api.hits
|
||||
methods = sorted(m for m, _ in heard)
|
||||
assert methods == ["GET", "GET", "GET"], "the client heard %r (the server saw %r)" % (heard, _Api.hits)
|
||||
@@ -20,7 +20,6 @@ from __future__ import annotations
|
||||
import dataclasses
|
||||
import http.server
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -291,8 +290,9 @@ STORE_PAGE = b"""<!doctype html><html><body>
|
||||
<input id="store">
|
||||
<script>
|
||||
window.__events = [];
|
||||
// e.timeStamp: when the browser made the event, not when this handler ran (a loaded machine runs two handlers together)
|
||||
for (const k of ['focus', 'keydown'])
|
||||
document.addEventListener(k, e => __events.push([k, performance.now()]), true);
|
||||
document.addEventListener(k, e => __events.push([k, e.timeStamp]), true);
|
||||
const answer = +(new URLSearchParams(location.search).get('answer') || 600);
|
||||
store.addEventListener('focus', () => setTimeout(() => { store.value = ''; }, answer));
|
||||
</script></body></html>"""
|
||||
@@ -343,9 +343,7 @@ def test_a_store_that_answers_the_focus_does_not_eat_the_text(firefox_binary, st
|
||||
with InvisiblePlaywright(seed=seed, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(store_url)
|
||||
started = time.monotonic()
|
||||
getattr(page.locator("#store"), how)(TEXT)
|
||||
took = time.monotonic() - started
|
||||
value = page.input_value("#store")
|
||||
events = page.evaluate("__events")
|
||||
assert value == TEXT, "the field holds %r after %s" % (value, how)
|
||||
@@ -354,7 +352,11 @@ def test_a_store_that_answers_the_focus_does_not_eat_the_text(firefox_binary, st
|
||||
assert (first - focus) / 1000 >= ANSWER_MS / 1000, (
|
||||
"the first key came %.0f ms after the focus, before the store's "
|
||||
"answer at %d ms" % (first - focus, ANSWER_MS))
|
||||
# The pause is a pause, not a stall: one hesitation (restarted once, by
|
||||
# the store's write) on top of the typing itself.
|
||||
assert took < 2 * pause + ANSWER_MS / 1000 + 0.4 * len(TEXT), (
|
||||
"%s took %.1f s" % (how, took))
|
||||
# The pause is a pause, not a stall: one hesitation (restarted once, by the store's write) on top of the store's
|
||||
# answer. Judged on the browser's own stamps of the focus and of the first key, so the speed of the machine that
|
||||
# drives the browser (which made the duration of the whole call, typing included, 11.3 s against a bound of
|
||||
# 10.3 s on a loaded Windows runner) is not in the verdict; a pause that stalls (three hesitations, or the pause
|
||||
# taken again at every key) is still past this bound. How fast the text is typed is the rhythm tests' business.
|
||||
assert (first - focus) / 1000 <= ANSWER_MS / 1000 + 2 * pause, (
|
||||
"%s: the first key came %.0f ms after the focus; the store answers at %d ms and one hesitation is %.0f ms, "
|
||||
"restarted at most once" % (how, first - focus, ANSWER_MS, pause * 1000))
|
||||
@@ -0,0 +1,71 @@
|
||||
"""A goto to a response that carries no document (204 No Content, 205 Reset Content) ENDS, with the error the engine says.
|
||||
|
||||
Firefox does not replace the page for such a response: the load of the new document stops where its request ends, and the
|
||||
page stays where it was. In the network of the parent the request does not fail (it is answered), so the end of that
|
||||
navigation is said by the process that held the frame, and nothing else says it. A goto whose end nobody says hangs until
|
||||
its own timeout: that is the defect this file is red on, and the timeout here (30 s) is only its detector.
|
||||
|
||||
Known-bad input: an engine whose content process stays silent on the abort of an http load (the frame tree that leaves
|
||||
every http end to the parent) -> both goto here raise a TimeoutError instead of the engine's error.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
def _serve():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/no-content"):
|
||||
self.send_response(204)
|
||||
self.end_headers()
|
||||
return
|
||||
if self.path.startswith("/reset-content"):
|
||||
self.send_response(205)
|
||||
self.send_header("content-length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
body = b"<!doctype html><title>start</title><p>start"
|
||||
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)
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv, "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def served():
|
||||
srv, url = _serve()
|
||||
try:
|
||||
yield url
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["no-content", "reset-content"])
|
||||
def test_a_goto_to_a_response_with_no_document_ends_with_the_engines_error(firefox_binary, served, path):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright.sync_api import Error
|
||||
|
||||
with InvisiblePlaywright(seed=4243, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(served + "start", wait_until="load", timeout=30_000)
|
||||
with pytest.raises(Error) as nav:
|
||||
page.goto(served + path, timeout=30_000)
|
||||
message = nav.value.message
|
||||
# it ENDED: an error the engine said, not the goto's own timeout running out
|
||||
assert not any(w in message for w in ("Timeout", "exceeded", "not reached")), message
|
||||
assert page.url == served + "start", "a response with no document replaced the page: %s" % page.url
|
||||
@@ -23,7 +23,7 @@ import pytest
|
||||
from _servers import LocalServer
|
||||
|
||||
READ = """() => new Promise(resolve => {
|
||||
const timer = setTimeout(() => resolve({timeout: true}), 8000);
|
||||
const timer = setTimeout(() => resolve({timeout: true}), 30000);
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
p => { clearTimeout(timer); resolve({lat: p.coords.latitude, lon: p.coords.longitude}); },
|
||||
e => { clearTimeout(timer); resolve({error: e.code, message: e.message}); });
|
||||
|
||||
@@ -6,18 +6,30 @@ network by those events (tf-fetch's network recorder does) never knew the reques
|
||||
|
||||
The page asks for the same address four ways. `plain` is the control (a fetch without keepalive), `keepalive` and
|
||||
`beacon` are the two that the engine runs in the parent process, and each must give exactly one `request` and one end.
|
||||
|
||||
The test waits for what the product promises, not for a time: until every request that began has its end (and the four
|
||||
have begun), with a deadline of 15 s that no healthy run comes near. A product that loses an end stays red, because the
|
||||
deadline passes; a slow machine only takes longer. The message gives every event with the time it was heard, from the
|
||||
goto, so a red run says whether the end came late or never.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
from _waits import Timeline, wait_until, without_end
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
EXPECTED = ["/seen/beacon", "/seen/keepalive", "/seen/keepalive-nocors", "/seen/plain"]
|
||||
|
||||
#: Far beyond what a healthy run needs (a few hundred ms); it is the only clock the verdict has.
|
||||
DEADLINE = 15.0
|
||||
|
||||
PAGE = b"""<!doctype html><title>keepalive</title><script>
|
||||
addEventListener('load', () => {
|
||||
fetch('/seen/plain', {method: 'POST', body: 'x'});
|
||||
@@ -40,13 +52,18 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _heard(self):
|
||||
self.server.timeline.add("server", "%s %s" % (self.command, self.path))
|
||||
|
||||
def do_GET(self):
|
||||
self._heard()
|
||||
if self.path == "/":
|
||||
self._answer(PAGE, "text/html; charset=utf-8")
|
||||
else:
|
||||
self._answer(b"ok")
|
||||
|
||||
def do_POST(self):
|
||||
self._heard()
|
||||
self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
||||
self._answer(b"ok")
|
||||
|
||||
@@ -54,9 +71,10 @@ class _Handler(BaseHTTPRequestHandler):
|
||||
@pytest.fixture
|
||||
def site():
|
||||
srv = LocalServer(("127.0.0.1", 0), _Handler)
|
||||
srv.timeline = Timeline()
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d" % srv.server_address[1]
|
||||
yield SimpleNamespace(url="http://127.0.0.1:%d" % srv.server_address[1], timeline=srv.timeline)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
@@ -66,19 +84,36 @@ def site():
|
||||
def test_every_request_of_the_page_reaches_the_client_with_its_end(firefox_binary, site, route):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
started, ended = [], []
|
||||
timeline = site.timeline
|
||||
|
||||
def short(url):
|
||||
return url.replace(site.url, "")
|
||||
|
||||
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
|
||||
context = browser.new_context()
|
||||
if route:
|
||||
context.route("**/*", lambda r: r.continue_())
|
||||
def handler(r):
|
||||
timeline.add("route", short(r.request.url))
|
||||
r.continue_()
|
||||
context.route("**/*", handler)
|
||||
page = context.new_page()
|
||||
page.on("request", lambda r: started.append(r.url.replace(site, "")))
|
||||
page.on("requestfinished", lambda r: ended.append(r.url.replace(site, "")))
|
||||
page.on("requestfailed", lambda r: ended.append(r.url.replace(site, "")))
|
||||
page.goto(site + "/", wait_until="load")
|
||||
page.wait_for_timeout(2000) # the client is a sync one: events are delivered while it calls the browser
|
||||
seen = sorted(u for u in started if u.startswith("/seen/"))
|
||||
assert seen == ["/seen/beacon", "/seen/keepalive", "/seen/keepalive-nocors", "/seen/plain"], \
|
||||
"the client heard these requests: %r" % started
|
||||
assert sorted(u for u in ended if u.startswith("/seen/")) == seen, \
|
||||
"requests without an end for the client: %r" % sorted(set(seen) - set(ended))
|
||||
page.on("request", lambda r: timeline.add("request", short(r.url)))
|
||||
page.on("requestfinished", lambda r: timeline.add("finished", short(r.url)))
|
||||
page.on("requestfailed", lambda r: timeline.add("failed", short(r.url)))
|
||||
|
||||
def of_the_page(kinds):
|
||||
return [u for u in timeline.of(*kinds) if u.startswith("/seen/")]
|
||||
|
||||
timeline.begin()
|
||||
page.goto(site.url + "/", wait_until="load")
|
||||
# The client is a sync one: events are delivered while it calls the browser, so the wait is a call.
|
||||
# What is awaited: the four requests have begun, and every request that began has its end.
|
||||
wait_until(lambda: sorted(set(of_the_page(["request"]))) == EXPECTED
|
||||
and not without_end(of_the_page(["request"]), of_the_page(["finished", "failed"])),
|
||||
DEADLINE, lambda: page.wait_for_timeout(50))
|
||||
started, ended = of_the_page(["request"]), of_the_page(["finished", "failed"])
|
||||
events = "\nevents, from the goto:\n" + timeline.render()
|
||||
assert sorted(started) == EXPECTED, "the client heard these requests: %r (after %.0f s)%s" % (
|
||||
started, DEADLINE, events)
|
||||
assert sorted(ended) == sorted(started), "requests without an end for the client: %r%s" % (
|
||||
without_end(started, ended), events)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""A launch of an e2e test is told where it leaves from; no service of the internet is asked (no browser).
|
||||
|
||||
The core's ``prepare_session_geo`` asks ``discover_egress_ip`` for the exit of a session, and with no proxy that is an HTTP request to three "what is my
|
||||
address" services. ``tests/_lab_egress.py`` and the session fixture ``_the_lab_declares_the_exit`` of ``tests/conftest.py`` declare the exit of the lab
|
||||
instead, so that the 222 launches that name neither ``timezone=`` nor ``proxy=`` depend on nothing outside the machine. This file is the proof, on the
|
||||
real composition of a session and with every way out of the process closed:
|
||||
|
||||
* a session composed with the declared exit asks the core's discovery once, gets the zone and the language of the lab database, and opens no
|
||||
connection and resolves no name (the socket and the resolver raise, and ``requests`` is not called);
|
||||
* the same with a zone named by the caller: the question is still asked, and still answered here;
|
||||
* a question behind a proxy is not answered here: it goes to what answered it before (the gateways of the tests answer it themselves);
|
||||
* the test that must prove the discovery itself gets the real function against an echo service on loopback, and the three services are not asked;
|
||||
* the conftest holds the declaration for the whole session, and a module-scoped browser is launched after it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import _lab_egress
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
TESTS = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
class _Closed(AssertionError):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_way_out(monkeypatch):
|
||||
"""Every way out of the process raises: the connect, the name lookup, the request. What an offline runner does, said loudly."""
|
||||
tried = []
|
||||
|
||||
def closed(what):
|
||||
def refuse(*args, **kwargs):
|
||||
tried.append(what)
|
||||
raise _Closed("%s was asked: a launch of an e2e test must not leave the machine" % what)
|
||||
return refuse
|
||||
|
||||
monkeypatch.setattr(socket.socket, "connect", closed("socket.connect"))
|
||||
monkeypatch.setattr(socket, "create_connection", closed("socket.create_connection"))
|
||||
monkeypatch.setattr(socket, "getaddrinfo", closed("socket.getaddrinfo"))
|
||||
import requests
|
||||
|
||||
monkeypatch.setattr(requests.sessions.Session, "request", closed("requests"))
|
||||
return tried
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def declared(monkeypatch, tmp_path):
|
||||
"""What the session fixture of the conftest installs, installed for one test (the same function, with the patch of the test)."""
|
||||
monkeypatch.delenv("STEALTHFOX_GEOIP_MMDB", raising=False)
|
||||
exit_ = _lab_egress.install(monkeypatch, tmp_path)
|
||||
assert exit_ is not None
|
||||
return exit_
|
||||
|
||||
|
||||
def test_a_session_composed_with_the_declared_exit_opens_no_connection_and_gets_the_zone_of_the_lab(declared, no_way_out):
|
||||
from invisible_core import prepare_session_geo
|
||||
|
||||
geo = prepare_session_geo("", None, "auto", seed=7)
|
||||
assert no_way_out == [], "the composition left the machine: %s" % no_way_out
|
||||
assert declared.direct_questions == 1 and declared.proxied_questions == []
|
||||
assert geo.egress_ip == _lab_egress.LAB_EGRESS_IP
|
||||
assert geo.timezone == "America/New_York" and geo.locale.primary == "en-US", (geo.timezone, geo.locale)
|
||||
|
||||
|
||||
def test_a_zone_named_by_the_caller_does_not_make_the_launch_ask_the_internet(declared, no_way_out):
|
||||
from invisible_core import prepare_session_geo
|
||||
|
||||
geo = prepare_session_geo("Europe/Rome", None, "auto", seed=7)
|
||||
assert no_way_out == []
|
||||
assert declared.direct_questions == 1, "the core asks for the exit even when the zone is named: the question must be answered here"
|
||||
assert geo.timezone == "Europe/Rome" and geo.egress_ip == _lab_egress.LAB_EGRESS_IP
|
||||
|
||||
|
||||
def test_the_lab_exit_is_a_public_address_the_lab_database_answers_as_new_york(tmp_path):
|
||||
import ipaddress
|
||||
|
||||
import maxminddb
|
||||
|
||||
assert ipaddress.ip_address(_lab_egress.LAB_EGRESS_IP).is_global, "a reserved address is refused by the core as not routable"
|
||||
path = tmp_path / "lab.mmdb"
|
||||
path.write_bytes(_lab_egress.lab_database_bytes())
|
||||
with maxminddb.open_database(str(path)) as reader:
|
||||
record = reader.get(_lab_egress.LAB_EGRESS_IP)
|
||||
assert record["country"]["iso_code"] == "US" and record["location"]["time_zone"] == "America/New_York", record
|
||||
|
||||
|
||||
def test_a_question_behind_a_proxy_goes_to_what_answered_it_before(monkeypatch):
|
||||
asked = []
|
||||
|
||||
def before(proxy=None, *args, **kwargs):
|
||||
asked.append(proxy)
|
||||
return "203.0.113.9"
|
||||
|
||||
exit_ = _lab_egress.DeclaredExit(before)
|
||||
proxy = {"server": "socks5://127.0.0.1:9"}
|
||||
assert exit_(None) == _lab_egress.LAB_EGRESS_IP and asked == []
|
||||
assert exit_({}) == _lab_egress.LAB_EGRESS_IP and asked == []
|
||||
assert exit_(proxy, timeout=3) == "203.0.113.9" and asked == [proxy]
|
||||
assert exit_.direct_questions == 2 and exit_.proxied_questions == ["socks5://127.0.0.1:9"]
|
||||
|
||||
|
||||
def test_a_test_that_replaces_the_question_goes_back_to_the_declared_exit_not_to_the_network(monkeypatch, tmp_path):
|
||||
"""The order a session makes: the fixture of the session installs first, the test's own ``monkeypatch`` replaces and then undoes."""
|
||||
from invisible_core import _geo
|
||||
|
||||
with pytest.MonkeyPatch.context() as session:
|
||||
session.setenv("STEALTHFOX_GEOIP_MMDB", str(tmp_path / "set-by-a-leg"))
|
||||
declared = _lab_egress.install(session, tmp_path)
|
||||
with pytest.MonkeyPatch.context() as test:
|
||||
test.setattr(_geo, "discover_egress_ip", lambda *a, **k: "203.0.113.5")
|
||||
assert _geo.discover_egress_ip(None) == "203.0.113.5"
|
||||
assert _geo.discover_egress_ip(None) == _lab_egress.LAB_EGRESS_IP and declared.direct_questions == 1
|
||||
|
||||
|
||||
def test_a_database_set_by_a_leg_is_left_alone_and_none_is_made_when_not_set(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("STEALTHFOX_GEOIP_MMDB", str(tmp_path / "pinned.mmdb"))
|
||||
assert _lab_egress.use_the_lab_database(monkeypatch, tmp_path / "made") is None and not (tmp_path / "made").exists()
|
||||
monkeypatch.delenv("STEALTHFOX_GEOIP_MMDB")
|
||||
made = _lab_egress.use_the_lab_database(monkeypatch, tmp_path / "made")
|
||||
import os
|
||||
|
||||
assert made is not None and made.read_bytes() == _lab_egress.lab_database_bytes() and os.environ["STEALTHFOX_GEOIP_MMDB"] == str(made)
|
||||
|
||||
|
||||
def test_the_real_discovery_is_proved_against_an_echo_service_on_loopback(local_egress_echo):
|
||||
from invisible_core import _geo
|
||||
|
||||
found = _geo.discover_egress_ip(None)
|
||||
assert found == _lab_egress.LAB_EGRESS_IP
|
||||
assert local_egress_echo.questions == 1, "the real function asked %d time(s) and only the echo of the test may be asked" % local_egress_echo.questions
|
||||
assert all(url.startswith("http://127.0.0.1:") for url in _geo._IP_ECHO_ENDPOINTS)
|
||||
|
||||
|
||||
def test_the_conftest_declares_the_exit_for_the_whole_session_and_before_any_module_browser():
|
||||
tree = ast.parse((TESTS / "conftest.py").read_text(encoding="utf-8"))
|
||||
fixtures = {}
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.FunctionDef):
|
||||
for decorator in node.decorator_list:
|
||||
if isinstance(decorator, ast.Call) and getattr(decorator.func, "attr", "") == "fixture":
|
||||
fixtures[node.name] = {kw.arg: getattr(kw.value, "value", None) for kw in decorator.keywords}
|
||||
declaration = fixtures.get("_the_lab_declares_the_exit")
|
||||
assert declaration == {"scope": "session", "autouse": True}, (
|
||||
"the exit of the lab is declared by an autouse fixture of SESSION scope (a module-scoped browser is launched before any function-scoped one): %r"
|
||||
% (declaration,))
|
||||
assert fixtures["browser"].get("scope") == "module", "the conftest's module browser is the reason for the scope above"
|
||||
@@ -126,7 +126,7 @@ def test_the_launcher_marks_what_it_composes():
|
||||
prefs = _session.build_prefs(
|
||||
profile=generate_profile(seed=7), locale=decide_session_locale("en-US"),
|
||||
timezone="America/New_York", extra_prefs=None, virtual_display=False,
|
||||
cursor_engine=_session.ENGINE_BINARY, humanize=humanize, session_seed=7)
|
||||
cursor_engine=_session.ENGINE_PYTHON, humanize=humanize, session_seed=7)
|
||||
assert prefs.get(COMPOSED_PREF) is True, humanize
|
||||
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ def test_a_bare_launch_behind_a_proxy_is_composed_through_it(firefox_binary, mon
|
||||
from invisible_core._geo import SessionGeo
|
||||
from invisible_playwright import _session
|
||||
from invisible_playwright._pw.sync_api import sync_playwright
|
||||
from _socks_servers import Socks5TcpOnly
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, Socks5TcpOnly
|
||||
from test_webrtc_realness import _PROBE_JS, candidates, host_is_mdns
|
||||
|
||||
egress = "203.0.113.7"
|
||||
@@ -141,7 +141,7 @@ def test_a_bare_launch_behind_a_proxy_is_composed_through_it(firefox_binary, mon
|
||||
try:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("http://127.0.0.1:%d/" % httpd.server_address[1], wait_until="domcontentloaded")
|
||||
res = page.evaluate(_PROBE_JS)
|
||||
res = page.evaluate(_PROBE_JS, "stun:%s:%d" % (STUN_NUMBER, STUN_PORT))
|
||||
finally:
|
||||
browser.close()
|
||||
finally:
|
||||
|
||||
@@ -23,6 +23,7 @@ import threading
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
@@ -57,6 +58,13 @@ def _serve():
|
||||
return server, "http://127.0.0.1:%d" % server.server_address[1]
|
||||
|
||||
|
||||
def _heard(page, responses, names):
|
||||
"""Until the client has heard the response of each name (the events of a sync client are delivered while it calls
|
||||
the browser), with a deadline far beyond a healthy run: a machine's speed is not the verdict."""
|
||||
assert wait_until(lambda: all(name in responses for name in names), 30, lambda: page.wait_for_timeout(100)), (
|
||||
"the client never heard %r; it heard %r" % ([n for n in names if n not in responses], sorted(responses)))
|
||||
|
||||
|
||||
def test_the_body_of_a_document_the_tab_left_is_evicted(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-60")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
@@ -68,13 +76,13 @@ def test_the_body_of_a_document_the_tab_left_is_evicted(firefox_binary, engine_a
|
||||
responses = {}
|
||||
page.on("response", lambda r: responses.setdefault(r.url.rsplit("/", 1)[-1], r))
|
||||
|
||||
page.goto(base + "/a.html", wait_until="load", timeout=20_000)
|
||||
page.wait_for_timeout(300)
|
||||
page.goto(base + "/a.html", wait_until="load", timeout=30_000)
|
||||
_heard(page, responses, ("a.html", "a.css", "a.js"))
|
||||
assert b"document A" in responses["a.html"].body()
|
||||
assert b"/* A */" in responses["a.css"].body(), "the current document's sub-resource is readable"
|
||||
|
||||
page.goto(base + "/b.html", wait_until="load", timeout=20_000)
|
||||
page.wait_for_timeout(300)
|
||||
page.goto(base + "/b.html", wait_until="load", timeout=30_000)
|
||||
_heard(page, responses, ("b.html", "b.js"))
|
||||
assert b"document B" in responses["b.html"].body(), "the document that committed keeps its body"
|
||||
assert b"fromB" in responses["b.js"].body()
|
||||
|
||||
@@ -95,12 +103,12 @@ def test_nothing_else_is_lost_when_the_bodies_go(firefox_binary, engine_at_least
|
||||
with InvisiblePlaywright(seed=4250, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
for i in range(6):
|
||||
page.goto(base + "/%s.html" % "ab"[i % 2], wait_until="load", timeout=20_000)
|
||||
page.goto(base + "/%s.html" % "ab"[i % 2], wait_until="load", timeout=30_000)
|
||||
second = browser.new_page()
|
||||
second.goto(base + "/a.html", wait_until="load", timeout=20_000)
|
||||
second.goto(base + "/a.html", wait_until="load", timeout=30_000)
|
||||
assert "document A" in second.content()
|
||||
second.close()
|
||||
page.goto(base + "/b.html", wait_until="load", timeout=20_000)
|
||||
page.goto(base + "/b.html", wait_until="load", timeout=30_000)
|
||||
assert "document B" in page.content()
|
||||
finally:
|
||||
server.shutdown()
|
||||
@@ -74,7 +74,7 @@ ON_WINDOWS = sys.platform == "win32"
|
||||
@pytest.mark.skipif(ON_WINDOWS, reason="the system theme is declared, and its absence refused, on Linux only")
|
||||
@pytest.mark.parametrize("pref", MISSING)
|
||||
def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-68")
|
||||
with pytest.raises(RuntimeError) as err:
|
||||
c, profile_dir = _launch(firefox_binary, pref)
|
||||
# Not reached when the engine refuses: close what must not be running.
|
||||
@@ -88,7 +88,7 @@ def test_a_missing_pref_refuses_the_launch(firefox_binary, engine_at_least, pref
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_every_pref_declared_the_launch_succeeds(firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-65")
|
||||
engine_at_least("firefox-68")
|
||||
c, profile_dir = _launch(firefox_binary, None)
|
||||
try:
|
||||
assert c.ready_seen, "the browser did not announce the protocol"
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from _waits import wait_until
|
||||
from stroke_shape import stroke_problems
|
||||
|
||||
PAGE = """<!doctype html><html><body style="margin:0">
|
||||
@@ -44,7 +45,6 @@ def test_a_stroke_from_standstill_does_not_open_with_the_point_it_stands_on(fire
|
||||
"""After a move that stopped on (500, 300) and a pause, the click's stroke
|
||||
begins at its first real step: the page's next `mousemove` is not (500, 300)
|
||||
again."""
|
||||
import time
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=4252, binary_path=firefox_binary, headless=True,
|
||||
@@ -52,7 +52,9 @@ def test_a_stroke_from_standstill_does_not_open_with_the_point_it_stands_on(fire
|
||||
page = browser.new_context().new_page()
|
||||
page.set_content(PAGE)
|
||||
page.mouse.move(500, 300)
|
||||
time.sleep(0.3)
|
||||
# until the page has heard the move end on its point (a condition with a deadline, not 0.3 s): the click below starts from a pointer at rest
|
||||
assert wait_until(lambda: (page.evaluate("window.moves") or [None])[-1] == [500, 300], 30,
|
||||
lambda: page.wait_for_timeout(50)), page.evaluate("window.moves")
|
||||
seen = len(page.evaluate("window.moves"))
|
||||
assert page.evaluate("window.moves")[-1] == [500, 300]
|
||||
page.mouse.click(400, 240)
|
||||
|
||||
@@ -55,29 +55,31 @@ _WORKER = r"""(urls) => {
|
||||
#: same security check before anything is read, so what can differ is the
|
||||
#: answer, and the answer is compared.
|
||||
_CHANNELS = r"""async (url) => {
|
||||
const settle = (p, ms = 3000) => Promise.race([p, new Promise(r => setTimeout(() => r("no answer"), ms))]);
|
||||
const out = {};
|
||||
out.worker = await settle(new Promise(r => {
|
||||
// Every channel is asked at once and each has 30 s to answer: "no answer" is a channel that stays silent, and the deadline is the wait's, far beyond any
|
||||
// healthy run. A name that is nowhere answers every channel (an error, a throw, a rejection), so no silence is waited for when the engine's file looks like it.
|
||||
const settle = (p, ms = 30000) => Promise.race([p, new Promise(r => setTimeout(() => r("no answer"), ms))]);
|
||||
const channels = {};
|
||||
channels.worker = new Promise(r => {
|
||||
try {
|
||||
const w = new Worker(url);
|
||||
w.onerror = e => { e.preventDefault(); r("error event: " + (e.message || "")); };
|
||||
w.onmessage = () => r("message");
|
||||
} catch (e) { r("throws " + e.name); }
|
||||
}));
|
||||
out.module_worker = await settle(new Promise(r => {
|
||||
});
|
||||
channels.module_worker = new Promise(r => {
|
||||
try {
|
||||
const w = new Worker(url, {type: "module"});
|
||||
w.onerror = e => { e.preventDefault(); r("error event: " + (e.message || "")); };
|
||||
} catch (e) { r("throws " + e.name); }
|
||||
}));
|
||||
out.shared_worker = await settle(new Promise(r => {
|
||||
});
|
||||
channels.shared_worker = new Promise(r => {
|
||||
try {
|
||||
const w = new SharedWorker(url);
|
||||
w.onerror = e => { e.preventDefault(); r("error event"); };
|
||||
} catch (e) { r("throws " + e.name); }
|
||||
}));
|
||||
out.fetch = await settle(fetch(url).then(res => "status " + res.status, e => "rejects " + e.name));
|
||||
out.xhr = await settle(new Promise(r => {
|
||||
});
|
||||
channels.fetch = fetch(url).then(res => "status " + res.status, e => "rejects " + e.name);
|
||||
channels.xhr = new Promise(r => {
|
||||
const seen = [];
|
||||
try {
|
||||
const x = new XMLHttpRequest();
|
||||
@@ -86,18 +88,22 @@ _CHANNELS = r"""async (url) => {
|
||||
x.open("GET", url);
|
||||
x.send();
|
||||
} catch (e) { r("throws " + e.name); }
|
||||
}));
|
||||
out.import = await settle(import(url).then(() => "loaded", e => "rejects " + e.name));
|
||||
});
|
||||
channels.import = import(url).then(() => "loaded", e => "rejects " + e.name);
|
||||
for (const [tag, attr] of [["script", "src"], ["img", "src"], ["link", "href"], ["iframe", "src"]]) {
|
||||
out[tag] = await settle(new Promise(r => {
|
||||
channels[tag] = new Promise(r => {
|
||||
const el = document.createElement(tag);
|
||||
if (tag === "link") el.rel = "stylesheet";
|
||||
el.onload = () => r("load");
|
||||
el.onerror = () => r("error");
|
||||
el[attr] = url;
|
||||
document.body.appendChild(el);
|
||||
}), 1500);
|
||||
});
|
||||
}
|
||||
const names = Object.keys(channels);
|
||||
const answers = await Promise.all(names.map(n => settle(channels[n])));
|
||||
const out = {};
|
||||
names.forEach((n, i) => { out[n] = answers[i]; });
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
@@ -30,7 +30,14 @@ _GATHER_JS = r"""async () => {
|
||||
const cands = [];
|
||||
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, 2500));
|
||||
// Until the gathering says it is over, not for a fixed time: how long a gathering takes is the speed of the machine, whether it ends is the product.
|
||||
// The deadline is far beyond any healthy run; a gathering that never completes returns what it has, and the assertions on the candidates fail on it.
|
||||
await new Promise(resolve => {
|
||||
const timer = setTimeout(resolve, 30000);
|
||||
const done = () => { if (pc.iceGatheringState === 'complete') { clearTimeout(timer); resolve(); } };
|
||||
pc.addEventListener('icegatheringstatechange', done);
|
||||
done();
|
||||
});
|
||||
try { pc.close(); } catch (e) {}
|
||||
return cands;
|
||||
}"""
|
||||
|
||||
@@ -43,7 +43,6 @@ from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -54,20 +53,19 @@ ROUNDS = 5
|
||||
|
||||
def _goto(page, url, **kwargs):
|
||||
"""`page.goto`, which may answer that the previous page's own redirect won
|
||||
(module docstring). Either answer comes in seconds."""
|
||||
(module docstring). The detector of a navigation that never answers is the timeout of the `goto` itself (each caller passes
|
||||
one): a bound of the test stricter than it only judged the speed of the machine."""
|
||||
from invisible_playwright.sync_api import Error
|
||||
|
||||
started = time.monotonic()
|
||||
try:
|
||||
page.goto(url, **kwargs)
|
||||
except Error as e:
|
||||
if "NS_BINDING_ABORTED" in str(e):
|
||||
# The page's own replace stopped ours: it is where it sent itself.
|
||||
page.wait_for_url("**/landed", timeout=10_000)
|
||||
page.wait_for_url("**/landed", timeout=30_000)
|
||||
else:
|
||||
assert "is interrupted by another navigation to" in str(e), e
|
||||
assert "/landed" in str(e).split("another navigation to")[1], e
|
||||
assert time.monotonic() - started < 10, url
|
||||
|
||||
|
||||
def _replace_after_load(ms: int, cross_site: bool) -> bytes:
|
||||
@@ -79,6 +77,24 @@ def _replace_after_load(ms: int, cross_site: bool) -> bytes:
|
||||
% (target, ms)).encode()
|
||||
|
||||
|
||||
def _replace_without_a_timer(held: bool, cross_site: bool) -> bytes:
|
||||
"""The page of a `networkidle` case: it replaces itself with no timer in it, so how fast the machine is cannot
|
||||
decide whether the move comes before the half second of quiet that `networkidle` waits for.
|
||||
|
||||
- ``held`` False: from inside the `load` handler itself, before `load` is even reported;
|
||||
- ``held`` True: when the first bytes of a response the server holds open arrive. That request is in flight until
|
||||
the navigation aborts it, so the network is not quiet for as long as the page has not moved, whatever the load
|
||||
on the machine."""
|
||||
target = ("location.origin.replace('127.0.0.1','localhost')+'/landed'"
|
||||
if cross_site else "'/landed'")
|
||||
if held:
|
||||
script = ("addEventListener('load', () => fetch('/hold').then(r => r.body.getReader().read())"
|
||||
".then(() => location.replace(%s)))" % target)
|
||||
else:
|
||||
script = "addEventListener('load', () => location.replace(%s))" % target
|
||||
return ("<!doctype html><html><body><p id=p>first</p><script>%s</script></body></html>" % script).encode()
|
||||
|
||||
|
||||
PAGES = {
|
||||
"/head": (b"<!doctype html><html><head><script>location.replace('/landed')"
|
||||
b"</script></head><body><p id=p>head</p></body></html>"),
|
||||
@@ -89,12 +105,33 @@ PAGES = {
|
||||
for _ms in (0, 50, 300):
|
||||
PAGES["/r%d" % _ms] = _replace_after_load(_ms, False)
|
||||
PAGES["/x%d" % _ms] = _replace_after_load(_ms, True)
|
||||
# the networkidle cases: "/ir0" and "/ix0" move inside the load handler, "/ir50" and "/ix50" when the held response
|
||||
# starts to arrive (the 0 and the 50 of the names are the cases of the old timers)
|
||||
for _name, _held in (("0", False), ("50", True)):
|
||||
PAGES["/ir" + _name] = _replace_without_a_timer(_held, False)
|
||||
PAGES["/ix" + _name] = _replace_without_a_timer(_held, True)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
release = threading.Event()
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path.split("?")[0] == "/hold":
|
||||
# a response that has begun and does not end: 16 KiB so the first chunk is delivered at once,
|
||||
# then it stays open until the page that asked for it moves away (or the module's teardown)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(b"x" * 16384)
|
||||
self.wfile.flush()
|
||||
except OSError:
|
||||
return
|
||||
release.wait(60)
|
||||
return
|
||||
body = PAGES.get(self.path.split("?")[0], PAGES["/landed"])
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
@@ -111,6 +148,7 @@ def site():
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield "http://127.0.0.1:%d" % srv.server_address[1]
|
||||
release.set()
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
@@ -128,7 +166,7 @@ def page(firefox_binary):
|
||||
def test_a_read_right_after_goto_answers(page, site, path):
|
||||
for i in range(ROUNDS):
|
||||
_goto(page, "%s%s?i=%d" % (site, path, i), wait_until="domcontentloaded",
|
||||
timeout=15_000)
|
||||
timeout=30_000)
|
||||
# Each read is made at once, while the page may still be moving: none
|
||||
# of them may surface the engine's refusal of a vanished world. A count
|
||||
# is of the page as it is NOW, and that can be the replacing document
|
||||
@@ -142,7 +180,7 @@ def test_a_read_right_after_goto_answers(page, site, path):
|
||||
texts = ([], ["first"], ["head"], ["landed"])
|
||||
assert page.locator("#p").all_inner_texts() in texts
|
||||
assert page.locator("#p").all_text_contents() in texts
|
||||
assert page.inner_text("#p", timeout=10_000) in ("first", "head",
|
||||
assert page.inner_text("#p", timeout=30_000) in ("first", "head",
|
||||
"landed")
|
||||
# The caller's code is NOT a read: it is sent once ([B285]). On a page
|
||||
# still moving - `/x50` replaces itself after the read above - it
|
||||
@@ -158,9 +196,12 @@ def test_a_read_right_after_goto_answers(page, site, path):
|
||||
|
||||
@pytest.mark.parametrize("path", ["/r0", "/r50", "/x0", "/x50"])
|
||||
def test_networkidle_is_reached_on_the_page_that_replaced_ours(page, site, path):
|
||||
"""The page moves with no timer (`_replace_without_a_timer`): `networkidle` promises half a second without
|
||||
network, and that cannot pass before the move however slow the machine is. A `networkidle` that comes back on the
|
||||
first page, or never comes back because the new frame forgot the navigation, is still red."""
|
||||
for i in range(ROUNDS):
|
||||
_goto(page, "%s%s?n=%d" % (site, path, i), wait_until="networkidle",
|
||||
timeout=15_000)
|
||||
_goto(page, "%s/i%s?n=%d" % (site, path[1:], i), wait_until="networkidle",
|
||||
timeout=30_000)
|
||||
assert page.url.endswith("/landed"), page.url
|
||||
|
||||
|
||||
@@ -192,7 +233,7 @@ def test_reads_wait_as_playwright_s_do(page, site):
|
||||
page.evaluate("setTimeout(() => { const b = document.createElement('b');"
|
||||
" b.id = 'late'; b.textContent = 'late';"
|
||||
" document.body.appendChild(b); }, 500)")
|
||||
assert page.inner_text("#late", timeout=5_000) == "late"
|
||||
assert page.inner_text("#late", timeout=30_000) == "late"
|
||||
from invisible_playwright.sync_api import TimeoutError as PlaywrightTimeout
|
||||
with pytest.raises(PlaywrightTimeout, match="Timeout 300ms exceeded"):
|
||||
page.inner_text("#never", timeout=300)
|
||||
@@ -205,8 +246,8 @@ def test_expect_reads_the_state_it_names(page, site):
|
||||
page.set_content("<input type=checkbox id=c><p id=h hidden>x</p>")
|
||||
with pytest.raises(AssertionError):
|
||||
expect(page.locator("#c")).to_be_checked(timeout=500)
|
||||
expect(page.locator("#c")).not_to_be_checked(timeout=500)
|
||||
expect(page.locator("#c")).not_to_be_checked(timeout=30_000)
|
||||
with pytest.raises(AssertionError):
|
||||
expect(page.locator("#h")).to_be_visible(timeout=500)
|
||||
expect(page.locator("#h")).to_be_hidden(timeout=500)
|
||||
expect(page.locator("#missing")).to_be_hidden(timeout=500)
|
||||
expect(page.locator("#h")).to_be_hidden(timeout=30_000)
|
||||
expect(page.locator("#missing")).to_be_hidden(timeout=30_000)
|
||||
@@ -0,0 +1,207 @@
|
||||
"""A path of the cursor is ONE stroke: the pacer's instants on the client's clock, each point sent without waiting for the reply of the one
|
||||
before it.
|
||||
|
||||
THE KNOWN-BAD, measured on a GitHub runner (hunt 43794672372): `Pointer` asked the `Pacer` for the instant of each point, but every point
|
||||
left through `actions.move`, a lone command that WAITS for the engine's reply. A slow reply stopped the path (the page saw a 2.6 s pause)
|
||||
and the points after it were then crowded together. The keys had the same defect before the stroke.
|
||||
|
||||
What is asserted here is who sends the path, never how long it took:
|
||||
|
||||
* with a stand-in for the core's actions (`_pointer_fakes.FakeActions`): the approach, the walk before a `Mouse.click`, the wheel burst
|
||||
and the idle movement each go to `Actions.walk` as one timeline, and no single `move` is made for them;
|
||||
* with the real `Actions` over a connection that records when a command is sent and when a reply is waited for: every point of the
|
||||
path is on the wire before the first reply is waited for, all of them in one stroke, each at its instant (`at`); a command of the
|
||||
user that is alone (`mouse.down`, `mouse.up`, a one-step `move`) still waits for its own reply.
|
||||
|
||||
Nothing launches a browser, and nothing here reads the time.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.juggler import PageActs
|
||||
from invisible_core.juggler.actions import Actions
|
||||
|
||||
from invisible_playwright import _cursor
|
||||
|
||||
from _pointer_fakes import BOX, FakeInjected, FakePage, VirtualClock, make_pointer, use_clock
|
||||
from invisible_playwright._juggler.pointer import Pointer
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def quiet(monkeypatch):
|
||||
monkeypatch.delenv(_cursor.LANDING_ENV, raising=False)
|
||||
_cursor._reset_warnings()
|
||||
yield
|
||||
_cursor._reset_warnings()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 1. Through a stand-in for the core's actions: what is handed over
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def test_the_approach_is_one_walk_and_no_single_move(monkeypatch):
|
||||
use_clock(monkeypatch, VirtualClock())
|
||||
page, pointer = make_pointer()
|
||||
pointer.approach("main", "#b", None)
|
||||
assert len(page.walks) == 1
|
||||
assert len(page.walks[0]["events"]) > 3, "a path of one point is not a path"
|
||||
assert page.singles == [], "a point of the path was sent as a command of its own"
|
||||
assert page.walks[0]["emit_last"] is False, "the last hop is the action's"
|
||||
|
||||
|
||||
def test_the_walk_before_a_mouse_click_is_one_walk_and_no_single_move(monkeypatch):
|
||||
use_clock(monkeypatch, VirtualClock())
|
||||
page, pointer = make_pointer()
|
||||
pointer.travel(900.0, 500.0)
|
||||
assert len(page.walks) == 1 and len(page.walks[0]["events"]) > 3
|
||||
assert page.singles == []
|
||||
|
||||
|
||||
def test_the_wheel_burst_is_one_walk_with_its_notches_in_it(monkeypatch):
|
||||
use_clock(monkeypatch, VirtualClock())
|
||||
page, pointer = make_pointer()
|
||||
assert pointer.wheel(0.0, 900.0) is True
|
||||
assert len(page.walks) == 1
|
||||
notches = [e for e in page.walks[0]["events"] if e.is_wheel]
|
||||
assert len(notches) > 1
|
||||
assert sum(e.dy for e in notches) == pytest.approx(900.0)
|
||||
assert page.singles == []
|
||||
|
||||
|
||||
def test_the_idle_movement_and_the_approach_are_each_one_walk(monkeypatch):
|
||||
clock = VirtualClock()
|
||||
use_clock(monkeypatch, clock)
|
||||
page, pointer = make_pointer()
|
||||
pointer.approach("main", "#b", None)
|
||||
page.walks.clear()
|
||||
clock.t += 30.0 # the script was busy elsewhere
|
||||
pointer.approach("main", "#b", None)
|
||||
assert len(page.walks) == 2, "the fidget and the approach are one path each"
|
||||
assert page.singles == []
|
||||
|
||||
|
||||
def test_the_instants_handed_over_are_the_pacers_and_grow(monkeypatch):
|
||||
use_clock(monkeypatch, VirtualClock())
|
||||
page, pointer = make_pointer()
|
||||
pointer.approach("main", "#b", None)
|
||||
ts = [e.t_ms for e in page.walks[0]["events"]]
|
||||
assert ts == sorted(ts) and ts[-1] > 0.0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 2. Through the real `Actions`: what goes on the wire
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class Reply:
|
||||
def __init__(self, engine, index) -> None:
|
||||
self.engine, self.index = engine, index
|
||||
|
||||
def wait(self, timeout=None):
|
||||
self.engine.log.append(("wait", self.index))
|
||||
return {}, 0
|
||||
|
||||
|
||||
class HeldEngine:
|
||||
"""A connection that records when each command is sent and when its reply is waited for. A reply is only ever read at `wait`, so a
|
||||
command sent before the `wait` of the one before it was sent while that reply was still held."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.sent = []
|
||||
self.log = []
|
||||
|
||||
def send_async(self, method, params, session=None):
|
||||
self.log.append(("send", len(self.sent)))
|
||||
self.sent.append((method, dict(params)))
|
||||
return Reply(self, len(self.sent) - 1)
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=None, **kw):
|
||||
return self.send_async(method, params or {}, session).wait(timeout)[0]
|
||||
|
||||
def kinds(self):
|
||||
return [k for k, _i in self.log]
|
||||
|
||||
def params(self, method):
|
||||
return [p for m, p in self.sent if m == method]
|
||||
|
||||
|
||||
class Life:
|
||||
main_frame = "main"
|
||||
|
||||
|
||||
class Injected(FakeInjected):
|
||||
def check_hit_target(self, frame_id, element, point):
|
||||
return "done"
|
||||
|
||||
|
||||
def _real(monkeypatch, *, seed=4242, budget=1.5):
|
||||
use_clock(monkeypatch, VirtualClock())
|
||||
engine = HeldEngine()
|
||||
page = FakePage(box=BOX)
|
||||
actions = Actions(engine, "S", Life(), Injected(page), acts=PageActs(0), session_seed=seed,
|
||||
motion_budget_s=budget, layout="us")
|
||||
pointer = Pointer(actions, Injected(page), 0, seed, budget, lambda: page.viewport_size)
|
||||
return engine, actions, pointer
|
||||
|
||||
|
||||
def _one_stroke_in_order(params):
|
||||
assert len(params) > 3, "a path of one point is not a path"
|
||||
assert len({p["stroke"] for p in params}) == 1
|
||||
ats = [p["at"] for p in params]
|
||||
assert ats == sorted(ats) and len(set(ats)) == len(ats), "the instants of a path increase"
|
||||
|
||||
|
||||
def test_every_point_of_the_approach_is_sent_before_any_reply_is_waited_for(monkeypatch):
|
||||
engine, actions, pointer = _real(monkeypatch)
|
||||
pointer.approach("main", "#b", None)
|
||||
n = len(engine.sent)
|
||||
assert engine.kinds() == ["send"] * n + ["wait"] * n, "a point waited for the reply of the one before it"
|
||||
_one_stroke_in_order(engine.params("Page.dispatchMouseEvent"))
|
||||
|
||||
|
||||
def test_every_point_of_the_walk_before_a_click_is_in_one_stroke(monkeypatch):
|
||||
engine, actions, pointer = _real(monkeypatch)
|
||||
pointer.travel(900.0, 500.0)
|
||||
n = len(engine.sent)
|
||||
assert engine.kinds() == ["send"] * n + ["wait"] * n
|
||||
_one_stroke_in_order(engine.params("Page.dispatchMouseEvent"))
|
||||
|
||||
|
||||
def test_the_wheel_burst_is_one_stroke_of_moves_and_notches(monkeypatch):
|
||||
engine, actions, pointer = _real(monkeypatch)
|
||||
assert pointer.wheel(0.0, 900.0) is True
|
||||
n = len(engine.sent)
|
||||
assert engine.kinds() == ["send"] * n + ["wait"] * n
|
||||
everything = [p for _m, p in engine.sent]
|
||||
assert len({p["stroke"] for p in everything}) == 1
|
||||
ats = [p["at"] for p in everything]
|
||||
assert ats == sorted(ats)
|
||||
assert sum(p["deltaY"] for p in engine.params("Page.dispatchWheelEvent")) == pytest.approx(900.0)
|
||||
|
||||
|
||||
def test_the_path_of_one_gesture_is_not_the_stroke_of_the_next(monkeypatch):
|
||||
engine, actions, pointer = _real(monkeypatch)
|
||||
pointer.travel(900.0, 500.0)
|
||||
first = {p["stroke"] for p in engine.params("Page.dispatchMouseEvent")}
|
||||
pointer.travel(100.0, 100.0)
|
||||
ids = {p["stroke"] for p in engine.params("Page.dispatchMouseEvent")}
|
||||
assert len(first) == 1 and len(ids) == 2
|
||||
|
||||
|
||||
def test_a_lone_press_release_and_one_step_move_each_wait_for_their_own_reply(monkeypatch):
|
||||
engine, actions, pointer = _real(monkeypatch)
|
||||
actions.move(10.0, 10.0)
|
||||
actions.mouse_down()
|
||||
actions.mouse_up()
|
||||
assert engine.kinds() == ["send", "wait"] * 3
|
||||
assert all("stroke" not in p and "at" not in p for _m, p in engine.sent)
|
||||
|
||||
|
||||
def test_the_explicit_move_walks_its_path_as_a_stroke_and_then_is_one_command(monkeypatch):
|
||||
engine, actions, pointer = _real(monkeypatch)
|
||||
pointer.move(900.0, 500.0)
|
||||
actions.move(900.0, 500.0)
|
||||
n = len(engine.sent) - 1
|
||||
assert engine.kinds() == ["send"] * n + ["wait"] * n + ["send", "wait"]
|
||||
@@ -22,6 +22,8 @@ import time
|
||||
|
||||
import pytest
|
||||
|
||||
from _waits import wait_until
|
||||
|
||||
PAGE = """<!doctype html><html><body style="margin:0">
|
||||
<button id="b" style="width:300px;height:200px">b</button>
|
||||
<script>
|
||||
@@ -62,13 +64,16 @@ def test_each_pointer_call_answers_after_the_page_handled_its_event(firefox_bina
|
||||
"not wait for the page" % (step, took * 1000))
|
||||
|
||||
|
||||
@pytest.mark.wall_clock
|
||||
@pytest.mark.e2e
|
||||
def test_a_click_that_opens_a_dialog_still_answers(firefox_binary):
|
||||
"""The wait ends when the event's handler opens a dialog: the handler runs
|
||||
the dialog inside itself, so the page handles the event only once the
|
||||
dialog is closed - and closing it is the caller's business, after the call
|
||||
has answered. Without that end, this click would hang until the bound."""
|
||||
has answered. Without that end, this click would hang until the engine's
|
||||
bound, which is 5 s and an error (`PageHandler._awaitBounded`): the call
|
||||
raises instead of answering. The dialog stays open until the call has
|
||||
returned, so the call can have answered only by the dialog's end of the
|
||||
wait, not because the handler finished; no clock is read."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=4248, binary_path=firefox_binary, headless=True,
|
||||
@@ -76,11 +81,13 @@ def test_a_click_that_opens_a_dialog_still_answers(firefox_binary):
|
||||
page = browser.new_context().new_page()
|
||||
page.set_content('<button id="b" style="width:300px;height:200px" '
|
||||
'onclick="alert(1); window.after = true">b</button>')
|
||||
seen = []
|
||||
page.on("dialog", lambda d: (seen.append(d.message), d.dismiss()))
|
||||
started = time.perf_counter()
|
||||
opened = []
|
||||
page.on("dialog", lambda dialog: opened.append(dialog)) # a plain function: the client tags its handlers
|
||||
# raises (the engine's "did not handle ... within 5 s") if the call waited for the handler
|
||||
page.mouse.click(150, 100)
|
||||
took = time.perf_counter() - started
|
||||
page.wait_for_function("window.after === true", timeout=5_000)
|
||||
assert seen == ["1"], seen
|
||||
assert took < 4.0, "the click waited %.1f s for a page held by its dialog" % took
|
||||
# the dialog event comes before the reply of the call; the pump only lets a late one be read
|
||||
assert wait_until(lambda: opened, 30, lambda: page.wait_for_timeout(50)), (
|
||||
"the click answered without the dialog having been heard")
|
||||
assert [d.message for d in opened] == ["1"], opened
|
||||
opened[0].dismiss()
|
||||
page.wait_for_function("window.after === true", timeout=30_000)
|
||||
+11
-6
@@ -124,7 +124,7 @@ def test_a_destination_that_commits_nothing_gives_no_popup_event(firefox_binary,
|
||||
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:
|
||||
with page.expect_popup(timeout=30000) 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()
|
||||
@@ -140,7 +140,10 @@ def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(fir
|
||||
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
|
||||
# The lower bound is the server's: it answers after 25 s, so a popup announced before 24 s was announced
|
||||
# before it was ready. There is no upper bound of ours: the limit above is expect_popup's 45 s (a popup
|
||||
# dropped at 20 s, the defect this test is red on, ends in its timeout).
|
||||
assert took > 24.0, "reported after %.1f s, before the destination had answered" % took
|
||||
assert info.value.url == site + "slow?ms=25000"
|
||||
info.value.close()
|
||||
|
||||
@@ -160,17 +163,19 @@ def test_a_listener_registered_in_the_page_handler_hears_the_load_of_the_popup(f
|
||||
def on_page(popup):
|
||||
popup.on("load", lambda p: heard.append(time.monotonic()))
|
||||
t = time.monotonic()
|
||||
popup.wait_for_load_state("load", timeout=10000)
|
||||
popup.wait_for_load_state("load", timeout=30000)
|
||||
waited.append(time.monotonic() - t)
|
||||
|
||||
ctx.on("page", on_page)
|
||||
with page.expect_popup(timeout=20000) as info:
|
||||
with page.expect_popup(timeout=30000) as info:
|
||||
page.click(opener)
|
||||
deadline = time.monotonic() + 5
|
||||
deadline = time.monotonic() + 30
|
||||
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
|
||||
# wait_for_load_state in the handler has its own deadline (10 s, above): a wait that never returns raises
|
||||
# there and `waited` stays empty, which is red here. How long it took is the machine's, not a verdict.
|
||||
assert waited, "wait_for_load_state in the handler never returned"
|
||||
info.value.close()
|
||||
|
||||
_drive(mode, firefox_binary, body)
|
||||
@@ -93,7 +93,7 @@ def _check(page, popup_of, site, opener):
|
||||
with page.expect_popup(timeout=30000) as info:
|
||||
page.click(opener)
|
||||
popup = info.value
|
||||
popup.wait_for_load_state("load", timeout=5000)
|
||||
popup.wait_for_load_state("load", timeout=30000)
|
||||
expected = (site.replace("127.0.0.1", "localhost") if opener.startswith("#x") else site) + "popup"
|
||||
assert popup.url == expected
|
||||
assert popup.title() == "popup"
|
||||
|
||||
Loaded 100 of 273 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user