Compare commits

...
Author SHA1 Message Date
feder-cr 2ec829cd8c ci: a hunt that repeats the Control+A file with the protocol trace of the worlds, the contexts and set_content
The rare red "the caller's world never appeared for frame mainframe-N ... Worlds seen: ['']" is raised by InjectedScript.caller_context of the core
after waiting for the context named __ctx_caller__, which only InjectedScript.install() declares (Page.setInitScripts). This measures, with times, what the
engine said and what the server sent around it, in the in-process browser and in the stock-client mode, on Linux and Windows.

- scripts/hunt_trace_plugin.py: a pytest plugin loaded with -p (not in tests/conftest.py); one JSON per test with the events of navigations, frames and
  contexts, the commands sent, and marks for install, caller_context and set_content.
- scripts/hunt_ctrla_rounds.py: rounds of four copies of the file at once (the browsers of a loadfile run, same tests in the same order per browser)
  until 300 runs; a red copy never stops the others.
- scripts/hunt_ctrla_summary.py: reds and greens apart, the sequence of the world events around set_content for each.
- control-a-trace-hunt.yml on a push to hunt/control-a-trace only, Linux (xvfb) and Windows; replaces second-goto-trace-hunt.yml.
2026-11-16 01:05:13 +01:00
feder-cr 0069d2fd96 ci: a hunt that runs the trace of the second goto on Linux and Windows, and not the full e2e of the branch it comes from
second-goto-trace-hunt.yml runs on a push to hunt/second-goto-trace only; e2e-no-reruns-hunt.yml is removed from this branch so that the push does not start the whole e2e again.
2026-11-16 00:41:25 +01:00
feder-cr 303adbecf8 ci: the second-goto hunt can record the protocol trace of ours (--trace): every event the client hears for the page, with its time, and the navigation id of each goto
The hook is the public Connection.add_listener of the core, found the way tests/_screencast_evidence.py finds it; the commands that start or end a navigation are seen on the same connection (the reply of Page.navigate gives the id of each goto). Nothing of src/ is touched.
2026-11-16 00:41:25 +01:00
feder-cr 47e67680de ci: the hunt measures the second goto that replaces the first on stock Playwright's Firefox beside ours
The same scenario as test_a_second_goto_to_a_third_site_interrupts_the_first_and_lands, 20 repetitions per browser,
a new browser each, ours and stock alternating, on Linux and on Windows. It records whether /second reached the
server and when, how each goto ended and after how many ms, and asserts nothing about the outcome.
2026-11-16 00:18:49 +01:00
feder-cr b1bae5e3fd tests: the replaced-goto test says which requests reached the server when it is red 2026-11-16 00:10:04 +01:00
feder-cr ea3f372b3a ci: the hunt proves the core it installed by the command its runner builds, not by a word its docstring may still name 2026-11-16 00:07:38 +01:00
feder-cr ac866325d9 ci: a hunt that runs the whole e2e of e2e.yml on the core of main, which reruns nothing, and keeps the junit of every pass 2026-11-15 23:57:59 +01:00
feder-cr 24a1e7c33b tests: the decorators in the known-bad sources of the clock check start a string of their own, so no line reads as an address 2026-11-15 23:57:59 +01:00
feder-cr 84bfdec0d4 tests: the comment of the WebRTC probe names what it is, not where it was copied from 2026-11-15 23:50:57 +01:00
feder-cr c5605964e1 tests: the known-bad Marionette port of the clock check is not itself a fixed port to the Marionette guard 2026-11-15 23:36:39 +01:00
feder-cr a1bbafbeaa tests: the debt of the clock check is made again on main with the Marionette port per launch, and the known-bad port of the check is not a fixed port to the Marionette guard 2026-11-15 23:36:15 +01:00
feder-cr 88d285d303 tests: closing one of four browsers is judged by where the loop's thread was and by the order of the answers, not by milliseconds
The three absolute bounds (held < 0.09 on the second control, held < 0.05 on the close, slowest < 2.0 on the other three) were
verdicts on the runner: a starved machine runs a short callback longer without any defect.

* the loop is held when the watcher saw its thread inside a step of the close that waits (shutdown, _join_workers, reap, op_close,
  wait_procs, rmtree, Thread.join); the control that holds the loop on purpose must be seen inside the function that holds it;
* a loop the machine did not schedule is charged no more than the longest stretch the same samples saw its thread run;
* the first removal inside the close waits (30 s at most) until every other browser answered a call that began after it did: a
  removal in a thread of its own is released by the answers, one on the loop only by the deadline; each other browser must also
  answer a call that began and ended inside the close. The seconds are printed and decide nothing.

The verdicts are pure functions in tests/_close_loop_verdicts.py, tried without a browser (on the real instrument, taken out of the
client script) in tests/test_the_close_loop_verdicts_see_the_defects.py. The three entries leave the debt of the clock check.
2026-11-15 23:33:19 +01:00
feder-cr a2d48d33be tests: the clock check refuses a deadline under 30 s on a wait for something that must happen, and an absolute margin on a duration in a judge that reports
The rule `timeout` reads `timeout=` (milliseconds for the Playwright API, seconds for the standard library, the helpers and the driver), `set_default_timeout`, `set_default_navigation_timeout` and the default of a parameter named timeout; a window in which the call is expected to run out of time (pytest.raises, a swallowed timeout, a limit named NEGATIVE) is accepted by its shape. The rule `bound` also reads an `if` that reports a problem, so judge_visits (LOAD_MARGIN_MS) is seen. The occurrences are in the debt until each one is corrected.
2026-11-15 23:33:19 +01:00
feder-cr feb43f03a3 tests: every key is still held to the 40 ms bound (it is born and handled in one task); only the events that cross from the parent are judged on the median 2026-11-15 23:33:19 +01:00
feder-cr 6aad4b3edb tests: the debt of the clock check holds only the nine occurrences other work corrects, every entry has the reason that makes it certain 2026-11-15 23:33:19 +01:00
feder-cr 03834f3a66 tests: the bound rule sees a limit that is a named variable or has a slack added, and the cpu-budget kind; the list is not made again yet 2026-11-15 23:33:19 +01:00
feder-cr e52f2dda30 tests: the deadline of a wait for something that must happen is 30 s where it was 5, 8, 10, 15, 20 or 25 2026-11-15 23:33:19 +01:00
feder-cr 8641484dbd tests: a fixed pause before a read is a wait for the condition the read needs, with a deadline of 30 s 2026-11-15 23:33:19 +01:00
feder-cr f09ff6adf5 tests: the channels of the juggler probe are asked at once and each has 30 s, not 3 s and 1.5 s one after the other 2026-11-15 23:33:18 +01:00
feder-cr 81741026c9 tests: the time a connection took to open is judged only when the page itself was not stopped, and the age of an input is judged on the median of its stream 2026-11-15 23:33:18 +01:00
feder-cr b91e18db21 tests: a PeerConnection of an e2e stays open until the road it was made for has been seen, it is no longer closed by a timer of the page 2026-11-15 23:33:07 +01:00
feder-cr 8c698e9421 tests: the turn page says posted and its final status in one step, so a read at posted never sees PENDING 2026-11-15 23:33:07 +01:00
feder-cr 12a8233a98 tests: the proof that a frame is in another process spins until one spin shows ticks, 30 s, and waits for the end of the spin instead of spin_ms + 800 2026-11-15 23:33:07 +01:00
feder-cr 8de65f8284 tests: a function handed by name to wait_until, watch or awatch is the step of a wait with a deadline 2026-11-15 23:33:07 +01:00
feder-cr 3caafc8b6e ci: the unit job fetches main so the lists that may only shrink can be compared with it 2026-11-15 23:33:07 +01:00
feder-cr 5d2200d6f2 tests: a check that the e2e tests do not wait on clocks, share ports, write the environment or reach the world
Reads the e2e files and the helpers of tests/ with ast and refuses a fixed pause
(time.sleep, asyncio.sleep, wait_for_timeout) that is not the step of a poll
with a deadline, a page timer, an absolute upper bound on a duration, a literal
port, a write to os.environ, a real host or a pip install outside the files of
the round after a publication, a count of processes, and a conftest that does
not declare the exit of the lab. Occurrences are named by file, scope, rule and
nth, never by line.

tests/gates/e2e_clock_exceptions.json holds the reviewed entries (closed kinds,
a reason each) and the debt: every other occurrence, made again from the sources
by scripts/e2e_clock_exceptions.py --write. A stale item of either list is red,
and the debt may not hold an occurrence that main's does not.
2026-11-15 23:33:07 +01:00
feder-cr 58794fc460 tests: the install and upgrade e2e run only in the round after a publication
test_release_e2e.py and test_upgrade_e2e.py install from the real index with
pip and uv, download the release from GitHub and walk the GitHub API: PyPI or
GitHub being down or rate limited reddened every pull request. The e2e tests
of those two files are now deselected from any run that does not name the file
(conftest.py, no new marker: the vocabulary is shared with the core), so
scripts/run_e2e.py, the Windows legs and the hunt do not collect them, and
user-install.yml, which names both, still does. A test collects and checks it,
and checks the wiring.
2026-11-15 23:33:07 +01:00
feder-cr 95c3a17e28 tests: the pages and STUN servers of three e2e tests are the test's own, not example.com and a public STUN
The persistent-profile test loads its own page on loopback (the same origin in
both sessions). The WebRTC gather without a proxy asks a STUN server of the
test on this host's address, the gather behind a TCP-only proxy asks a number
nothing answers, and its page is the local one carried through the proxy; a
proxy or network that fails there is now a failure, not a skip.
2026-11-15 23:33:07 +01:00
feder-cr b88f5e3a4d tests: an e2e launch is told where it leaves from, it does not ask three services of the internet
A launch with no proxy asks the core for its egress address, and the core asks
api.ipify.org, icanhazip.com and checkip.amazonaws.com: a third party in the
222 launches that name neither timezone= nor proxy=. A session fixture in the
conftest (session scope, so that the module-scoped browsers are covered)
answers that question with the lab's exit, and uses the lab GeoIP database when
no leg set one. A question behind a proxy is left to what answered it before.
A test that must prove the discovery itself uses local_egress_echo: the real
function against an echo service on loopback.
2026-11-15 23:33:07 +01:00
feder-cr 61219b606f Merge branch 'tests/no-third-party-reds-medium' into tmp/hm 2026-11-15 23:33:01 +01:00
feder-cr 61950b9f08 tests: the UDP chain by name is judged by an order (the Allocate comes while the later handshakes are held) and a count of exchanges, with no round budget on a clock
The verdict of the road of a TURN server written as a name compared the time between the first CONNECT to the DoH and the Allocate with
(rounds + 1) x the round trip, so a stall of the runner turned it red, and the number of rounds was an estimate. Two causal checks
replace it, and no duration is read:

- the test holds, with the new `Gateway.hold` (per control connection, by index and by what the connection asked for), the answer of
  every association handshake begun after the pool was ready; the TURN server has to answer the Allocate with credentials before the
  test lets them go. A handshake that waits for another leaves the road waiting for the test on any machine;
- the exchanges the gateway (`Gateway.requests`), the DoH and the TURN server (`TurnServer.transactions`, a retransmission is the
  same transaction) recorded from the birth of the PeerConnection to that Allocate are at most what the protocols ask for: one
  SOCKS5 control connection with its CONNECT (RFC 1928), one A question to the DoH (RFC 8484), two Allocate transactions (RFC 8656,
  RFC 8489): five, six with a user and a password (RFC 1929). One more is red.

Units, with no browser: red on handshakes in series and on one exchange more, green on the good road at any speed of the machine (every
stamp scaled up to 5000 times), and a plain client that walks the protocols spends exactly the five.
2026-11-15 23:31:25 +01:00
feder-cr de6f23cab3 tests: the rate of a screencast is read on the engine's stamps of its frames, not on when a client that stalled heard them 2026-11-15 23:31:25 +01:00
feder-cr 64ca7b6858 tests: the goto timeout detects a page that moves, the screencast waits have deadlines of 30 s, the transport tests set the driver choice with monkeypatch 2026-11-15 23:31:25 +01:00
feder-cr d52ce6b0c5 tests: the compositing test keeps the GPU CPU-time bound on Windows and asserts the absence of a GPU process on Linux, with no absolute CPU bound of the parent 2026-11-15 23:31:25 +01:00
feder-cr 60047974cc tests: the UDP chain by name is judged by rounds of the gateway and the association it left on, not by the tick of the page or two launches 2026-11-15 23:31:25 +01:00
feder-cr abb0fec604 tests: the serial-comparison guard knows the first-candidate test no longer compares two durations 2026-11-15 23:31:25 +01:00
feder-cr e6425ed823 tests: a unit test for the verdicts of the reworked e2e tests, with the red case of each 2026-11-15 23:31:25 +01:00
feder-cr 4ae82c636f tests: h3 visits wait for the QUIC connection of the browser, not for a fixed pause 2026-11-15 23:31:25 +01:00
feder-cr 11c81a7d18 tests: the first candidate of a far gateway is judged with the handshake held, and the 701 has no ceiling 2026-11-15 23:31:25 +01:00
feder-cr 72a88e9bef tests: the screencast arms wait for a number of frames and compare the rates of the frames that came 2026-11-15 23:31:24 +01:00
feder-cr de98485983 tests: the compositing test starts to sample when the engine has a content process 2026-11-15 23:31:24 +01:00
feder-cr af7a5ea507 tests: the service worker and the end of the processes of a closed context are waited for on their condition 2026-11-15 23:31:24 +01:00
feder-cr 6366bd5779 tests: the screenshots of frames of other sites are taken again until the frame is painted 2026-11-15 23:31:24 +01:00
feder-cr a64c1bb591 tests: the mouse events are waited for until the last one expected, not for 0.4 s 2026-11-15 23:31:24 +01:00
feder-cr ad78730b09 tests: the pause before the first key is judged on the browser's time stamps, not on the duration of the whole call 2026-11-15 23:31:24 +01:00
feder-cr abcc56e5b5 tests: the key delay is read from the browser's own event time stamps 2026-11-15 23:31:24 +01:00
feder-cr 11de43a1fc tests: the first datagram of a PeerConnection is judged by the association it left on, not by a number of milliseconds 2026-11-15 23:31:24 +01:00
feder-cr 912bf0c685 tests: the transport tests wait for the console, pageerror and dialog events, and the late element is shown after the absence check 2026-11-15 23:31:24 +01:00
feder-cr 8de974db6f tests: a page that moves is replaced with no timer, so networkidle cannot race it 2026-11-15 23:31:24 +01:00
72 changed files with 5385 additions and 463 deletions

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
# ─────────────────────────────────────────────────────────────────────────────
# control-a-trace-hunt.yml - a MEASUREMENT, not a gate: the Control+A file of the
# e2e (tests/test_control_a_selects_all_in_a_field_e2e.py, 20 tests: 5 ways to press
# the shortcut x 2 fields x the in-process browser and the stock client), run again
# and again with the protocol trace of scripts/hunt_trace_plugin.py, to find the cause
# of a rare red: `Page.set_content: the caller's world never appeared for frame
# mainframe-N - did you call install()? Worlds seen: ['']`.
#
# What it records, per test run, in one JSON: the events the engine sends about
# navigations, frames and contexts (executionContextsCleared / Created / Destroyed with
# the world), the commands the server sends (Page.setInitScripts, which is what
# declares the caller's world; Runtime.evaluate with its context), and the marks of
# install(), caller_context() and set_content, all with their time. scripts/
# hunt_ctrla_summary.py then puts the red runs and the green ones side by side.
#
# ROUNDS OF FOUR COPIES, not `-n 4`: four pytest processes at once, each on the whole
# file (what a `--dist loadfile` worker of the gate does), so that every browser lives
# the same 10 tests per mode, in the same order, as in the gate and four browsers are
# up together (scripts/hunt_ctrla_rounds.py says why). Rounds follow until 300 test
# runs per system are recorded (4 rounds = 320). A red copy never stops the others,
# and the verdict of the job is only that the files are there.
#
# It runs on a push to its own branch only.
# ─────────────────────────────────────────────────────────────────────────────
name: control-a-trace-hunt
on:
push:
branches: [hunt/control-a-trace]
permissions:
contents: read
# A hunt has a group of its own, unique to the run: a newer push never cancels
# a measurement that is half done (tests/test_ci_runs_once_per_commit.py).
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
GITHUB_TOKEN: ${{ github.token }}
# the core of main, not the pinned one: the pair is mismatched on purpose (as the core's wrapper-on-this-core job does)
INVISIBLE_CORE_PIN: allow
INVISIBLE_CORE_AUTOFIX: "off"
jobs:
control-a-trace-linux:
name: control-a-trace (linux)
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps (+ Playwright ONLY as a system tool)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install --no-deps --force-reinstall "git+https://github.com/oss-invisible/core@65307f59f1245e214c8357593950d5ec929536ac"
python -c "import invisible_core; from invisible_core.testing import e2e; c = e2e.command('4', [], junit='x.xml'); print('core', invisible_core.__version__, c); assert not any(a.startswith('--rerun') for a in c) and 'no:rerunfailures' in c, c"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: System deps (xvfb + Firefox runtime libs)
run: |
sudo apt-get update
sudo apt-get install -y xvfb
sudo "$(which python)" -m playwright install-deps firefox
- name: Fetch the published firefox binary
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: The Control+A file in rounds of four copies, with the protocol trace
timeout-minutes: 30
env:
PYTHONUNBUFFERED: "1"
run: xvfb-run -a python -u scripts/hunt_ctrla_rounds.py --binary "$FF" --out-dir "$RUNNER_TEMP/ctrla-hunt" --min-runs 300 --copies 4 --budget-min 18
- name: Close every Firefox left
if: always()
run: |
pkill -f firefox || true
echo "left: $(pgrep -fc firefox || true)"
- name: The summary of the red and the green runs
if: always()
run: python scripts/hunt_ctrla_summary.py "$RUNNER_TEMP/ctrla-hunt/trace" --max-reds 30 | tee "$RUNNER_TEMP/ctrla-hunt/summary.txt" || true
- name: Upload the traces, the junit and the logs
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: control-a-trace-linux-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/ctrla-hunt
if-no-files-found: warn
retention-days: 14
# The verdict is only that the files are there: a red test is what the hunt is for.
- name: Verdict (the files are there)
if: always()
run: |
traces=$(ls "$RUNNER_TEMP/ctrla-hunt/trace"/*.json 2>/dev/null | wc -l)
junits=$(ls "$RUNNER_TEMP/ctrla-hunt/junit"/*.xml 2>/dev/null | wc -l)
echo "trace files: $traces, junit files: $junits"
if [ "$traces" -lt 300 ]; then echo "::warning::only $traces test runs were recorded (300 were wanted)"; fi
[ "$traces" -gt 0 ] && [ "$junits" -gt 0 ]
control-a-trace-windows:
name: control-a-trace (windows)
runs-on: windows-2022
timeout-minutes: 40
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: Install wrapper + test deps
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install --no-deps --force-reinstall "git+https://github.com/oss-invisible/core@65307f59f1245e214c8357593950d5ec929536ac"
python -c "import invisible_core; from invisible_core.testing import e2e; c = e2e.command('4', [], junit='x.xml'); print('core', invisible_core.__version__, c); assert not any(a.startswith('--rerun') for a in c) and 'no:rerunfailures' in c, c"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: Fetch the published firefox binary
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: The Control+A file in rounds of four copies, with the protocol trace
timeout-minutes: 30
env:
PYTHONUNBUFFERED: "1"
run: python -u scripts/hunt_ctrla_rounds.py --binary "$FF" --out-dir "$RUNNER_TEMP/ctrla-hunt" --min-runs 300 --copies 4 --budget-min 18
- name: Close every Firefox left
if: always()
shell: pwsh
run: |
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
- name: The summary of the red and the green runs
if: always()
run: python scripts/hunt_ctrla_summary.py "$RUNNER_TEMP/ctrla-hunt/trace" --max-reds 30 | tee "$RUNNER_TEMP/ctrla-hunt/summary.txt" || true
- name: Upload the traces, the junit and the logs
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: control-a-trace-windows-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/ctrla-hunt
if-no-files-found: warn
retention-days: 14
# The verdict is only that the files are there: a red test is what the hunt is for.
- name: Verdict (the files are there)
if: always()
run: |
traces=$(ls "$RUNNER_TEMP/ctrla-hunt/trace"/*.json 2>/dev/null | wc -l)
junits=$(ls "$RUNNER_TEMP/ctrla-hunt/junit"/*.xml 2>/dev/null | wc -l)
echo "trace files: $traces, junit files: $junits"
if [ "$traces" -lt 300 ]; then echo "::warning::only $traces test runs were recorded (300 were wanted)"; fi
[ "$traces" -gt 0 ] && [ "$junits" -gt 0 ]
+2
View File
@@ -131,6 +131,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
+6
View File
@@ -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:
+56
View File
@@ -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())
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""A MEASUREMENT, not a gate: the Control+A file, run again and again with the protocol trace, until there are enough runs.
python scripts/hunt_ctrla_rounds.py --binary "$FF" --out-dir out [--min-runs 300] [--copies 4] [--budget-min 28]
One ROUND starts COPIES pytest processes at once, each on the whole file tests/test_control_a_selects_all_in_a_field_e2e.py (20 tests: 10 for
the in-process browser, 10 for the stock client), each with its own junit, its own log and its own tag (`r<round>c<copy>`), loaded with
`-p scripts.hunt_trace_plugin` (one JSON per test in `<out-dir>/trace`). Rounds follow each other until `--min-runs` test runs have been
recorded or the time budget is spent (no round is started after it). No round ever stops the others: a copy that is red, hangs or dies is
only a copy that wrote what it wrote, and the exit code is non-zero only when the hunt could not start (no binary) or recorded nothing.
Why COPIES in parallel and not `-n 4 --dist loadfile` or `-n 4 --dist load`: under `loadfile` a file goes to ONE worker, so a single file
would run on one worker and the other three would be idle, which is not four at once; under `load` the 20 tests of the file are scattered
over four workers and each builds the module-scoped `browser` fixture for itself, so every browser sees about 5 tests instead of the 10 it
sees in the gate, in another order: the question of this hunt (what a browser that has served pages before does with the next one) would
be asked of a different browser. A copy is what a `loadfile` worker is in the gate: the whole file, in file order, one browser per mode;
four copies are the four browsers at once of the gate (the cap of this project is four browsers).
Layout of `--out-dir`: `trace/` (the JSON of the plugin), `junit/` (one XML per copy), `logs/` (the output of each copy).
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
TEST_FILE = "tests/test_control_a_selects_all_in_a_field_e2e.py"
#: A test that hangs ends its copy at this many seconds (pytest-timeout, thread method as in the gate), not the job.
TEST_DEADLINE_S = 300
#: A copy that is still alive after this long is killed: a whole file takes a couple of minutes.
COPY_DEADLINE_S = 15 * 60
def command(junit):
return [
sys.executable, "-u", "-m", "pytest",
"-m", "e2e", "-o", "addopts=",
"-p", "no:rerunfailures", "-p", "no:cacheprovider",
"-p", "scripts.hunt_trace_plugin",
"-o", "junit_family=xunit2", "--junitxml=%s" % junit,
"--timeout", str(TEST_DEADLINE_S), "--timeout-method", "thread",
"-v", "--tb=short",
TEST_FILE,
]
def environment(binary, trace_dir, tag):
env = {k: v for k, v in os.environ.items() if k != "PYTEST_ADDOPTS"}
env.update({
"PYTHONUNBUFFERED": "1",
"INVPW_BINARY_PATH": binary,
"STEALTHFOX_E2E_BINARY": binary,
"HUNT_TRACE_DIR": str(trace_dir),
"HUNT_TRACE_TAG": tag,
})
return env
def recorded(trace_dir):
return sum(1 for _ in Path(trace_dir).glob("*.json"))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH") or os.environ.get("FF"),
help="the engine of invisible_playwright (default: $INVPW_BINARY_PATH, then $FF)")
parser.add_argument("--out-dir", default="ctrla-hunt", help="where trace/, junit/ and logs/ are written")
parser.add_argument("--min-runs", type=int, default=300, help="stop after the round that reaches this many test runs (default 300)")
parser.add_argument("--copies", type=int, default=4, help="pytest processes at once in a round (default 4: the browsers of the gate)")
parser.add_argument("--budget-min", type=float, default=28.0, help="no new round after this many minutes (default 28)")
args = parser.parse_args(argv)
if not args.binary or not Path(args.binary).exists():
print("::error::the engine is needed: --binary, or $INVPW_BINARY_PATH / $FF (%r)" % args.binary, flush=True)
return 2
out = Path(args.out_dir).resolve()
trace, junit, logs = out / "trace", out / "junit", out / "logs"
for directory in (trace, junit, logs):
directory.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
number = 0
while recorded(trace) < args.min_runs:
if number and time.monotonic() - started > args.budget_min * 60:
print("budget of %.0f min spent: no new round" % args.budget_min, flush=True)
break
number += 1
round_started = time.monotonic()
procs = []
for copy in range(1, args.copies + 1):
tag = "r%02dc%d" % (number, copy)
log = open(logs / (tag + ".log"), "w", encoding="utf-8", newline="\n")
proc = subprocess.Popen(command(junit / (tag + ".xml")), cwd=str(ROOT), env=environment(args.binary, trace, tag),
stdout=log, stderr=subprocess.STDOUT)
procs.append((tag, proc, log))
codes = {}
for tag, proc, log in procs:
try:
codes[tag] = proc.wait(timeout=max(1.0, COPY_DEADLINE_S - (time.monotonic() - round_started)))
except subprocess.TimeoutExpired:
proc.kill()
codes[tag] = "killed"
log.close()
print("round %d: %.0f s, %d run(s) recorded so far, exit codes %s" % (
number, time.monotonic() - round_started, recorded(trace), codes), flush=True)
total = recorded(trace)
print("%d round(s), %d test run(s) recorded in %s" % (number, total, trace), flush=True)
return 0 if total else 1
if __name__ == "__main__":
sys.exit(main())
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""The summary of a Control+A hunt: the JSON of scripts/hunt_trace_plugin.py, read and put in two piles, red and green.
python scripts/hunt_ctrla_summary.py DIR [DIR ...] [--around MS] [--top N] [--max-reds N]
DIR is a folder (or several: the artefact of each job) holding the files the plugin wrote, however deep. It prints
* the count per system and mode of the browser fixture (in-process, stock-client): how many passed and how many were red;
* for each red (up to --max-reds): the test, the first line of its failure and the sequence of events of the world, the context and the
navigation of ITS page around `set_content`: what the engine said (event), what the server sent (send / reply / error) and the marks of
the plugin (install, caller_context, set_content), with the ms counted from the start of `set_content` (negative: before it). A context is
named by its world: main (the page's own, empty name), aux (`__ctx_aux__`, the utility world) and caller (`__ctx_caller__`, the one
`set_content` waits for); an id is resolved to its world from the creation event;
* the sequence that is typical of the greens, per mode (the most frequent ones, --top), in the same words and with the times of the first
test that had it, so that a red is read against what a green does.
Nothing here decides: the exit code is 1 only when no JSON is found. The red ones are the ones whose outcome is `failed` or `error`.
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import Counter
from pathlib import Path
#: What the sequence is made of: the events of the worlds, the contexts, the frames and the navigations; the commands that make a world or run
#: in one; the marks of the plugin.
_EVENT = {
"Page.navigationStarted", "Page.navigationCommitted", "Page.navigationAborted", "Page.sameDocumentNavigation", "Page.eventFired",
"Page.frameAttached", "Page.frameDetached", "Runtime.executionContextsCleared", "Runtime.executionContextCreated",
"Runtime.executionContextDestroyed", "Browser.attachedToTarget", "Browser.detachedFromTarget",
}
_COMMAND = {"Page.setInitScripts", "Runtime.evaluate", "Runtime.callFunction", "Page.navigate", "Page.close", "Browser.newPage"}
_WORLD = {"": "main", "__ctx_aux__": "aux", "__ctx_caller__": "caller"}
_RED = ("failed", "error")
def load(directories):
tests = []
for directory in directories:
for path in sorted(Path(directory).rglob("*.json")):
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if isinstance(data, dict) and "events" in data and "nodeid" in data:
data["_file"] = path.name
tests.append(data)
return tests
def _session_of(row):
"""The session a row belongs to: its own, or for a target that attaches the one it announces."""
_, _, method, detail, _, session = row
if method in ("Browser.attachedToTarget", "Browser.detachedFromTarget"):
return (detail or {}).get("sessionId") or session
return session
def _world_names(rows):
"""executionContextId -> world, from the creation events of this test (every connection: the ids are unique to a session)."""
out = {}
for _, kind, method, detail, _, _ in rows:
if kind == "event" and method == "Runtime.executionContextCreated":
out[str(detail.get("executionContextId"))] = _WORLD.get(detail.get("world"), detail.get("world"))
return out
def _word(row, worlds):
"""One row as a short word: what it is and what tells it apart (the world, the frame is left out: the session is already one page)."""
_, kind, method, detail, _, _ = row
detail = detail or {}
short = method.replace("Page.", "").replace("Runtime.", "").replace("Browser.", "")
parts = []
if method == "Runtime.executionContextCreated":
parts.append(_WORLD.get(detail.get("world"), detail.get("world")))
elif method == "Runtime.executionContextDestroyed":
parts.append(worlds.get(str(detail.get("executionContextId")), "unknown ctx"))
elif method in ("Runtime.evaluate", "Runtime.callFunction"):
parts.append("in " + worlds.get(str(detail.get("executionContextId")), "?"))
if detail.get("expression"):
parts.append(detail["expression"][:40])
elif method == "Page.setInitScripts" and kind == "send":
parts.append("+".join(_WORLD.get(w[0], str(w[0])) for w in detail.get("worlds") or []) or "none")
elif method.startswith("Page.navigation") and detail.get("url"):
parts.append(detail["url"][:40])
elif method == "Page.eventFired":
parts.append(detail.get("name"))
elif method in ("caller_context.start", "caller_context.error", "set_content.start", "install.start"):
if detail.get("worlds") is not None:
parts.append("worlds known: [%s]" % ", ".join(w.split("=")[0] for w in detail["worlds"]))
if detail.get("error"):
parts.append(detail["error"][:60])
elif method == "set_content.error" and detail.get("error"):
parts.append(detail["error"][:60])
prefix = {"send": "-> ", "reply": "<- ", "error": "<-ERR ", "event": "", "mark": "## "}[kind]
word = prefix + short
if kind == "event" and detail.get("replay"):
word += " (replayed)"
if kind == "error":
parts.append(str(detail.get("error", ""))[:60])
elif kind == "reply" and detail.get("ms") is not None:
parts.append("%s ms" % detail["ms"])
return "%s(%s)" % (word, " ".join(str(p) for p in parts if p is not None and p != "")) if parts else word
def _interesting(row):
_, kind, method, _, _, _ = row
if kind == "event":
return method in _EVENT
if kind in ("send", "reply", "error"):
return method in _COMMAND
return kind == "mark" and (method.startswith(("install.", "caller_context.", "set_content.")))
def _sequence(test):
"""(session, rows of that page that matter, anchor ms): the page is the one of the `set_content` mark; the anchor is its start."""
rows = test["events"]
anchor_row = next((r for r in rows if r[1] == "mark" and r[2] == "set_content.start"), None) or next((r for r in rows if r[1] == "mark" and r[2] == "caller_context.start"), None) # the world is asked for by others too
if anchor_row is None:
return None, [], None, {}
session = anchor_row[5]
worlds = _world_names(rows)
mine = [r for r in rows if _interesting(r) and (_session_of(r) == session or r[1] == "mark" and r[5] == session)]
return session, mine, anchor_row[0], worlds
def _fold(words):
"""Consecutive repeats collapse: [word, ms of the first, count]."""
folded = []
for word, ms in words:
if folded and folded[-1][0] == word:
folded[-1][2] += 1
else:
folded.append([word, ms, 1])
return folded
def _words(test):
got = _sequence(test)
session, rows, anchor, worlds = got
if session is None and not rows:
return None
return [(_word(r, worlds), round(r[0] - anchor, 1)) for r in rows]
def _print_sequence(folded, indent=" "):
for word, ms, count in folded:
print("%s%+10.1f ms %s%s" % (indent, ms, word, " x%d" % count if count > 1 else ""))
def _first_line(test):
for text in (test.get("failure") or {}).values():
for line in str(text).splitlines():
if line.startswith("E ") and ("Error" in line or "error" in line):
return line[1:].strip()[:200]
return str(text).strip().splitlines()[0][:200] if str(text).strip() else ""
return ""
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("directories", nargs="+", help="folders with the JSON of the plugin (searched however deep)")
parser.add_argument("--around", type=float, default=None, metavar="MS",
help="show only the rows from this many ms before set_content (default: the whole life of the page)")
parser.add_argument("--top", type=int, default=3, help="how many green sequences to show per mode (default 3)")
parser.add_argument("--max-reds", type=int, default=10, help="how many red tests to show in detail (default 10)")
args = parser.parse_args(argv)
tests = load(args.directories)
if not tests:
print("no JSON of the plugin under %s" % ", ".join(args.directories))
return 1
counts = Counter((t.get("system"), t.get("mode"), "red" if t["outcome"] in _RED else t["outcome"]) for t in tests)
print("== %d test runs" % len(tests))
for system, mode in sorted({(s, m) for s, m, _ in counts}, key=str):
row = {k: v for (s, m, k), v in counts.items() if (s, m) == (system, mode)}
print(" %-8s %-13s %s" % (system, mode, ", ".join("%s %d" % (k, v) for k, v in sorted(row.items()))))
hooks = sorted({e for t in tests for e in t.get("hook_errors") or []})
if hooks:
print("== hooks that could not be installed (the trace is partial):")
for e in hooks:
print(" " + e)
reds = [t for t in tests if t["outcome"] in _RED]
print("\n== %d red" % len(reds))
for test in reds[:args.max_reds]:
print("\n-- %s [%s, %s, pid %s, #%s]\n %s" % (test["nodeid"], test.get("system"), test.get("mode"), test.get("pid"),
test.get("sequence"), _first_line(test)))
words = _words(test)
if words is None:
print(" (no set_content and no caller_context in this test: the failure is not where the hunt looks)")
continue
if args.around is not None:
words = [w for w in words if w[1] >= -args.around]
print(" page session %s; ms from the start of set_content (events of THIS page; ## = a mark of the plugin):" % _sequence(test)[0])
_print_sequence(_fold(words))
if len(reds) > args.max_reds:
print("\n(%d more red not shown: --max-reds)" % (len(reds) - args.max_reds))
greens = [t for t in tests if t["outcome"] == "passed"]
print("\n== typical sequence of the %d green, per mode" % len(greens))
for mode in sorted({t.get("mode") for t in greens}, key=str):
groups = {}
for test in (t for t in greens if t.get("mode") == mode):
words = _words(test)
if words is None:
continue
if args.around is not None:
words = [w for w in words if w[1] >= -args.around]
folded = _fold(words)
slot = groups.setdefault(tuple((w, c) for w, _, c in folded), [0, folded])
slot[0] += 1
ranked = sorted(groups.values(), key=lambda item: -item[0])
print("\n-- mode %s: %d distinct sequence(s)" % (mode, len(ranked)))
for n, folded in ranked[:args.top]:
print(" x%d (times of the first test with it):" % n)
_print_sequence(folded)
return 0
if __name__ == "__main__":
sys.exit(main())
+686
View File
@@ -0,0 +1,686 @@
#!/usr/bin/env python3
"""A MEASUREMENT, not a gate: one scenario, run on this package's browser and on stock Playwright's Firefox, side by side.
The scenario is the one of tests/test_navigation_across_processes_e2e.py::test_a_second_goto_to_a_third_site_interrupts_the_first_and_lands:
* sites isolated as in that file (`fission.autostart`, strategy 1), a local server on a thread, three hosts a.test, b.test and c.test
on its one port, told to the browser by `network.dns.localDomains` (a standard Firefox pref: the same line reaches both browsers);
* the page is at a.test/plain; goto 1 goes to b.test/partial, whose headers and first bytes the server sends and whose rest it HOLDS
until the scenario is over; as soon as the client has heard the response of /partial, goto 2 goes to c.test/second
(domcontentloaded, timeout 15 s).
Per repetition it records what the question "did the second goto leave the browser, and how did the two gotos end" needs:
* whether the request of /second reached the server, and at how many ms after the start of goto 2 (the server and the client read the
same clock, `time.perf_counter()`, in this one process), and whether it came before or after goto 2 had ended;
* how goto 1 ended (the error and its class), and at how many ms;
* how goto 2 ended (it returned, or the error), at how many ms.
A new BROWSER per repetition, not a new context: what the navigation depends on is the processes the browser has (the spare process it
preallocated, the one that holds a.test, the ones it starts for b.test and c.test); a new context of a warmed browser would inherit them and
every repetition after the first would measure another state. A cold browser per repetition is the state a user's first navigations have,
and it is the same for both. The two browsers alternate (ours, stock, ours, ...) so a runner that slows down in the middle of the run slows both.
Nothing here decides: the exit code is non-zero only when the script itself could not measure (a browser that never launched in any
repetition, a binary that is not there). The result is one JSON per browser and system and a summary printed to the log.
python scripts/hunt_second_goto_vs_stock.py --binary "$FF" --out-dir out # both browsers, 20 repetitions each
python scripts/hunt_second_goto_vs_stock.py --browser stock --repetitions 3 --out-dir out
python scripts/hunt_second_goto_vs_stock.py --binary "$FF" --browser invisible --trace --out-dir out # the protocol trace of ours
`--trace` (our browser only) adds to every repetition what the client heard of the protocol, and when: see "the protocol trace" below.
Stock Firefox is the one `python -m playwright install firefox` downloads for the `playwright` package installed (scripts/playwright_pin.txt).
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import platform
import statistics
import sys
import tempfile
import threading
import time
from collections import Counter
from http.server import BaseHTTPRequestHandler
from pathlib import Path
from socketserver import ThreadingTCPServer
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parent.parent
#: The prefs of the file the scenario comes from (FISSION_ON there): the same for both browsers.
FISSION_ON = {
"fission.autostart": True,
"fission.webContentIsolationStrategy": 1,
"dom.ipc.processCount.webIsolated": 4,
"network.dns.localDomains": "a.test,b.test,c.test",
}
SEED = 42 # the seed of the test this comes from (only ours reads it)
REPETITIONS = 20
GOTO1_TIMEOUT_MS = 30000 # the first goto ends when the second replaces it, or when the held answer is let go
GOTO2_TIMEOUT_MS = 15000 # as asked: domcontentloaded, 15 s
HEAR_RESPONSE_S = 15.0 # how long the client waits to hear the response of /partial before it gives the repetition up
SETTLE_S = 1.0 # after the end of the scenario and the release: a /second that comes late is still counted
LAUNCH_S = 90.0 # a launch that takes longer is a repetition lost, not a hang
CLOSE_S = 30.0
REPETITION_S = 150.0 # the whole scenario of one repetition: nothing may hold the run
def _ms(seconds):
return None if seconds is None else round(seconds * 1000.0, 1)
class _Server(ThreadingTCPServer):
"""A thread per connection and daemon threads: a connection the browser opens and leaves cannot hold the server or its shutdown."""
daemon_threads = True
allow_reuse_address = True
def server_bind(self):
ThreadingTCPServer.server_bind(self)
self.server_name, self.server_port = self.server_address[:2]
class Sites:
"""The local server of one repetition. `arrived` has the time (perf_counter) each path was first asked for."""
def __init__(self):
self.arrived = {} # path -> perf_counter of the first request
self.release = threading.Event() # what the server holds until the scenario is over
owner = self
class Handler(BaseHTTPRequestHandler):
timeout = 10
def log_message(self, *args):
pass
def do_GET(self):
path = self.path.split("?")[0]
owner.arrived.setdefault(path, time.perf_counter())
try:
if path == "/partial":
# the headers and the start of the body arrive, the rest is held: the response is there, the navigation has
# changed process, the document is not complete
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", "200")
self.end_headers()
self.wfile.write(b"<!doctype html><title>partial</title><p>start")
self.wfile.flush()
owner.release.wait()
self.wfile.write(b" " * 156)
return
body = ("<!doctype html><title>%s</title><p>%s" % (path, path)).encode()
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)
except OSError:
pass
self.server = _Server(("127.0.0.1", 0), Handler)
self.port = self.server.server_address[1]
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
def at(self, host, path):
return "http://%s:%d%s" % (host, self.port, path)
def close(self):
self.release.set()
try:
self.server.shutdown()
self.server.server_close()
except Exception:
pass
self.thread.join(timeout=10)
# ---------------------------------------------------------------- the two browsers
class _Ours:
"""invisible_playwright, the published engine ($FF), the prefs of the scenario."""
name = "invisible"
def __init__(self, binary):
self.binary = binary
self._cm = None
async def launch(self):
from invisible_playwright.async_api import InvisiblePlaywright
self._cm = InvisiblePlaywright(seed=SEED, binary_path=self.binary, humanize=False, headless=True, extra_prefs=FISSION_ON)
browser = await self._cm.__aenter__()
return browser
async def close(self):
cm, self._cm = self._cm, None
if cm is not None:
await cm.__aexit__(None, None, None)
class _Stock:
"""Stock Playwright with its own Firefox: no engine of ours, no seed, the same prefs."""
name = "stock"
def __init__(self, binary=None):
self._pw = None
self._browser = None
async def launch(self):
from playwright.async_api import async_playwright
self._pw = await async_playwright().start()
self._browser = await self._pw.firefox.launch(headless=True, firefox_user_prefs=dict(FISSION_ON))
return self._browser
async def close(self):
browser, self._browser = self._browser, None
pw, self._pw = self._pw, None
try:
if browser is not None:
await browser.close()
finally:
if pw is not None:
await pw.stop()
# ---------------------------------------------------------------- one repetition
def _error_class(message):
if message is None:
return None
if "is interrupted by another navigation" in message:
return "interrupted by another navigation"
if "NS_BINDING_ABORTED" in message:
return "NS_BINDING_ABORTED"
if "Timeout" in message and "exceeded" in message:
return "timeout"
if "load not reached" in message:
return "load not reached"
return "other"
async def _scenario(page, sites, trace=None):
"""The measurement. Every time is perf_counter; the row says them in ms from the start of goto 1 (`t=0`)."""
if trace is not None:
trace.attach(page) # before the first goto: nothing the navigations of the page say is missed
heard = {} # path -> perf_counter the client heard its response
page.on("response", lambda r: heard.setdefault(urlsplit(r.url).path, time.perf_counter()))
await page.goto(sites.at("a.test", "/plain"), wait_until="domcontentloaded", timeout=GOTO2_TIMEOUT_MS)
ends = {}
async def goto1():
try:
await page.goto(sites.at("b.test", "/partial"), wait_until="domcontentloaded", timeout=GOTO1_TIMEOUT_MS)
return None
except Exception as e:
return str(e)
finally:
ends["first"] = time.perf_counter()
t_first = time.perf_counter()
if trace is not None:
trace.t0 = t_first
first = asyncio.ensure_future(goto1())
deadline = time.monotonic() + HEAR_RESPONSE_S
while "/partial" not in heard or "/partial" not in sites.arrived:
if first.done() or time.monotonic() > deadline:
break
await asyncio.sleep(0.02)
row = {"response_heard": "/partial" in heard}
second_error = None
second_status = None
t_second = None
if row["response_heard"]:
t_second = time.perf_counter()
if trace is not None:
trace.t_second = t_second
try:
response = await page.goto(sites.at("c.test", "/second"), wait_until="domcontentloaded", timeout=GOTO2_TIMEOUT_MS)
second_status = response.status if response is not None else None
except Exception as e:
second_error = str(e)
ends["second"] = time.perf_counter()
# the rest of the first response is sent only now: it can have ended only by being replaced (or, if it did not, by this)
sites.release.set()
try:
first_error = await asyncio.wait_for(first, 20)
except asyncio.TimeoutError:
first.cancel()
first_error = "(goto 1 still pending 20 s after the held response was let go)"
ends.setdefault("first", time.perf_counter())
await asyncio.sleep(SETTLE_S)
def at(stamp):
return None if stamp is None else _ms(stamp - t_first)
second_request = sites.arrived.get("/second")
row.update({
"partial_request_ms": at(sites.arrived.get("/partial")),
"partial_response_heard_ms": at(heard.get("/partial")),
"goto2_start_ms": at(t_second),
"second_request_arrived": second_request is not None,
"second_request_ms": at(second_request),
"second_request_after_goto2_start_ms": None if second_request is None or t_second is None else _ms(second_request - t_second),
"second_request_before_goto2_end": None if second_request is None or "second" not in ends else second_request <= ends["second"],
"goto1_end_ms": at(ends.get("first")),
"goto1_error": first_error,
"goto1_error_class": _error_class(first_error) if first_error is not None else "none (it returned)",
"goto2_outcome": None if t_second is None else ("error" if second_error is not None else "commit"),
"goto2_ms": None if t_second is None else _ms(ends["second"] - t_second),
"goto2_error": second_error,
"goto2_error_class": _error_class(second_error),
"goto2_status": second_status,
"url_after": page.url,
"requests_at_the_server": sorted(sites.arrived),
})
return row
async def _repetition(maker, index, binary, trace_on=False):
row = {"repetition": index, "browser": maker.name, "launched": False}
sites = Sites()
kind = maker(binary)
trace = Trace() if trace_on else None
try:
try:
browser = await asyncio.wait_for(kind.launch(), LAUNCH_S)
row["launched"] = True
try:
row["browser_version"] = browser.version
except Exception:
pass
except Exception as e:
row["launch_error"] = "%s: %s" % (type(e).__name__, e)
return row
try:
page = await browser.new_page()
row.update(await asyncio.wait_for(_scenario(page, sites, trace), REPETITION_S))
except Exception as e:
row["scenario_error"] = "%s: %s" % (type(e).__name__, e)
finally:
if trace is not None:
try:
row.update(trace.finish(row))
except Exception as e: # the trace never costs the measurement
row["trace_error"] = "%s: %s" % (type(e).__name__, e)
sites.close()
try:
await asyncio.wait_for(kind.close(), CLOSE_S)
except BaseException as e:
row["close_error"] = "%s: %s" % (type(e).__name__, e)
return row
# ---------------------------------------------------------------- the protocol trace
#: What the client hears, by method: the events of the navigations of the pages, of the requests of their documents, of their contexts, of the targets.
_TRACED = frozenset((
"Page.navigationStarted", "Page.navigationCommitted", "Page.navigationAborted", "Page.sameDocumentNavigation", "Page.eventFired",
"Page.frameAttached", "Page.frameDetached",
"Network.requestWillBeSent", "Network.responseReceived", "Network.requestFinished", "Network.requestFailed",
"Runtime.executionContextsCleared", "Runtime.executionContextCreated",
"Browser.attachedToTarget", "Browser.detachedFromTarget",
))
#: The commands that start, stop or replace a navigation: what the client SAID, with the reply of `Page.navigate` (the id of its navigation).
_SAID = frozenset(("Page.navigate", "Page.stop", "Page.reload", "Page.goBack", "Page.goForward", "Page.close"))
#: The params kept, per method (the rest is the bulk: headers, timing, security details).
_KEPT = {
"Page.navigationStarted": ("frameId", "navigationId"),
"Page.navigationCommitted": ("frameId", "navigationId", "url"),
"Page.navigationAborted": ("frameId", "navigationId", "errorText"),
"Page.sameDocumentNavigation": ("frameId", "url"),
"Page.eventFired": ("frameId", "name"),
"Page.frameAttached": ("frameId", "parentFrameId"),
"Page.frameDetached": ("frameId",),
"Network.requestWillBeSent": ("requestId", "frameId", "navigationId", "url", "redirectedFrom", "cause"),
"Network.responseReceived": ("requestId", "status", "fromCache"),
"Network.requestFinished": ("requestId",),
"Network.requestFailed": ("requestId", "errorCode"),
"Runtime.executionContextCreated": ("executionContextId", "auxData"),
"Runtime.executionContextsCleared": (),
"Browser.attachedToTarget": ("sessionId",),
"Browser.detachedFromTarget": ("sessionId",),
}
def _reduced(method, params):
out = {k: params[k] for k in _KEPT.get(method, ()) if params.get(k) is not None}
if method == "Browser.attachedToTarget":
info = params.get("targetInfo") or {}
out.update({k: info[k] for k in ("targetId", "type", "url") if k in info})
return out
class Trace:
"""Every protocol event of the traced kinds that the CLIENT receives, with the time it received it.
The hook is the public one of the connection of the core, `Connection.add_listener(fn)` (invisible_core.juggler.connection): `fn(method,
params, session)` is called on the reader thread of the connection for every event the engine sends, after the subscribers the page
registered earlier. The connection is found the way tests/_screencast_evidence.py finds it:
`page._impl_obj._connection._transport._server.object(guid).conn`. The commands that start, stop or replace a navigation are seen on the
same connection (`send_placed`, wrapped on THIS instance only and passing everything through unchanged; removed in `finish`), so that the id of
each goto is the one the engine answered to its `Page.navigate`. Nothing of src/ is touched.
Times are `time.perf_counter()`, the clock of the rest of the script; `finish` turns them into ms from the start of goto 1 (`t=0`).
Of the network only the requests of DOCUMENTS are kept: the ones that carry a navigation id (or whose cause says document), and what follows them.
"""
def __init__(self):
self.t0 = None # perf_counter of the start of goto 1
self.t_second = None # perf_counter of the start of goto 2
self._raw = [] # (perf_counter, method, params, session)
self._documents = set() # request ids of documents
self._conn = None
# -- the hook
def attach(self, page):
impl = page._impl_obj
conn = impl._connection._transport._server.object(impl._guid).conn
self._conn = conn
conn.add_listener(self._on_event)
original = conn.send_placed
raw = self._raw
def send_placed(method, params=None, session=None, timeout=30.0):
said = method in _SAID
if said:
raw.append((time.perf_counter(), "send " + method, dict(params or {}), session))
try:
answer = original(method, params, session, timeout)
except BaseException as failure:
if said:
raw.append((time.perf_counter(), "error " + method, {"error": str(failure)[:300]}, session))
raise
if said:
result = answer[0] if isinstance(answer, tuple) else answer
raw.append((time.perf_counter(), "reply " + method, dict(result) if isinstance(result, dict) else {}, session))
return answer
conn.send_placed = send_placed
def _on_event(self, method, params, session):
if method not in _TRACED:
return
now = time.perf_counter()
params = params if isinstance(params, dict) else {}
if method == "Network.requestWillBeSent":
if params.get("navigationId") or "document" in str(params.get("cause", "")).lower():
self._documents.add(params.get("requestId"))
elif method.startswith("Network.") and params.get("requestId") not in self._documents:
return
self._raw.append((now, method, params, session))
def detach(self):
conn, self._conn = self._conn, None
if conn is not None:
conn.remove_listener(self._on_event)
conn.__dict__.pop("send_placed", None) # back to the method of the class
# -- the result
def finish(self, row):
self.detach()
raw = sorted(self._raw, key=lambda item: item[0])
base = self.t0 if self.t0 is not None else (raw[0][0] if raw else 0.0)
events = []
for stamp, method, params, session in raw:
if method.startswith(("reply ", "error ")):
kept = dict(params)
elif method.startswith("send "):
kept = {k: params[k] for k in ("url", "frameId") if k in params}
else:
kept = _reduced(method, params)
if session:
kept["session"] = session
events.append([_ms(stamp - base), method, kept])
def navigate_id(path):
"""The id of the navigation the engine answered to the `Page.navigate` of `path`."""
sent = None
for _, method, params, _ in raw:
if method == "send Page.navigate":
sent = params.get("url", "")
elif method == "reply Page.navigate" and sent is not None and urlsplit(sent).path == path:
return params.get("navigationId")
return None
g1, g2 = navigate_id("/partial"), navigate_id("/second")
source = "the reply of Page.navigate"
if g1 is None or g2 is None:
# no reply to say it: the navigationStarted that follows each goto
started = [(stamp, params.get("navigationId")) for stamp, method, params, _ in raw if method == "Page.navigationStarted"]
after1 = [nid for stamp, nid in started if self.t0 is not None and stamp >= self.t0]
after2 = [nid for stamp, nid in started if self.t_second is not None and stamp >= self.t_second]
g1 = g1 or (after1[0] if after1 else None)
g2 = g2 or (after2[0] if after2 else None)
source = "the navigationStarted after each goto"
if row.get("goto2_outcome") is None:
esito = "no goto 2 (%s)" % ("scenario error" if row.get("response_heard") else "the response of the first was never heard")
elif row["goto2_outcome"] == "commit":
esito = "commit"
else:
esito = "hung" if row.get("goto2_error_class") == "timeout" else "error: %s" % row.get("goto2_error_class")
return {"goto1_id": g1, "goto2_id": g2, "goto_ids_from": source, "esito": esito, "events": events}
def _token(event, goto1, goto2):
"""One event as a short word: its method, the goto its navigation id belongs to (G1, G2, other) and what tells it apart."""
_, method, params = event
nid = params.get("navigationId")
who = None if not nid else "G1" if nid == goto1 else "G2" if nid == goto2 else "other"
short = method.replace("Page.", "").replace("Network.", "net.").replace("Runtime.", "").replace("Browser.", "")
path = urlsplit(params["url"]).path if params.get("url") else None
detail = [d for d in (who, path, params.get("errorText") or params.get("errorCode"), params.get("status"), params.get("name")) if d is not None]
return "%s(%s)" % (short, " ".join(str(d) for d in detail)) if detail else short
def trace_sequences(rows):
"""Per outcome (hung, committed, other), the sequences of the events after the `navigationStarted` of goto 2, most frequent first:
{outcome: [(count, [[word, ms after that navigationStarted, repeats], ...])]}. The ms are those of the first repetition with that sequence."""
groups = {}
for r in rows:
events, g1, g2 = r.get("events"), r.get("goto1_id"), r.get("goto2_id")
if not events or g2 is None:
continue
kind = {"hung": "hung", "commit": "good (committed)"}.get(r.get("esito"), r.get("esito") or "?")
start = next((i for i, e in enumerate(events) if e[1] == "Page.navigationStarted" and e[2].get("navigationId") == g2), None)
if start is None:
groups.setdefault(kind + ", no navigationStarted for goto 2", {}).setdefault((), [0, []])[0] += 1
continue
t_start = events[start][0]
folded = []
for e in events[start + 1:]:
if e[1] in ("send Page.navigate", "reply Page.navigate"):
continue # said once per goto: not what the browser does after
word = _token(e, g1, g2)
if folded and folded[-1][0] == word: # consecutive repeats collapse: "x3"
folded[-1][2] += 1
else:
folded.append([word, round(e[0] - t_start, 1), 1])
slot = groups.setdefault(kind, {}).setdefault(tuple(w for w, _, _ in folded), [0, folded])
slot[0] += 1
return {kind: sorted(((n, f) for n, f in seqs.values()), key=lambda item: -item[0]) for kind, seqs in groups.items()}
def render_trace(sequences, top=3):
out = []
for kind, seqs in sorted(sequences.items()):
out.append("== trace, repetitions %s: %d" % (kind, sum(n for n, _ in seqs)))
for n, folded in seqs[:top]:
out.append(" x%d, after the navigationStarted of goto 2 (G1 = goto 1, G2 = goto 2):" % n)
if not folded:
out.append(" (nothing)")
for word, at, count in folded:
out.append(" +%8.1f ms %s%s" % (at, word, " x%d" % count if count > 1 else ""))
return "\n".join(out)
# ---------------------------------------------------------------- the summary
def _first_line(message):
return (message or "").strip().splitlines()[0][:160] if message else None
def summarise(rows):
measured = [r for r in rows if "second_request_arrived" in r]
gotos2 = [r for r in measured if r.get("goto2_outcome")]
ms2 = [r["goto2_ms"] for r in gotos2]
asked = [r["second_request_after_goto2_start_ms"] for r in measured if r.get("second_request_after_goto2_start_ms") is not None]
def median_max(values):
return {"median": round(statistics.median(values), 1), "max": round(max(values), 1)} if values else {"median": None, "max": None}
return {
"repetitions": len(rows),
"launched": sum(1 for r in rows if r.get("launched")),
"measured": len(measured),
"never_heard_the_response_of_the_first": sum(1 for r in measured if not r["response_heard"]),
"second_request_arrived": {"yes": sum(1 for r in measured if r["second_request_arrived"]),
"no": sum(1 for r in measured if not r["second_request_arrived"])},
"second_request_arrived_after_goto2_ended": sum(1 for r in measured if r.get("second_request_before_goto2_end") is False),
"goto2": {"commit": sum(1 for r in gotos2 if r["goto2_outcome"] == "commit"),
"error": sum(1 for r in gotos2 if r["goto2_outcome"] == "error")},
"goto2_errors": dict(Counter(_first_line(r["goto2_error"]) for r in gotos2 if r["goto2_error"])),
"goto1_end": dict(Counter(r["goto1_error_class"] for r in measured if "goto1_error_class" in r)),
"goto1_errors": dict(Counter(_first_line(r["goto1_error"]) for r in measured if r.get("goto1_error"))),
"goto2_ms": median_max(ms2),
"second_request_after_goto2_start_ms": median_max(asked),
"launch_errors": dict(Counter(_first_line(r["launch_error"]) for r in rows if r.get("launch_error"))),
"scenario_errors": dict(Counter(_first_line(r["scenario_error"]) for r in rows if r.get("scenario_error"))),
}
def render(name, summary):
out = ["== %s: %d repetitions, %d launched, %d measured" % (name, summary["repetitions"], summary["launched"], summary["measured"])]
s = summary["second_request_arrived"]
out.append(" /second reached the server: yes %d, no %d (of the yes, %d after goto 2 had ended)"
% (s["yes"], s["no"], summary["second_request_arrived_after_goto2_ended"]))
g = summary["goto2"]
out.append(" goto 2: committed %d, error %d" % (g["commit"], g["error"]))
out.append(" goto 2 ms: median %(median)s, max %(max)s" % summary["goto2_ms"])
out.append(" /second request, ms after goto 2 started: median %(median)s, max %(max)s" % summary["second_request_after_goto2_start_ms"])
out.append(" goto 1 ended as: %s" % (", ".join("%s x%d" % kv for kv in sorted(summary["goto1_end"].items())) or "-"))
for label, key in (("goto 2 errors", "goto2_errors"), ("goto 1 errors", "goto1_errors"), ("launch errors", "launch_errors"),
("scenario errors", "scenario_errors")):
for message, count in summary[key].items():
out.append(" %s: x%d %s" % (label, count, message))
if summary["never_heard_the_response_of_the_first"]:
out.append(" the client never heard the response of the first goto in %d repetition(s)"
% summary["never_heard_the_response_of_the_first"])
return "\n".join(out)
# ---------------------------------------------------------------- the run
def _versions():
found = {}
for module, label in (("playwright", "playwright"), ("invisible_playwright", "invisible_playwright"), ("invisible_core", "invisible_core")):
try:
found[label] = __import__(module).__version__
except Exception:
found[label] = None
try:
from importlib.metadata import version
found["playwright"] = version("playwright")
except Exception:
pass
return found
def _declare_the_lab(directory):
"""Where an e2e launch leaves from is declared, as the e2e suite does (tests/_lab_egress.py): no service of the internet is asked."""
sys.path.insert(0, str(ROOT / "tests"))
import pytest
import _lab_egress
patch = pytest.MonkeyPatch()
_lab_egress.install(patch, Path(directory))
return patch
async def _run(makers, repetitions, binary, out_dir, trace_on=False):
rows = {m.name: [] for m in makers}
for index in range(1, repetitions + 1):
for maker in makers: # alternate: ours, stock, ours, stock, ...
row = await _repetition(maker, index, binary, trace_on)
rows[maker.name].append(row)
shown = ["launched", "second_request_arrived", "second_request_after_goto2_start_ms", "goto1_error_class",
"goto2_outcome", "goto2_ms", "launch_error", "scenario_error"]
if trace_on:
shown += ["esito", "goto1_id", "goto2_id", "trace_error"]
print("[%s %d/%d] %s" % (maker.name, index, repetitions, json.dumps({k: row.get(k) for k in shown}, default=str)), flush=True)
system = {"win32": "windows", "linux": "linux", "darwin": "macos"}.get(sys.platform, sys.platform)
result = {}
for maker in makers:
summary = summarise(rows[maker.name])
payload = {
"meta": {"browser": maker.name, "system": system, "platform": platform.platform(), "python": sys.version.split()[0],
"versions": _versions(), "binary": binary if maker.name == "invisible" else "the Firefox of `playwright install firefox`",
"prefs": FISSION_ON, "hosts": "a.test, b.test, c.test -> the local server, by network.dns.localDomains",
"goto1_timeout_ms": GOTO1_TIMEOUT_MS, "goto2_timeout_ms": GOTO2_TIMEOUT_MS,
"trace": trace_on, "fresh_browser_per_repetition": True, "browsers_alternate": len(makers) > 1,
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())},
"summary": summary,
"rows": rows[maker.name],
}
if trace_on:
payload["trace_sequences"] = {
kind: [{"repetitions": n, "events": [{"word": w, "ms_after_goto2_started": at, "times": c} for w, at, c in folded]}
for n, folded in seqs]
for kind, seqs in trace_sequences(rows[maker.name]).items()}
path = Path(out_dir) / ("second-goto-%s%s-%s.json" % ("trace-" if trace_on else "", maker.name, system))
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8")
print("written", path, flush=True)
result[maker.name] = summary
print()
for maker in makers:
print(render(maker.name, result[maker.name]), flush=True)
if trace_on:
print(render_trace(trace_sequences(rows[maker.name])), flush=True)
return result
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--browser", choices=("both", "invisible", "stock"), default="both",
help="which browser: both alternate, repetition by repetition (default)")
parser.add_argument("--binary", default=os.environ.get("INVPW_BINARY_PATH") or os.environ.get("FF"),
help="the engine of invisible_playwright (default: $INVPW_BINARY_PATH, then $FF)")
parser.add_argument("--repetitions", type=int, default=REPETITIONS, help="per browser (default %d)" % REPETITIONS)
parser.add_argument("--out-dir", default="second-goto", help="where the JSON of each browser is written")
parser.add_argument("--trace", action="store_true",
help="record, in every repetition, the protocol events the client hears with their time (needs --browser invisible)")
args = parser.parse_args(argv)
if args.trace and args.browser != "invisible":
parser.error("--trace records the protocol of OUR browser: say --browser invisible")
makers = {"both": [_Ours, _Stock], "invisible": [_Ours], "stock": [_Stock]}[args.browser]
if _Ours in makers and not args.binary:
parser.error("the engine of invisible_playwright is needed: --binary, or $INVPW_BINARY_PATH / $FF")
with tempfile.TemporaryDirectory(prefix="second-goto-") as lab:
patch = _declare_the_lab(lab) if _Ours in makers else None
try:
result = asyncio.run(_run(makers, args.repetitions, args.binary, args.out_dir, args.trace))
finally:
if patch is not None:
patch.undo()
# the exit code says the script could measure, not what it measured
dead = [name for name, s in result.items() if s["measured"] == 0]
if dead:
print("::error::no repetition of %s could be measured" % ", ".join(dead), flush=True)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+363
View File
@@ -0,0 +1,363 @@
"""A pytest plugin for a HUNT, never for a gate: the protocol trace of every test it runs, one JSON per test.
python -m pytest -m e2e -p scripts.hunt_trace_plugin tests/test_control_a_selects_all_in_a_field_e2e.py
(run from the root of the repository, or with it on PYTHONPATH; the plugin is loaded with `-p` and is not in tests/conftest.py, so no other
run sees it.) Where the JSON go: `$HUNT_TRACE_DIR` (default `hunt-trace`); `$HUNT_TRACE_TAG` is a label of the run (the round, the copy) that is
written into every file name and every JSON.
Why it exists. `Page.set_content` failed, rarely, with "the caller's world never appeared for frame mainframe-N - did you call install()?
Worlds seen: ['']" (tests/test_control_a_selects_all_in_a_field_e2e.py). The message is raised by `InjectedScript.caller_context` of
invisible_core (juggler/injected.py) after 30 s of waiting for the context named `__ctx_caller__` of that frame, and the one thing that makes
that context exist is `InjectedScript.install()`, which sends `Page.setInitScripts` with a script per world (`__ctx_aux__`, `__ctx_caller__`
with worldKind "caller"): the engine creates the world when a document is created in the frame. `install()` is called once, in
`PageDispatcher._build`, after the events the page missed are replayed. This plugin records what the browser said and what the server said
to it, with times, so that a red run says in which order they happened.
What it records, per test (a time is `time.perf_counter()` in this process, written as ms from the start of the test):
* events the engine sent (heard by a listener of every `Connection`, registered at its birth): Page.navigationStarted / navigationCommitted /
navigationAborted / sameDocumentNavigation / frameAttached / frameDetached / eventFired, Runtime.executionContextsCleared /
executionContextCreated / executionContextDestroyed (frameId, world name, id), Browser.attachedToTarget / detachedFromTarget; the ones
delivered again to a page built after them (`BrowserDispatcher.replay`) carry `replay: true`;
* the commands the server sent (`Connection.send_placed`, wrapped on the CLASS, passing everything through): the command, its reduced
parameters (the worlds of `Page.setInitScripts`, the context of a `Runtime.evaluate`, the start of its expression) and its reply or error
with the time it took;
* marks: the phases of the test, `InjectedScript.install` (start, end), `InjectedScript.caller_context` (start, end or error, with the worlds
known for the frame at that moment), and `FrameDispatcher.op_set_content` (start, end or error), which is where `set_content` goes;
* the outcome of each phase of the test and the text of its failure.
Both modes of the `browser` fixture are traced: the in-process one and the stock-client one, because in both the server (JugglerServer) runs
in THIS process, on its own threads, and its `Connection` is the one hooked. What the stock client (the driver, a node process) says to
it is not seen; what the server does is. Nothing of src/ is touched: the hooks are installed at run time on the classes, and a hook that cannot
be installed (a name that moved) says so in the JSON (`hook_errors`) and the test goes on.
"""
from __future__ import annotations
import json
import os
import platform
import re
import threading
import time
import pytest
#: Events kept, by method; the rest of what the engine says (network, console, screencast) is not what this hunt asks.
_EVENTS = {
"Page.navigationStarted": ("frameId", "navigationId"),
"Page.navigationCommitted": ("frameId", "navigationId", "url"),
"Page.navigationAborted": ("frameId", "navigationId", "errorText"),
"Page.sameDocumentNavigation": ("frameId", "url"),
"Page.eventFired": ("frameId", "name"),
"Page.frameAttached": ("frameId", "parentFrameId"),
"Page.frameDetached": ("frameId",),
"Runtime.executionContextsCleared": (),
"Runtime.executionContextCreated": ("executionContextId",),
"Runtime.executionContextDestroyed": ("executionContextId",),
"Browser.attachedToTarget": (),
"Browser.detachedFromTarget": ("sessionId",),
}
#: Parameters kept of a command; a long text is cut.
_COMMAND_KEYS = ("frameId", "executionContextId", "url", "worldName", "name", "targetId", "browserContextId")
_CUT = 90
_FAILURE_CUT = 4000
_lock = threading.Lock()
_events: list = [] # [perf_counter, kind, method, detail, connection, session]
_state = {"connections": 0, "test": None, "hook_errors": [], "installed": False}
_replaying = threading.local()
def _now():
return time.perf_counter()
def _add(kind, method, detail, conn=None, session=None):
try:
row = (_now(), kind, method, detail, conn, session)
with _lock:
_events.append(row)
except Exception: # a recorder never costs the test
pass
def _cut(value):
text = str(value)
return text if len(text) <= _CUT else text[:_CUT] + "..."
def _event_detail(method, params):
params = params if isinstance(params, dict) else {}
out = {k: params[k] for k in _EVENTS[method] if params.get(k) is not None}
if method == "Runtime.executionContextCreated":
aux = params.get("auxData") or {}
out["frameId"] = aux.get("frameId")
out["world"] = aux.get("name") or ""
elif method == "Browser.attachedToTarget":
info = params.get("targetInfo") or {}
out.update({k: info[k] for k in ("targetId", "type", "url") if info.get(k) is not None})
if params.get("sessionId"):
out["sessionId"] = params["sessionId"]
if getattr(_replaying, "on", False):
out["replay"] = True
return out
def _command_detail(method, params):
params = params if isinstance(params, dict) else {}
out = {k: _cut(params[k]) for k in _COMMAND_KEYS if params.get(k) is not None}
if method == "Page.setInitScripts":
out["worlds"] = [[s.get("worldName"), s.get("worldKind"), len(s.get("script") or "")]
for s in params.get("scripts") or [] if isinstance(s, dict)]
for key in ("expression", "functionDeclaration"):
if params.get(key):
out[key] = _cut(params[key])
return out
# ---------------------------------------------------------------- the hooks on the classes
def _hook_connection():
"""Every Connection hears its events through one listener, registered when it is built (before its reader thread starts, so the first
events are not missed), and every command goes through `send_placed`, wrapped on the class."""
from invisible_core.juggler import connection as module
base, cls = module.EventListeners, module.Connection
original_init = base.__init__
original_send = cls.send_placed
def init(self, *args, **kwargs):
original_init(self, *args, **kwargs)
with _lock:
_state["connections"] += 1
label = "c%d" % _state["connections"]
self._hunt_label = label
def listen(method, params, session, _label=label):
if method in _EVENTS:
_add("event", method, _event_detail(method, params), _label, session)
self.add_listener(listen)
def send_placed(self, method, params=None, session=None, timeout=30.0):
label = getattr(self, "_hunt_label", None)
_add("send", method, _command_detail(method, params), label, session)
started = _now()
try:
answer = original_send(self, method, params, session, timeout)
except BaseException as failure:
_add("error", method, {"error": _cut(failure), "ms": round((_now() - started) * 1000, 1)}, label, session)
raise
_add("reply", method, {"ms": round((_now() - started) * 1000, 1)}, label, session)
return answer
base.__init__ = init
cls.send_placed = send_placed
def _worlds_of(injected, frame_id):
try:
return sorted("%s=%s" % (n or "''", v) for (f, n), v in list(injected.contexts.items()) if f == frame_id)
except Exception as failure:
return ["(unreadable: %s)" % failure]
def _hook_injected():
from invisible_core.juggler import injected as module
cls = module.InjectedScript
install, caller_context = cls.install, cls.caller_context
def label(self):
return getattr(self.c, "_hunt_label", None)
def hooked_install(self):
_add("mark", "install.start", {}, label(self), self.session)
try:
return install(self)
except BaseException as failure:
_add("mark", "install.error", {"error": _cut(failure)}, label(self), self.session)
raise
finally:
_add("mark", "install.end", {}, label(self), self.session)
def hooked_caller_context(self, frame_id, *args, **kwargs):
_add("mark", "caller_context.start", {"frameId": frame_id, "worlds": _worlds_of(self, frame_id)}, label(self), self.session)
try:
context = caller_context(self, frame_id, *args, **kwargs)
except BaseException as failure:
_add("mark", "caller_context.error",
{"frameId": frame_id, "error": _cut(failure), "worlds": _worlds_of(self, frame_id)}, label(self), self.session)
raise
_add("mark", "caller_context.end", {"frameId": frame_id, "executionContextId": context}, label(self), self.session)
return context
cls.install = hooked_install
cls.caller_context = hooked_caller_context
def _hook_server():
from invisible_playwright._juggler import server as module
frame_cls = module.FrameDispatcher
set_content = frame_cls.op_set_content
browser_cls = module.BrowserDispatcher
replay = browser_cls.replay
def hooked_set_content(self, params):
injected = getattr(self, "injected", None)
session = getattr(injected, "session", None)
conn = getattr(getattr(injected, "c", None), "_hunt_label", None)
frame_id = getattr(self, "frame_id", None)
detail = {"frameId": frame_id, "worlds": _worlds_of(injected, frame_id) if injected is not None else None,
"delivered": getattr(getattr(injected, "c", None), "delivered", None)}
_add("mark", "set_content.start", detail, conn, session)
try:
result = set_content(self, params)
except BaseException as failure:
_add("mark", "set_content.error", {"frameId": frame_id, "error": _cut(failure)}, conn, session)
raise
_add("mark", "set_content.end", {"frameId": frame_id}, conn, session)
return result
def hooked_replay(self, session, deliver):
_replaying.on = True
try:
return replay(self, session, deliver)
finally:
_replaying.on = False
frame_cls.op_set_content = hooked_set_content
browser_cls.replay = hooked_replay
def _install_hooks():
if _state["installed"]:
return
_state["installed"] = True
for hook in (_hook_connection, _hook_injected, _hook_server):
try:
hook()
except Exception as failure: # the hunt goes on without that part, and says so
_state["hook_errors"].append("%s: %s: %s" % (hook.__name__, type(failure).__name__, failure))
# ---------------------------------------------------------------- the tests
def pytest_configure(config):
_install_hooks()
def _safe(name):
return re.sub(r"[^A-Za-z0-9._-]+", "_", name)[-120:]
class _Current:
def __init__(self, item):
self.item = item
self.start = _now()
with _lock:
self.first = len(_events)
self.phases = {}
self.failure = {}
def _mode(item):
callspec = getattr(item, "callspec", None)
params = getattr(callspec, "params", {}) if callspec else {}
return params.get("browser") # "in-process" or "stock-client" (the fixture's param)
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item, nextitem):
current = _state["test"] = _Current(item)
_add("mark", "test.start", {"nodeid": item.nodeid})
try:
yield
finally:
_add("mark", "test.end", {})
try:
_write(current)
except Exception as failure:
_state["hook_errors"].append("write: %s: %s" % (type(failure).__name__, failure))
_state["test"] = None
def _phase_marks(phase):
_add("mark", "test.%s.start" % phase, {})
outcome = yield
_add("mark", "test.%s.end" % phase, {"raised": outcome.excinfo is not None})
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_setup(item):
yield from _phase_marks("setup")
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_call(item):
yield from _phase_marks("call")
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_teardown(item):
yield from _phase_marks("teardown")
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
current = _state["test"]
if current is None:
return
report = outcome.get_result()
current.phases[call.when] = report.outcome
if report.outcome in ("failed",) or (report.outcome == "skipped" and call.when == "setup"):
text = str(report.longrepr)
current.failure[call.when] = text if len(text) <= _FAILURE_CUT else text[:_FAILURE_CUT] + "\n..."
def _verdict(phases):
if phases.get("setup") == "failed" or phases.get("teardown") == "failed":
return "error"
if phases.get("call") == "failed":
return "failed"
if phases.get("setup") == "skipped" or phases.get("call") == "skipped":
return "skipped"
return "passed" if phases.get("call") == "passed" else "unknown"
_sequence = {"n": 0}
def _write(current):
with _lock:
rows = list(_events[current.first:])
_sequence["n"] += 1
number = _sequence["n"]
base = current.start
events = [[round((t - base) * 1000, 2), kind, method, detail, conn, session]
for t, kind, method, detail, conn, session in rows]
item = current.item
tag = os.environ.get("HUNT_TRACE_TAG", "")
payload = {
"nodeid": item.nodeid,
"mode": _mode(item),
"outcome": _verdict(current.phases),
"phases": current.phases,
"failure": current.failure,
"tag": tag,
"system": platform.system(),
"pid": os.getpid(),
"sequence": number,
"hook_errors": list(_state["hook_errors"]),
"columns": ["ms_from_test_start", "kind", "method", "detail", "connection", "session"],
"events": events,
}
out = os.environ.get("HUNT_TRACE_DIR", "hunt-trace")
os.makedirs(out, exist_ok=True)
name = "%s%s-%04d-%s.json" % (_safe(tag) + "-" if tag else "", os.getpid(), number, _safe(item.nodeid.split("::", 1)[-1]))
with open(os.path.join(out, name), "w", encoding="utf-8", newline="\n") as handle:
json.dump(payload, handle, indent=1, default=str)
handle.write("\n")
+93
View File
@@ -0,0 +1,93 @@
"""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), and 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 until every other browser had answered). A machine that is
slow stretches every duration and changes none of these.
``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",)),
)
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 did the same while the removal of the closing browser's profile was held. ``gate`` says how that hold ended: ``reached``
(the removal ran in the window of the close), ``released_by``: ``answered`` (every other browser had answered a call that began
after the removal began: the loop was free while the removal ran) 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]))
return None
+736
View File
@@ -0,0 +1,736 @@
"""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/'\"<>)\\]*)?")
_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)):
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}
debt = [{"file": v.file, "scope": v.scope, "rule": v.rule, "nth": v.nth, "class": v.klass, "reason": 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}
+173
View File
@@ -0,0 +1,173 @@
"""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 connections of the road after the birth that are not an ASSOCIATE: ONE, the CONNECT to the DoH that carries the
#: question, and none when the connection that loaded the page is still open and carries it. A connection for every question, or a
#: second one, is a handshake nobody needs.
CONNECTS_AFTER_THE_BIRTH = 1
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]], 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). Every control connection that carried a CONNECT (or any command but ASSOCIATE) costs its greeting
and its command (and the authentication); every DoH question one; every distinct Allocate transaction one."""
commands = [r for r in requests if r[2] in ("connect", "other") and born <= r[0] <= allocated_at]
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(commands) > CONNECTS_AFTER_THE_BIRTH:
found.append("%d SOCKS5 control connections with a command other than ASSOCIATE after the birth (%s), the design needs %d at most"
% (len(commands), [r[3] for r in commands], 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), list(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(commands) * 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]],
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) 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: one SOCKS5 control connection 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. An ASSOCIATE is no exchange of this road: 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)."""
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
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 x %d, %d DoH question, %d Allocate transactions): %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"))
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]],
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)
+16 -8
View File
@@ -161,7 +161,7 @@ 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
@@ -180,13 +180,13 @@ def spin_trial(observer, frame, spin_ms=SPIN_MS):
while (performance.now() < end) { /* spin */ }
window.__spin = [start, Date.now()];
}, 50); }""", spin_ms)
observer.page.wait_for_timeout(spin_ms + 800)
ticks = observer.evaluate("() => { clearInterval(window.__tick); return window.__ticks; }")
# 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 wait_for_value(page, read, seconds=20.0):
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()
@@ -222,21 +222,29 @@ def other_process_proved(trials):
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):
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. Up to ``TRIALS`` spins (the first that shows ticks inside it is enough; a healthy machine needs one)."""
spins. Spins until one shows ticks inside it (a healthy machine needs one), for ``seconds``."""
trials = []
for _ in range(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, TRIALS, SPIN_MS,
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]))
+130
View File
@@ -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()
+29
View File
@@ -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)
+14
View File
@@ -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" % (
+48 -2
View File
@@ -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.
@@ -174,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
@@ -193,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
@@ -248,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)
@@ -259,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)
@@ -309,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
@@ -434,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)
@@ -487,6 +532,7 @@ class Gateway:
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
+33 -5
View File
@@ -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]
@@ -275,8 +289,11 @@ const finish = (s) => { status = s; window.__result.status = s; window.__done =
document.addEventListener('DOMContentLoaded', () => {
mark('dom');
// 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.
// 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');
@@ -285,13 +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' || window.__result.srflx) 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');
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()
+47
View File
@@ -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:
@@ -151,6 +163,41 @@ def _offline_session_geo(request, monkeypatch):
monkeypatch.setattr(_session, "session_geo", lambda *_a, **_k: geo)
@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."""
+243
View File
@@ -0,0 +1,243 @@
{
"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_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_screenshot_of_text_returns_linux_e2e.py", "scope": "test_a_screenshot_of_a_page_with_text_returns", "rule": "bound", "nth": 1, "kind": "hang-detector", "reason": "The limit is the timeout of the screenshot call itself (the same constant, 30 s), so the assertion only ends a call that hangs and judges no speed."},
{"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": "_doh_servers.py", "scope": "DohGateway._connect", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "_http_proxy.py", "scope": "HttpProxy._connect", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "_http_proxy.py", "scope": "HttpProxy._forward", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "_ports.py", "scope": "who_holds", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "_realness_support.py", "scope": "ExitGateway._connect", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "_socks_servers.py", "scope": "Gateway._open_upstream", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "_socks_servers.py", "scope": "Socks5TcpOnly._handle", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"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."},
{"file": "test_a_left_documents_body_is_evicted_e2e.py", "scope": "test_nothing_else_is_lost_when_the_bodies_go", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_left_documents_body_is_evicted_e2e.py", "scope": "test_nothing_else_is_lost_when_the_bodies_go", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_a_left_documents_body_is_evicted_e2e.py", "scope": "test_nothing_else_is_lost_when_the_bodies_go", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_a_left_documents_body_is_evicted_e2e.py", "scope": "test_the_body_of_a_document_the_tab_left_is_evicted", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_left_documents_body_is_evicted_e2e.py", "scope": "test_the_body_of_a_document_the_tab_left_is_evicted", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_a_page_that_moves_on_e2e.py", "scope": "test_expect_reads_the_state_it_names", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_page_that_moves_on_e2e.py", "scope": "test_expect_reads_the_state_it_names", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_a_page_that_moves_on_e2e.py", "scope": "test_expect_reads_the_state_it_names", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "scope": "test_a_listener_registered_in_the_page_handler_hears_the_load_of_the_popup.body", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "scope": "test_a_listener_registered_in_the_page_handler_hears_the_load_of_the_popup.body.on_page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "scope": "test_a_slow_popup_is_reported_with_the_address_of_its_destination.body", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_popup_of_a_link_reaches_the_client_e2e.py", "scope": "_check", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_request_says_what_it_is_e2e.py", "scope": "test_each_kind_of_request_is_named_by_the_engine", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_request_says_what_it_is_e2e.py", "scope": "test_each_kind_of_request_is_named_by_the_engine", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "scope": "test_ten_tiny_downloads_of_each_size_are_saved_through_a_served_browser", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "scope": "_assert_a_new_page_with_a_new_worker", "rule": "sleep", "nth": 1, "class": "A", "reason": "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."},
{"file": "test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "scope": "test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same", "rule": "sleep", "nth": 1, "class": "A", "reason": "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."},
{"file": "test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "scope": "test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_accept_language_on_the_wire_e2e.py", "scope": "test_every_request_of_a_session_carries_the_retail_accept_language", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_actions_without_a_point.py", "scope": "test_hidden_elements_take_the_actions_playwright_allows", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_actions_without_a_point.py", "scope": "test_hidden_elements_take_the_actions_playwright_allows", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_actions_without_a_point.py", "scope": "test_hidden_elements_take_the_actions_playwright_allows", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_add_script_tag.py", "scope": "page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_an_isolated_page_and_the_next_e2e.py", "scope": "test_reads_after_the_isolated_page_answer", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_an_isolated_page_and_the_next_e2e.py", "scope": "test_reads_after_the_isolated_page_answer", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_an_isolated_page_and_the_next_e2e.py", "scope": "test_reads_after_the_isolated_page_answer", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_an_isolated_page_and_the_next_e2e.py", "scope": "test_reads_after_the_isolated_page_answer", "rule": "timeout", "nth": 4, "class": "F", "reason": "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."},
{"file": "test_caller_world_handles_e2e.py", "scope": "page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_context_locale_e2e.py", "scope": "test_a_context_locale_reaches_navigator_intl_and_the_header", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_context_locale_e2e.py", "scope": "test_a_context_locale_reaches_navigator_intl_and_the_header", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_context_locale_e2e.py", "scope": "test_a_context_locale_reaches_navigator_intl_and_the_header", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_context_locale_e2e.py", "scope": "test_a_context_locale_reaches_navigator_intl_and_the_header", "rule": "timeout", "nth": 4, "class": "F", "reason": "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."},
{"file": "test_context_locale_e2e.py", "scope": "test_a_context_locale_reaches_navigator_intl_and_the_header", "rule": "timeout", "nth": 5, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_cross_origin_iframe_content_frame_resolves", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_cross_origin_iframe_dispatch_event_click_works", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_cross_origin_iframe_evaluate_returns_real_values", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_cross_origin_iframe_frame_locator_resolves_button", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_cross_origin_iframe_frame_locator_resolves_button", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_cross_origin_iframe_url_appears_in_page_frames", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_the_geometry_invariant_holds_inside_a_nested_frame", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_cross_origin_iframe.py", "scope": "test_the_iframe_runs_in_another_process", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_download_is_intercepted_e2e.py", "scope": "test_a_clicked_download_is_reported_and_saved", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_download_is_intercepted_e2e.py", "scope": "test_a_navigation_that_ends_in_a_download_is_reported", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_file_chooser.py", "scope": "test_a_hidden_input_takes_files_by_selector", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_file_chooser.py", "scope": "test_a_hidden_input_takes_files_through_its_chooser", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_file_chooser.py", "scope": "test_a_hidden_input_takes_files_through_its_chooser", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_file_chooser.py", "scope": "test_expect_file_chooser_receives_the_event", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_file_chooser.py", "scope": "test_the_chosen_files_arrive_at_the_page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_fission_iframe_crash_e2e.py", "scope": "test_the_crash_of_an_iframe_s_process_leaves_the_tab", "rule": "count", "nth": 1, "class": "E", "reason": "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)."},
{"file": "test_fission_strategy1_bench.py", "scope": "page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_fission_strategy1_bench.py", "scope": "page", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_fontconfig_reads_nothing_of_the_host_linux_e2e.py", "scope": "test_a_killed_stand_in_leaves_neither_strace_nor_the_browser", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_goto_networkidle_after_spa_e2e.py", "scope": "test_networkidle_goto_leaves_a_quiet_spa_and_answers_for_the_new_page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_goto_networkidle_after_spa_e2e.py", "scope": "test_networkidle_goto_leaves_a_quiet_spa_and_answers_for_the_new_page", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_goto_script_redirect_e2e.py", "scope": "test_goto_returns_on_the_page_that_replaced_itself_from_script", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_goto_script_redirect_e2e.py", "scope": "test_goto_returns_on_the_page_that_replaced_itself_from_script", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_goto_to_the_same_url_e2e.py", "scope": "test_a_goto_to_the_address_the_page_is_at_ends_every_time.scenario", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_goto_to_the_same_url_e2e.py", "scope": "test_a_goto_to_the_address_the_page_is_at_ends_every_time.scenario", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_goto_to_the_same_url_e2e.py", "scope": "test_a_goto_to_the_same_address_with_a_query_ends_the_second_time_too.scenario", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_goto_to_the_same_url_e2e.py", "scope": "test_a_goto_to_the_same_address_with_a_query_ends_the_second_time_too.scenario", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_http3_through_the_proxy_e2e.py", "scope": "test_a_page_behind_an_http_proxy_reads_h2_on_every_visit_and_loads_without_delay.ProxyToTheServer._connect", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_ignore_https_errors_e2e.py", "scope": "test_ignore_https_errors_loads_a_self_signed_page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_juggler_actions.py", "scope": "test_the_lifecycle_WAITS_for_an_element_that_appears_later", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_juggler_transport.py", "scope": "test_going_BACK_then_FORWARD_leaves_the_page_readable", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_juggler_transport.py", "scope": "test_going_BACK_then_FORWARD_leaves_the_page_readable", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_juggler_transport.py", "scope": "test_going_BACK_then_FORWARD_leaves_the_page_readable", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_juggler_transport.py", "scope": "test_going_back_over_a_page_the_script_left_without_a_gesture", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_juggler_transport.py", "scope": "test_going_back_over_a_page_the_script_left_without_a_gesture", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_mouse.py", "scope": "test_hover_triggers_mouseenter", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_navigation_response.py", "scope": "test_navigation_answers_with_a_real_response", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_nested_frame_actions.py", "scope": "_timed", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_nested_frame_actions.py", "scope": "_timed", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_networkidle_reaches_the_client_e2e.py", "scope": "test_the_client_side_networkidle_waits_resolve", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_networkidle_reaches_the_client_e2e.py", "scope": "test_the_client_side_networkidle_waits_resolve", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_networkidle_reaches_the_client_e2e.py", "scope": "test_the_client_side_networkidle_waits_resolve", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_networkidle_reaches_the_client_e2e.py", "scope": "test_the_client_side_networkidle_waits_resolve", "rule": "timeout", "nth": 4, "class": "F", "reason": "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."},
{"file": "test_networkidle_reaches_the_client_e2e.py", "scope": "test_the_client_side_networkidle_waits_resolve", "rule": "timeout", "nth": 5, "class": "F", "reason": "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."},
{"file": "test_networkidle_reaches_the_client_e2e.py", "scope": "test_the_client_side_networkidle_waits_resolve", "rule": "timeout", "nth": 6, "class": "F", "reason": "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."},
{"file": "test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py", "scope": "test_the_native_sink_hears_a_native_lookup", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_oop_frame_element.py", "scope": "oop_page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_oop_frame_element.py", "scope": "oop_page", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_oop_frame_geometry.py", "scope": "open_page.open_", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_oop_frame_geometry.py", "scope": "open_page.open_", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_page_number_follows_the_call.py", "scope": "_Page.wait_until_ready", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_page_number_follows_the_call.py", "scope": "_new_page_in_thread", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_popup_destinations_e2e.py", "scope": "test_a_popup_to_a_slow_page_is_announced_when_it_answers", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_popups_reach_the_client_e2e.py", "scope": "_the_process_case_in", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_popups_reach_the_client_e2e.py", "scope": "_the_process_case_in", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_popups_reach_the_client_e2e.py", "scope": "test_a_popup_reaches_the_client", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_popups_reach_the_client_e2e.py", "scope": "test_a_popup_reaches_the_client", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_proxy_socks_auth_e2e.py", "scope": "_Socks5AuthRecorder._handle", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_resolver_race_e2e.py", "scope": "_beside_a_proxied_context", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_resolver_race_e2e.py", "scope": "_beside_a_proxied_context", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_resolver_race_e2e.py", "scope": "_beside_a_proxied_context", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_resolver_race_e2e.py", "scope": "_navigate_at_once", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_route_e2e.py", "scope": "test_a_route_guard_sees_and_stops_every_post", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_route_e2e.py", "scope": "test_a_route_guard_sees_and_stops_every_post", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_route_post_data_e2e.py", "scope": "test_a_routed_post_carries_its_body", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_route_post_data_e2e.py", "scope": "test_a_routed_post_carries_its_body", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_route_post_data_e2e.py", "scope": "test_without_a_route_the_request_still_carries_its_body", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_route_post_data_e2e.py", "scope": "test_without_a_route_the_request_still_carries_its_body", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_route_superseded_e2e.py", "scope": "test_answering_a_route_the_next_navigation_aborted_does_not_raise", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_route_superseded_e2e.py", "scope": "test_answering_a_route_the_next_navigation_aborted_does_not_raise", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_route_superseded_e2e.py", "scope": "test_sequential_routed_gotos_neither_hang_nor_raise", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_same_document_goto_e2e.py", "scope": "test_goto_to_a_fragment_answers_with_the_new_url", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_same_document_goto_e2e.py", "scope": "test_goto_to_a_fragment_answers_with_the_new_url", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_same_document_navigation.py", "scope": "test_pushState_updates_page_url_and_wakes_wait_for_url", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_same_document_navigation.py", "scope": "test_pushState_updates_page_url_and_wakes_wait_for_url", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_scroll_into_view.py", "scope": "test_it_scrolls_ONLY_IF_NEEDED_and_then_centres", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_scroll_into_view.py", "scope": "test_it_scrolls_ONLY_IF_NEEDED_and_then_centres", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_scroll_into_view.py", "scope": "test_scroll_into_view_puts_the_element_in_the_viewport", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_fetch_through_sw_returns_sw_synthesized_response", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_fetch_through_sw_returns_sw_synthesized_response", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_page_with_sw_can_navigate_repeatedly", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_page_with_sw_can_navigate_repeatedly", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_page_with_sw_can_navigate_repeatedly", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_service_worker_registration_does_not_crash_page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_service_worker_registration_does_not_crash_page", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_sw_fall_through_to_network_does_not_crash", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_sw_fall_through_to_network_does_not_crash", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_sw_unregister_then_register_again", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_service_worker.py", "scope": "test_sw_unregister_then_register_again", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_service_worker_controller_e2e.py", "scope": "test_a_reloaded_page_is_controlled_by_its_service_worker", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_service_worker_controller_e2e.py", "scope": "test_a_reloaded_page_is_controlled_by_its_service_worker", "rule": "timeout", "nth": 2, "class": "F", "reason": "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."},
{"file": "test_service_worker_controller_e2e.py", "scope": "test_a_reloaded_page_is_controlled_by_its_service_worker", "rule": "timeout", "nth": 3, "class": "F", "reason": "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."},
{"file": "test_service_workers_blocked.py", "scope": "_install", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_set_input_files_payloads.py", "scope": "test_a_payload_reaches_the_page_as_a_file", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_set_offline_e2e.py", "scope": "test_set_offline_stops_loads_and_set_online_resumes_them", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_shadow_trusted_input.py", "scope": "page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_strict_and_force.py", "scope": "test_force_turns_a_refusal_into_an_attempt", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_the_callers_code_is_not_counted_e2e.py", "scope": "page", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_ua_widget_not_selectable.py", "scope": "test_a_comma_selector_returns_only_author_elements", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_ua_widget_not_selectable.py", "scope": "test_a_simple_selector_returns_only_author_elements", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_ua_widget_not_selectable.py", "scope": "test_an_author_closed_shadow_root_is_still_reachable", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_ua_widget_not_selectable.py", "scope": "test_the_order_is_author_document_order_in_both_forms", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_ua_widget_not_selectable.py", "scope": "test_the_page_itself_still_sees_null_on_both_kinds_of_closed_root", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_wait_for_function.py", "scope": "test_it_also_sees_the_dom", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "test_wait_for_function.py", "scope": "test_it_sees_a_global_the_PAGE_defined", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "webfont_probe.py", "scope": "_Marionette.__init__", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."},
{"file": "webfont_probe.py", "scope": "fonts_mb", "rule": "sleep", "nth": 1, "class": "A", "reason": "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."},
{"file": "webfont_probe.py", "scope": "run", "rule": "env", "nth": 1, "class": "C", "reason": "os.environ written directly is not undone when the test ends or fails: use monkeypatch.setenv, which restores it."},
{"file": "webfont_probe.py", "scope": "run", "rule": "timeout", "nth": 1, "class": "F", "reason": "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."}
]
}
@@ -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:
@@ -94,7 +94,9 @@ 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")
pump = lambda: page.wait_for_timeout(100) # 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), (
+10 -8
View File
@@ -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))
@@ -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}); });
@@ -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"
@@ -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:
@@ -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;
}"""
+51 -10
View File
@@ -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)
@@ -43,21 +43,23 @@ TURN_NUMBER = "198.51.100.7"
TURN_NAME = "turn-a.test"
TURN_PORT = 3478
TURN_ZONE = {**ZONE, TURN_NAME: TURN_NUMBER}
#: How long the page waits for the ICE agent to try the server, in milliseconds.
WAIT_MS = 6000
#: How long to wait for the DoH to be asked and for the gateway to be handed the address, in seconds.
ASKED_SECONDS = 25
#: How long to wait for the DoH to be asked and for the gateway to be handed the address, in seconds (the deadline of the wait).
ASKED_SECONDS = 30
_PROBE_JS = """async ([url, waitMs]) => {
const errors = [], found = [];
const pc = new RTCPeerConnection({iceServers: [{urls: url, username: 'u', credential: 'p'}]});
#: The page starts the ICE agent and leaves it alive; the test closes it AFTER it has seen the DoH asked and the gateway handed the address, so the agent is never
#: closed before it has tried the server, whatever the speed of the machine (a timer of the page that closed it would judge that speed).
_START_JS = """async (url) => {
const probe = window.__probe = {errors: [], found: [], pc: null};
const pc = probe.pc = new RTCPeerConnection({iceServers: [{urls: url, username: 'u', credential: 'p'}]});
pc.createDataChannel('d');
pc.onicecandidateerror = (e) => errors.push(e.errorCode);
pc.onicecandidate = (e) => { if (e.candidate) found.push(e.candidate.candidate); };
pc.onicecandidateerror = (e) => probe.errors.push(e.errorCode);
pc.onicecandidate = (e) => { if (e.candidate) probe.found.push(e.candidate.candidate); };
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve) => setTimeout(resolve, waitMs));
pc.close();
return {errors, candidates: found.length};
}"""
_END_JS = """() => {
const probe = window.__probe;
probe.pc.close();
return {errors: probe.errors, candidates: probe.found.length};
}"""
@@ -81,9 +83,10 @@ def test_a_turn_server_named_over_tcp_is_resolved_by_the_doh_through_the_proxy_o
with _launch(firefox_binary, gw_launch.proxy if gw_launch else None) as browser:
context, page = _page_in(browser, proxy=gw_context.proxy)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
result = page.evaluate(_PROBE_JS, ["turn:%s:%d?transport=tcp" % (TURN_NAME, TURN_PORT), WAIT_MS])
page.evaluate(_START_JS, "turn:%s:%d?transport=tcp" % (TURN_NAME, TURN_PORT))
asked = ds.wait_until(lambda: doh.queries_for(TURN_NAME, QTYPE_A), ASKED_SECONDS)
handed = ds.wait_until(lambda: (TURN_NUMBER, TURN_PORT) in gw_context.connects, ASKED_SECONDS)
result = page.evaluate(_END_JS)
context.close()
watcher.stop()
@@ -18,6 +18,12 @@ selector (the machine did not run the loop: on a loaded host an idle loop is 100
doing and is not counted) or INSIDE something (held). The instrument is the one of the core's
`tests/test_a_close_does_not_hold_the_loop.py`. A control with the same instrument holds the loop on purpose first, so a watcher
that could not see a held loop does not pass the test for nothing.
Nothing here is judged by how long it took (that is a verdict on the runner: a loop that a starved machine runs late is late without
a defect). The loop is held when its thread was SEEN inside a step of the close that waits (`_close_loop_verdicts.blocked_by`), and the
other browsers keep answering when, in the order of the events, a call of each began and ended while the close was in flight and
while the removal of the closing browser's profile was held until every one of them had answered (a removal made on the loop would
wait for the answers that only the loop can read). The milliseconds are printed, never judged.
"""
from __future__ import annotations
@@ -29,6 +35,13 @@ import textwrap
import pytest
from _close_loop_verdicts import (
blind_instrument_problem,
charged_more_than_ran_problem,
close_on_the_loop_problem,
others_answered_problem,
)
pytestmark = pytest.mark.e2e
#: The client. Four browsers by the async API, each with a page; one is closed while a sentinel measures the loop and one pinger per
@@ -48,6 +61,10 @@ _CLIENT = textwrap.dedent("""
def __init__(self):
self.gaps, self.holes, self.held = [], [], 0.0
#: The longest stretch the watcher saw the main thread running something without a pause in the selector, and every
#: frame that was on its stack in those samples (file:function -> samples, and the innermost frames of the first stack
#: it was seen in): WHERE the thread was, which is the cause, where `held` only says for how long.
self.busy_run, self.inside = 0.0, {}
self.beat = [time.monotonic()]
self.stop = asyncio.Event()
self.over = threading.Event()
@@ -86,6 +103,19 @@ _CLIENT = textwrap.dedent("""
"others": {names.get(i, str(i)): "".join(traceback.format_stack(f)[-3:])
for i, f in frames.items() if i != main_id and i != threading.get_ident()}}
def note(self, frame):
names = []
while frame is not None:
names.append("%s:%s" % (frame.f_code.co_filename.replace(os.sep, "/"), frame.f_code.co_name))
frame = frame.f_back
names.reverse()
for name in names:
entry = self.inside.get(name)
if entry is None:
self.inside[name] = {"n": 1, "stack": names[-6:]}
else:
entry["n"] += 1
def watcher(self):
# Only the part of a lateness during which the loop's thread was RUNNING counts. A loop the machine did not schedule waits in
# the selector and then, once woken, runs the callbacks that queued meanwhile (the pingers' replies): counting the whole
@@ -97,11 +127,14 @@ _CLIENT = textwrap.dedent("""
now = time.monotonic()
late = now - self.beat[0]
level = int(late / 0.03)
if self.idle(sys._current_frames().get(main_id)):
frame = sys._current_frames().get(main_id)
if self.idle(frame):
busy_since = None
else:
if busy_since is None:
busy_since = now
self.busy_run = max(self.busy_run, now - busy_since)
self.note(frame)
held = now - max(self.beat[0], busy_since)
if held > 0.03:
self.held = max(self.held, held)
@@ -136,7 +169,8 @@ _CLIENT = textwrap.dedent("""
self._real.clear()
def report(self):
return {"held": self.held, "gap": max(self.gaps), "holes": self.holes[:4], "on_the_loop": sorted(set(self.on_the_loop))}
return {"held": self.held, "busy_run": self.busy_run, "inside": self.inside, "gap": max(self.gaps),
"holes": self.holes[:4], "on_the_loop": sorted(set(self.on_the_loop))}
def engines():
@@ -150,23 +184,35 @@ _CLIENT = textwrap.dedent("""
return out
async def pinger(page, record, closing):
async def pinger(page, record, closing, gate, records):
# A call counts as answered DURING the close when it began after the close began and ended before it ended, and as answered
# DURING THE REMOVAL when it began after the removal of the profile did: the order of the events, not how long it took.
while not record["stop"]:
while_closing = closing.is_set()
started = time.monotonic()
await page.evaluate("1 + 1")
took = time.monotonic() - started
if closing.is_set():
record["answers"] += 1
record["slowest"] = max(record["slowest"], took)
if while_closing and closing.is_set():
record["inside"] += 1
record["slowest"] = max(record["slowest"], took) # printed, never judged
since = gate["since"]
if since is not None and started >= since and gate["released_by"] is None:
record["during_removal"] += 1
if all(r["during_removal"] >= 1 for r in records):
gate["all_answered"].set()
await asyncio.sleep(0.02)
def hold_the_loop(seconds):
time.sleep(seconds)
async def main():
# The control: the same instrument on a loop that is held on purpose.
control = Instrument()
await control.start()
await asyncio.sleep(0.05)
time.sleep(0.4)
hold_the_loop(0.4)
await asyncio.sleep(0.05)
await control.finish()
@@ -191,10 +237,25 @@ _CLIENT = textwrap.dedent("""
# A slow disk: removing a profile takes 150 ms more (a scanner of files at work, a spinning disk, a loaded runner). On a fast
# disk the removal of a profile is a few ms and a close made on the loop hides in the noise; with a disk that is slow the
# wait is what the loop pays, wherever it is made. Every thread pays it the same.
#
# And the first removal inside the close waits until every other browser has answered a call that began after it did (30 s
# at most, the deadline of a hang): the removal that runs in a thread of its own lets the loop serve them and goes on at once;
# one that runs ON the loop stops the only thread that could read their answers, and goes on only at the deadline. How the
# hold ended (`released_by`) is the verdict; a slow machine only makes the answers come later.
real_rmtree = shutil.rmtree
gate = {"since": None, "released_by": None, "all_answered": threading.Event()}
gate_lock = threading.Lock()
def slow_rmtree(*x, **k):
time.sleep(0.15)
first = False
if closing.is_set():
with gate_lock:
if gate["since"] is None:
gate["since"], first = time.monotonic(), True
if first:
answered = gate["all_answered"].wait(30)
gate["released_by"] = "answered" if answered else "deadline"
return real_rmtree(*x, **k)
shutil.rmtree = slow_rmtree
@@ -211,9 +272,9 @@ _CLIENT = textwrap.dedent("""
closing, records = asyncio.Event(), []
tasks = []
for page in pages[1:]:
record = {"stop": False, "answers": 0, "slowest": 0.0}
record = {"stop": False, "inside": 0, "during_removal": 0, "slowest": 0.0}
records.append(record)
tasks.append(asyncio.create_task(pinger(page, record, closing)))
tasks.append(asyncio.create_task(pinger(page, record, closing, gate, records)))
await asyncio.sleep(0.5)
instrument = Instrument()
@@ -229,7 +290,8 @@ _CLIENT = textwrap.dedent("""
"took": took, "launched": launched,
"control": control.report(),
"unscheduled": unscheduled.report(),
"answers": [r["answers"] for r in records], "slowest": [r["slowest"] for r in records],
"others": [{"inside": r["inside"], "during_removal": r["during_removal"], "slowest": r["slowest"]} for r in records],
"gate": {"reached": gate["since"] is not None, "released_by": gate["released_by"]},
})
# The other three still work after it.
shutil.rmtree = real_rmtree
@@ -280,37 +342,52 @@ def report(firefox_binary, tmp_path_factory):
return json.loads(lines[-1][len("REPORT "):])
#: The function the client holds its loop in on purpose (the control), in the script the test writes.
_HOLDER = (("/client.py", ("hold_the_loop",)),)
@pytest.mark.wall_clock
def test_the_instrument_sees_a_loop_that_is_held(report):
"""The control: the loop held on purpose for 400 ms is seen as held. Without this, a watcher that could not tell a held loop from
a starved one would pass the test below for nothing."""
"""The control: the loop held on purpose for 400 ms is seen as held, and seen INSIDE the function that holds it. Without this, a
watcher that could not tell a held loop from a starved one, or could not read where the thread was, would pass the test below for
nothing."""
control = report["control"]
assert control["held"] > 0.3, (
"the watcher did not see a loop held for 400 ms: held %.0f ms" % (control["held"] * 1000))
assert "sleep" in control["on_the_loop"]
assert blind_instrument_problem(control["inside"], _HOLDER) is None, blind_instrument_problem(control["inside"], _HOLDER)
@pytest.mark.wall_clock
def test_the_instrument_does_not_charge_a_loop_the_machine_did_not_schedule(report):
"""The second control: a loop that waited 150 ms in its selector and then ran a 45 ms callback was held for those 45 ms, not 195.
Charging it the whole lateness made a loaded Windows runner fail the bound below with 94 ms and nothing on the loop's thread
(candidate 43727128285)."""
Charging it the whole lateness made a loaded Windows runner fail a bound of 90 ms with 94 ms and nothing on the loop's thread
(candidate 43727128285). What is charged is judged against what the same samples saw run, not against a number of milliseconds:
a held time greater than the longest stretch the thread was seen running counted a wait that was not the loop's."""
unscheduled = report["unscheduled"]
assert unscheduled["gap"] > 0.25, "the sentinel was not late: %r" % unscheduled
assert unscheduled["held"] < 0.09, (
"a loop late by the machine for ~145 ms, then running a 45 ms callback, was charged %.0f ms: only the 45 ms the thread ran may count"
% (unscheduled["held"] * 1000))
assert charged_more_than_ran_problem(unscheduled["held"], unscheduled["busy_run"]) is None, charged_more_than_ran_problem(
unscheduled["held"], unscheduled["busy_run"])
def test_the_removal_of_the_profile_ran_inside_the_close(report):
"""The slow disk of the client is only a stimulus if the removal of the profile ran, through `shutil.rmtree`, while the first
browser closed: the hold of the removal until the others answer is made there. Without this a close that removed nothing through it
would pass the test of the others by not being gated."""
assert report["gate"]["reached"], "no `shutil.rmtree` ran while the first browser closed: %r" % report["gate"]
@pytest.mark.wall_clock
def test_closing_one_of_four_browsers_does_not_hold_the_loop(report):
"""Four browsers, one closes: the loop of the program is not held for 50 ms, counting only the time its thread is running."""
"""Four browsers, one closes: the thread that runs the loop of the program is never seen inside a step of the close that waits
(the shutdown of the server, the join of its workers, the reaping of the tree, the removal of the profile)."""
assert report["launched"] >= 4, "fewer than four engines were running before the close: %r" % report["launched"]
assert report["took"] > 0.3, "the close finished before the engine could have exited: nothing was waited for"
assert report["held"] < 0.05, (
"the loop was held for %.0f ms while one of four browsers closed (the close took %.0f ms; the longest wake was %.0f ms late; "
"calls made by the loop's own thread: %s). Where the threads were while it was late:\n%s"
% (report["held"] * 1000, report["took"] * 1000, report["gap"] * 1000, report["on_the_loop"], _holes(report)))
problem = close_on_the_loop_problem(report["inside"])
assert problem is None, (
"%s\n(printed, not judged: the loop was held %.0f ms while one of four browsers closed, the close took %.0f ms, the longest "
"wake was %.0f ms late; calls made by the loop's own thread: %s). Where the threads were while it was late:\n%s"
% (problem, report["held"] * 1000, report["took"] * 1000, report["gap"] * 1000, report["on_the_loop"], _holes(report)))
def test_no_blocking_step_of_the_close_runs_on_the_loop_s_thread(report):
@@ -319,12 +396,13 @@ def test_no_blocking_step_of_the_close_runs_on_the_loop_s_thread(report):
assert report["on_the_loop"] == [], "the loop's own thread made these calls while it awaited the close: %s" % report["on_the_loop"]
@pytest.mark.wall_clock
def test_the_other_three_keep_answering_during_the_close(report):
"""A call on each of the other three browsers is answered while the first one closes, and the three are alive after."""
assert len(report["answers"]) == 3
assert all(n >= 3 for n in report["answers"]), "the others stopped answering during the close: %r" % report["answers"]
assert max(report["slowest"]) < 2.0, "a call of another browser waited %.1f s during the close" % max(report["slowest"])
"""Each of the other three browsers answers a call that began and ended while the first one closes, the removal of the first one's
profile is held until every one of them has answered, and the three are alive after. The order of the events decides; the
seconds a call took are printed."""
problem = others_answered_problem(report["others"], report["gate"])
assert problem is None, "%s\n(printed, not judged: the slowest call of each browser inside the close, in s: %s)" % (
problem, [round(r["slowest"], 3) for r in report["others"]])
assert report["texts"] == ["browser 1", "browser 2", "browser 3"]
+16 -6
View File
@@ -29,6 +29,7 @@ import statistics
import pytest
from _e2e_verdicts import MDNS_RETRY_MS, opened_at_the_retry_problem
from test_webrtc_realness import _e2e_binary, _launch, candidates, decode_priority, host_candidates, is_mdns # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
@@ -81,8 +82,16 @@ _LOOPBACK_JS = r"""async () => {
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
const deadline = performance.now() + 8000;
while (performance.now() < deadline && !(opened !== null && echoed)) await new Promise(r => setTimeout(r, 5));
// Until the channel has opened and echoed, for 30 s (the deadline of the wait). The loop also keeps the longest time it did not run: a page that
// was stopped by the machine says so, and the time the connection took is not judged then (`_e2e_verdicts.opened_at_the_retry_problem`).
const deadline = performance.now() + 30000;
let stalled = 0, last = performance.now();
while (performance.now() < deadline && !(opened !== null && echoed)) {
await new Promise(r => setTimeout(r, 5));
const now = performance.now();
stalled = Math.max(stalled, now - last);
last = now;
}
// The road the connection took, read from the browser's own statistics: the nominated pair, and the protocol of each end.
let pair = null;
try {
@@ -98,7 +107,7 @@ _LOOPBACK_JS = r"""async () => {
});
} catch (e) {}
pc1.close(); pc2.close();
return {opened, echoed, pair, gathered};
return {opened, echoed, pair, gathered, stalled: Math.round(stalled)};
}"""
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
@@ -108,7 +117,6 @@ _LOOPBACK_JS = r"""async () => {
# the machine. What the test judges is the ROAD, which the machine cannot change (see the test), and a ceiling under the
# first retry of the mDNS responder (3 s), which no machine is slow enough to reach by being slow.
RETAIL_MEDIAN_WINDOW_MS = (30, 55) # printed beside the measure, for the reader
MDNS_RETRY_MS = 3000 # the responder asks again after 3 s: a run that opens only then took the slow road
def _session(declaration, socks, page_url, monkeypatch, seed, script):
@@ -217,7 +225,8 @@ def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_p
socket could not bind and the connection fell back to TCP, about 600 ms on average);
* the nominated pair is direct and local over UDP at both ends: host or peer-reflexive, never relay or server-reflexive, never
TCP (a peer-reflexive end is legitimate: the other connection's mDNS name was not resolved yet and its check came first);
* it opens in less than the responder's first retry (3 s): a name that does not come back opens only at the retry.
* it opens in less than the responder's first retry (3 s) unless the page itself was stopped for a second or more in the meantime: a name that does
not come back opens only at the retry, and a machine that stops for seconds opens late on any road.
The time itself is printed with the retail window beside it: a fast machine shows 30-55 ms, a runner shows more, and
neither is a verdict (an absolute time failed on both GitHub runners with a healthy engine)."""
@@ -243,7 +252,8 @@ def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_p
# network), and never TCP (checked above).
assert pair["localType"] in ("host", "prflx") and pair["remoteType"] in ("host", "prflx"), (
"run %d: the pair is not direct and local (a relay or a server-reflexive road): %r" % (n, pair))
assert res["opened"] < MDNS_RETRY_MS, "run %d: opened after %d ms, at the responder's retry" % (n, res["opened"])
problem = opened_at_the_retry_problem(res["opened"], res["stalled"], MDNS_RETRY_MS)
assert problem is None, "run %d: %s" % (n, problem)
times = sorted(r["opened"] for r in runs)
low, high = RETAIL_MEDIAN_WINDOW_MS
with capsys.disabled():
+7 -6
View File
@@ -13,7 +13,7 @@ knows the names used here, so a page loads only if the lookup went to the DoH).
measures). In global mode 0 `TRRService::GetRequestTimeout` returns `network.trr.request_timeout_ms` (1.5 s); in global
mode 3 it returns `network.trr.request_timeout_mode_trronly_ms` (30 s). A request made TRR_ONLY per request under a global
mode 0 would keep the 1.5 s one and fail a lookup whose answer is only 2 s away, with nothing to fall back to. The page
must load, within 20 s, and the FakeDoh log must show the queries answered after the delay.
must load, within 30 s, and the FakeDoh log must show the queries answered after the delay.
* `test_a_name_the_doh_refused_once_resolves_on_the_next_request`: the FakeDoh refuses the FIRST query of each type for
`flaky-a.test` by ending the exchange with no answer (a reset h2 stream: a failure of the CHANNEL, the kind
`ConfirmationContext::RecordTRRStatus` counts; `_doh_servers.FAILURE_KINDS` has the other two) and serves it afterwards.
@@ -48,13 +48,13 @@ pytestmark = pytest.mark.e2e
#: The latency of the slow DoH, and what a page behind it may take at most.
DOH_LATENCY_S = 2.0
SLOW_LOAD_LIMIT_S = 20.0
SLOW_LOAD_LIMIT_S = 30.0
#: The retries after a refusal: how many and how far apart (more than the 1 s negative cache). The loop is a COUNT of navigations, so
#: a runner that stalls for seconds between two of them lengthens the test and never takes an attempt away from it.
RETRIES = 5
RETRY_GAP_S = 2.0
#: What one navigation of that loop may take: far beyond any healthy run (the product's own limits are 1.5 s for a DoH request and
#: the 20 s of the slow page); a navigation that reaches it is a page that never ends, and is reported as that attempt's error.
#: the 30 s of the slow page); a navigation that reaches it is a page that never ends, and is reported as that attempt's error.
NAVIGATION_LIMIT_MS = 30000
@@ -115,7 +115,7 @@ def _only_the_doh_road_was_used(doh, gw, watcher):
def test_a_slow_doh_still_resolves_the_name_of_a_proxied_context(firefox_binary, doh, pages, gateway, watcher,
record_property):
"""`slow-a.test` is known only to the FakeDoh, which answers it 2 s after the query. The page of a context with a
proxy of its own must load within 20 s, reached by address through that proxy."""
proxy of its own must load within 30 s, reached by address through that proxy."""
doh.names["slow-a.test"] = "127.0.0.1"
doh.delay_names["slow-a.test"] = DOH_LATENCY_S
gw = gateway("gw")
@@ -142,7 +142,6 @@ def test_a_slow_doh_still_resolves_the_name_of_a_proxied_context(firefox_binary,
"the page behind a DoH that answers in %.0f s did not load (%s): the DoH request of a lookup made TRR_ONLY per "
"request gave up before the answer (the 1.5 s timeout of global mode 0?)" % (DOH_LATENCY_S, error) + why)
assert "HOST=slow-a.test:%d" % pages.port in text, "the page is not the page of the name: %r" % text + why
assert seconds < SLOW_LOAD_LIMIT_S, "the page took %.1f s to load, the limit is %.0f s" % (seconds, SLOW_LOAD_LIMIT_S) + why
assert seconds >= DOH_LATENCY_S - 0.2, (
"the page loaded in %.2f s, before the DoH could have answered (%.0f s): the name was not resolved by it"
% (seconds, DOH_LATENCY_S) + why)
@@ -183,7 +182,9 @@ def test_a_name_the_doh_refused_once_resolves_on_the_next_request(firefox_binary
context, page = _page_in(browser, proxy=gw.proxy)
page.close()
attempts.append(_navigate(context, url, NAVIGATION_LIMIT_MS))
while attempts[-1][0] is None and len(attempts) <= RETRIES:
for _retry in range(RETRIES):
if attempts[-1][0] is not None:
break
time.sleep(RETRY_GAP_S)
attempts.append(_navigate(context, url, NAVIGATION_LIMIT_MS))
context.close()
+1 -1
View File
@@ -146,7 +146,7 @@ def _worker_navigator_dict(page, props):
worker.onmessage = (e) => resolve(e.data);
worker.onerror = (e) => reject(new Error(e.message));
worker.postMessage(props);
setTimeout(() => reject(new Error('worker timeout')), 5000);
setTimeout(() => reject(new Error('worker timeout')), 30000);
});
return result;
} finally {
@@ -26,6 +26,7 @@ import pytest
from _fission_frames import (Sites, assert_other_process, decode_png, launch, near, new_page, wait_for,
wait_frame)
from _waits import watch
pytestmark = pytest.mark.e2e
@@ -177,17 +178,17 @@ def test_waiting_for_an_element_that_appears_later_in_a_frame_of_another_site(pa
frame = {"frame": wait_frame(page, late.url("B"), "/late-b"),
"nested": wait_frame(page, late.url("C"), "/late-c")}[target]
# the element is not there yet when the wait starts, or it is by now: either way the wait returns it
handle = frame.wait_for_selector("#late", timeout=8000)
handle = frame.wait_for_selector("#late", timeout=30000)
try:
assert handle.inner_text() == "arrived"
assert handle.owner_frame() is frame
finally:
handle.dispose()
# the same, by the locator of the frame and by the frame locator of the page
frame.locator("#shown").wait_for(state="visible", timeout=8000)
frame.locator("#shown").wait_for(state="visible", timeout=30000)
outer = page.frame_locator("#b")
scoped = outer.locator("#late") if target == "frame" else outer.frame_locator("#c").locator("#late")
scoped.wait_for(state="attached", timeout=8000)
scoped.wait_for(state="attached", timeout=30000)
assert scoped.inner_text() == "arrived"
@@ -335,12 +336,34 @@ def painted(sites):
return sites
def painted_shot(page, take, probes, seconds=30.0):
"""``decode_png`` of the first screenshot whose pixel at every probe ``((x, y), colour)`` is the colour asked.
The frame of another site is painted by its own process, and when that happens depends on the machine (half a second
after the frame is listed was not enough on a loaded Windows runner), so the screenshot is taken again until the
paint is there, with a deadline; a frame that is never painted is red at the deadline, with the colours seen at each
probe on the way. The caller then asserts on the image returned, as before."""
last = {}
def sample():
last["png"] = decode_png(take())
_, _, pixel = last["png"]
return tuple(pixel(*point) for point, _ in probes)
seen = watch(sample, lambda colours: all(near(c, want) for c, (_, want) in zip(colours, probes)), seconds,
lambda: page.wait_for_timeout(100))
assert seen.ok, "the frames were never painted as asked within %.0f s; the colours at %s were: %s" % (
seconds, [point for point, _ in probes], seen.render())
return last["png"]
def test_a_page_screenshot_shows_the_content_of_the_frames_of_other_sites(page, painted):
page.goto(painted.url("A", "/paint"), wait_until="load")
wait_frame(page, painted.url("C"), "/paint")
page.wait_for_timeout(500)
assert_other_process(page.main_frame, wait_frame(page, painted.url("B"), "/paint"))
_, _, pixel = decode_png(page.screenshot(scale="css"))
_, _, pixel = painted_shot(page, lambda: page.screenshot(scale="css"), [
((10, 10), (255, 255, 255)), ((50 + 5, 40 + 5), PINK), ((50 + 20 + 40, 40 + 30 + 30), GREEN),
((50 + 120 + 5, 40 + 20 + 5), BLUE), ((50 + 120 + 10 + 25, 40 + 20 + 10 + 20), GOLD)])
# outside the frame the page's own white; inside it the frame's pink; its swatch; the nested frame's blue
assert near(pixel(10, 10), (255, 255, 255)), pixel(10, 10)
assert near(pixel(50 + 5, 40 + 5), PINK), pixel(55, 45)
@@ -355,8 +378,9 @@ def test_a_locator_screenshot_of_an_element_in_a_frame_of_another_site(page, pai
page.goto(painted.url("A", "/paint"), wait_until="load")
frame = {"frame": wait_frame(page, painted.url("B"), "/paint"),
"nested": wait_frame(page, painted.url("C"), "/paint")}[target]
page.wait_for_timeout(500)
width, height, pixel = decode_png(frame.locator("#swatch").screenshot(scale="css"))
points = ((0, 0), (size[0] - 1, size[1] - 1), (size[0] // 2, size[1] // 2), (size[0] - 1, 0))
width, height, pixel = painted_shot(page, lambda: frame.locator("#swatch").screenshot(scale="css"),
[(point, color) for point in points])
assert (width, height) == size
for x, y in ((0, 0), (width - 1, height - 1), (width // 2, height // 2), (width - 1, 0)):
assert near(pixel(x, y), color), ((x, y), pixel(x, y))
@@ -365,7 +389,7 @@ def test_a_locator_screenshot_of_an_element_in_a_frame_of_another_site(page, pai
def test_a_locator_screenshot_of_the_iframe_element_shows_the_frame(page, painted):
page.goto(painted.url("A", "/paint"), wait_until="load")
wait_frame(page, painted.url("C"), "/paint")
page.wait_for_timeout(500)
width, height, pixel = decode_png(page.locator("#b").screenshot(scale="css"))
width, height, pixel = painted_shot(page, lambda: page.locator("#b").screenshot(scale="css"),
[((5, 5), PINK), ((60, 60), GREEN), ((125, 25), BLUE)])
assert (width, height) == (300, 200)
assert near(pixel(5, 5), PINK) and near(pixel(60, 60), GREEN) and near(pixel(125, 25), BLUE)
@@ -47,7 +47,7 @@ WORKER_JS = """(kind) => new Promise(resolve => {
} catch (e) { resolve({error: String(e)}); return; }
worker.onmessage = e => resolve(e.data);
worker.onerror = e => resolve({error: 'worker error: ' + e.message});
setTimeout(() => resolve({error: 'timeout'}), 10000);
setTimeout(() => resolve({error: 'timeout'}), 30000);
})""" % json.dumps(IDENTITY)
WINDOW_JS = "() => (%s)" % IDENTITY
@@ -137,7 +137,7 @@ SHARED_WORKER_JS = """() => new Promise(resolve => {
worker.port.onmessage = e => resolve({outcome: 'ok', identity: e.data});
worker.onerror = e => resolve({outcome: 'error', message: String(e.message || e)});
} catch (e) { resolve({outcome: 'throw', message: e.name + ': ' + e.message}); }
setTimeout(() => resolve({outcome: 'timeout'}), 10000);
setTimeout(() => resolve({outcome: 'timeout'}), 30000);
})"""
SERVICE_WORKER_JS = """() => new Promise(resolve => {
@@ -150,7 +150,7 @@ SERVICE_WORKER_JS = """() => new Promise(resolve => {
}),
e => resolve({outcome: 'rejected', message: e.name + ': ' + e.message}));
} catch (e) { resolve({outcome: 'throw', message: e.name + ': ' + e.message}); }
setTimeout(() => resolve({outcome: 'timeout'}), 15000);
setTimeout(() => resolve({outcome: 'timeout'}), 30000);
})"""
+11 -8
View File
@@ -61,7 +61,7 @@ from urllib.parse import urlsplit
import pytest
sys.path.insert(0, os.path.dirname(__file__))
from _fission_frames import TRIALS, other_process_proved, ticks_inside # noqa: E402
from _fission_frames import PROOF_SECONDS, TRIALS, other_process_proved, ticks_inside # noqa: E402
from _servers import LocalServer # noqa: E402
SEED = 4242
@@ -542,10 +542,10 @@ SPIN_PROBE_JS = """(spin) => new Promise(resolve => {
const ticks = [];
const id = setInterval(() => ticks.push(Date.now()), 10);
const done = (spun) => { clearInterval(id); removeEventListener('message', on); resolve([ticks, spun]); };
const on = e => { if (e.data && e.data.fission_spun) setTimeout(() => done(e.data.fission_spun), 200); };
const on = e => { if (e.data && e.data.fission_spun) done(e.data.fission_spun); };
addEventListener('message', on);
document.getElementById('oop2').contentWindow.postMessage({fission_busy: spin}, '*');
setTimeout(() => done(null), 8000);
setTimeout(() => done(null), 30000);
})"""
@@ -570,11 +570,14 @@ def _run(binary: str, seed: int, strategy: int) -> dict:
# strategy 1: until one spin shows ticks inside it (a healthy machine needs one). strategy 0: all of
# them, and none may show a tick inside (the proof of one process is the absence, every time)
trials = []
for _ in range(TRIALS):
ticks, spun = page.evaluate(SPIN_PROBE_JS, SPIN_MS)
trials.append((ticks, spun))
if strategy == 1 and other_process_proved(trials):
break
if strategy == 1:
# spins until one shows ticks inside it, for 30 s (a loaded machine starves the top for a whole spin now and then)
end = time.monotonic() + PROOF_SECONDS
while not other_process_proved(trials) and time.monotonic() < end:
trials.append(tuple(page.evaluate(SPIN_PROBE_JS, SPIN_MS)))
else:
for _ in range(TRIALS):
trials.append(tuple(page.evaluate(SPIN_PROBE_JS, SPIN_MS)))
finally:
server.shutdown()
return {"results": results, "spin_trials": trials, "port": port}
@@ -68,9 +68,14 @@ import time
import pytest
from _waits import awatch
pytestmark = pytest.mark.e2e
HELD_S = 1.5
#: The deadline of every wait for a thing that must happen (the stop of a goto the server holds, the page it lands on): a goto that nothing stops ends at
#: it with another error, so it is the bound of the wait that leads up to the stop and no healthy run comes near it.
GOTO_TIMEOUT_MS = 30_000
ACT = {
"docopen": "document.open(); document.write('<html><body><h1>rewritten</h1></body></html>'); document.close();",
"stop": "window.stop();",
@@ -201,7 +206,7 @@ def test_a_goto_stopped_on_its_way_raises_or_lands_and_never_lies(firefox_binary
began = time.monotonic()
error = None
try:
page.goto(target, wait_until="domcontentloaded", timeout=10_000)
page.goto(target, wait_until="domcontentloaded", timeout=GOTO_TIMEOUT_MS)
except Error as e:
error = e.message
finally:
@@ -217,7 +222,7 @@ def test_a_goto_stopped_on_its_way_raises_or_lands_and_never_lies(firefox_binary
expected = same + end
if end in ("/old", "/start"):
expected = same + "%s?k=%s&i=%d" % (end, kind, i)
page.wait_for_url(expected, timeout=5_000)
page.wait_for_url(expected, timeout=GOTO_TIMEOUT_MS)
else:
assert error is None, where
# It waited for its page, which the server held.
@@ -248,17 +253,16 @@ def test_a_second_goto_interrupts_the_first_and_lands(firefox_binary, server):
# the gate, after both gotos have returned: the first can only
# end by being replaced.
gate = GATES["first=%d" % i] = threading.Event()
began = time.monotonic()
async def go(url, after=None):
# The second goto starts once the server has the first's
# request, so the first is on its way on any machine. The
# first goto's own timeout is the bound of the wait.
while after is not None and after not in ARRIVED:
assert time.monotonic() - began < 10, "the first goto never left"
await asyncio.sleep(0.02)
if after is not None:
left = await awatch(lambda: after in ARRIVED, bool, GOTO_TIMEOUT_MS / 1000, lambda: asyncio.sleep(0.02))
assert left.ok, "the first goto never left: %s" % left.render()
try:
await page.goto(url, wait_until="domcontentloaded", timeout=10_000)
await page.goto(url, wait_until="domcontentloaded", timeout=GOTO_TIMEOUT_MS)
return None
except Exception as e:
return str(e)
+5 -3
View File
@@ -133,10 +133,12 @@ def test_hidden_desktop_takes_the_window_off_screen_but_keeps_rendering(firefox_
with ip as browser:
page = browser.new_page()
page.goto(served, timeout=30_000)
time.sleep(2)
desktop = ip._virtual_display.name
assert desktop and desktop != "Default"
# until the window is on its own desktop (a condition with a deadline, not 2 s): the check that none is on the caller's desktop is read
# after the window exists, so it cannot be read before the window had a place to be put in; a session that never puts one there ends red below
wait_until(lambda: _moz_windows_on(desktop, ip) >= 1, 30, lambda: page.wait_for_timeout(100))
# 1) not on the desktop the caller is on ...
assert _moz_windows_on(None, ip) == 0, (
@@ -165,13 +167,13 @@ def test_hidden_desktop_takes_the_window_off_screen_but_keeps_rendering(firefox_
# line that makes the engine's release gate prove it per build.
stream = Stream("hidden desktop")
stream.start(page)
deadline = time.time() + 15
deadline = time.time() + 30
while not stream.frames and time.time() < deadline:
time.sleep(0.1)
page.screencast.stop()
frames = stream.frames
assert frames, ("no screencast frame arrived from the hidden desktop "
"in 15 s: the window capturer is not being used there\n"
"in 30 s: the window capturer is not being used there\n"
"%s\n"
"engine output (lines starting with 'screencast:'):\n%s"
% (stream.describe(), engine_screencast_lines(page)))
+12 -3
View File
@@ -11,8 +11,8 @@ not have to come at the second visit. THE THIRD RUN (Windows, DoH and UDP free)
(h3, h2, h2): behind a proxy "visit 1 is always h2" is NOT a retail fact. With UDP blocked it is h2/h2/h2 in 15 of 15, with no
delay of the load: the only outcome of the retail that repeats every time. With no
proxy and the native DNS (measured in loopback) it is h2, h3, h3. The method is the retail's: one context, the same page again
and again (``?v=N`` keeps each visit off the HTTP cache), a pause of two seconds after each load so that the Alt-Svc it carries
settles, and the ``nextHopProtocol`` of the navigation entry of the document,
and again (``?v=N`` keeps each visit off the HTTP cache), after each load a wait (with a deadline) until the server has seen the QUIC connection that the
Alt-Svc it carries makes, on the roads where UDP is free, and a pause of two seconds, and the ``nextHopProtocol`` of the navigation entry of the document,
``performance.getEntriesByType('navigation')[0].nextHopProtocol``. What each road reads is in ``_udp_line.expected_protocols``
and is judged by ``_udp_line.judge_visits``.
@@ -51,6 +51,7 @@ import time
import pytest
from _host_address import this_host_address
from _waits import wait_until
from _udp_line import (declared_udp, egress_by_proxy, expected_protocols, judge_visits, measure_servers, no_https_record,
visits_for)
@@ -62,6 +63,8 @@ EXIT_DIRECT = "203.0.113.7"
_DECLARED = {"socks5_coherent": "coherent", "socks5_no_udp": "no", "socks5_mismatched": "no", "socks5_unmeasured": "unmeasured"}
#: The pause after each load (the retail method), and the nextHopProtocol of the document.
PAUSE_MS = 2000
#: The roads where QUIC can reach the server, so a QUIC connection of the browser is what its Alt-Svc turns into.
_UDP_FREE_ROADS = ("direct", "socks5_coherent")
_NAV_JS = "() => performance.getEntriesByType('navigation')[0].nextHopProtocol"
@@ -108,7 +111,13 @@ def _visits(road, server, monkeypatch, discover, **launch):
started = time.monotonic()
page.goto(url, wait_until="load", timeout=60000)
walls.append(round((time.monotonic() - started) * 1000))
page.wait_for_timeout(PAUSE_MS) # let the later resources and the Alt-Svc settle
if road in _UDP_FREE_ROADS:
# The Alt-Svc of the document is absorbed when the browser has made its own QUIC connection to the server (the
# server sees it): the next visit reads h3 from then on, and not before. Waited for as a condition with a
# deadline, not slept for: on a loaded machine that connection comes later than any pause. A road whose UDP
# leads nowhere has nothing to wait for (every visit is h2 and no QUIC arrives): it keeps the pause.
wait_until(lambda: server.quic_peers, 30, lambda: page.wait_for_timeout(100))
page.wait_for_timeout(PAUSE_MS) # let the later resources settle
protocols.append(page.evaluate(_NAV_JS))
return protocols, walls
@@ -134,7 +134,9 @@ def test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701(firefox_bi
assert [e["code"] for e in res["errors"]] == [701], "the STUN request must end in ONE ICE error 701" + why
protocols = sorted({c["proto"].upper() for c in cands if c["typ"] == "host"})
assert protocols == ["TCP", "UDP"], "host candidates of a retail with UDP blocked: UDP and TCP" + why
assert 10_000 <= res["at_ms"]["error"] <= 13_000, (
# The floor only: an error that comes at once is a name that was never resolved, and nICEr's own time on a network that
# drops UDP (11.1-11.3 s) can only be stretched by a slow machine, so no ceiling short of the page's own wait (25 s).
assert res["at_ms"]["error"] >= 10_000, (
"the 701 came at %s ms; nICEr's time on a network that drops UDP is 11.1-11.3 s (an immediate error means the "
"name was never resolved)" % res["at_ms"]["error"] + why)
assert "complete" in res["at_ms"], "the gather did not end by itself" + why
+14 -3
View File
@@ -73,11 +73,14 @@ function arrivedFromOutside(el, label) {
const WATCHED = ['b', 'l', 'i'].map(id => document.getElementById(id));
WATCHED.forEach(remember);
// The watcher counts its own looks (`window.__looks`), so a test that wants a look made AFTER something it did waits for the counter to move, not for a time.
window.__looks = 0;
setInterval(() => {
const f = [];
WATCHED.forEach((el, n) => f.push(...arrivedFromOutside(el, 'el' + n)));
document.getElementById('verdict').textContent =
f.length ? ('DIRTY ' + f.join(' ')) : 'clean';
window.__looks += 1;
}, 50);
// ⛔ THE CONTROL FOR THE WATCHER ITSELF. The page stamps a fresh element with
@@ -172,8 +175,12 @@ def test_the_aria_snapshot_writes_nothing_the_page_can_see(firefox_binary):
call = ("(injected, o) => injected.ariaSnapshot("
"document.documentElement, o)")
looks_before = page.evaluate("window.__looks")
snapshot = d.injected.call(frame, call, {"mode": "ai"})
page.wait_for_timeout(200)
# until the watcher has looked twice more (a condition with a deadline, not 200 ms): the second look began after the call above had returned,
# so the verdict read below is of the page as the snapshot left it. A watcher that stops ends red at the deadline.
assert wait_until(lambda: page.evaluate("window.__looks") >= looks_before + 2, 30, lambda: page.wait_for_timeout(50)), (
"the watcher of the page did not look again after the snapshot: its verdict below would be of the page before it")
# ⛔ THE BRANCH HAS TO HAVE RUN, or this test goes green on a build
# where nothing was written and says nothing about confinement. `ref=`
@@ -208,14 +215,18 @@ def test_the_default_path_does_not_even_write_in_the_sandbox(firefox_binary):
seed=42, binary_path=firefox_binary) as browser:
page = browser.new_page()
page.goto(site.url)
page.wait_for_timeout(200)
# until the watcher has looked once (a condition with a deadline, not 200 ms)
assert wait_until(lambda: page.evaluate("window.__looks") >= 1, 30, lambda: page.wait_for_timeout(50)), "the watcher of the page never ran"
d = _page_dispatcher(page)
frame = d.actions.lifecycle.main_frame
looks_before = page.evaluate("window.__looks")
d.injected.call(frame,
"(injected, o) => injected.ariaSnapshot("
"document.documentElement, o)", {"mode": "raw"})
page.wait_for_timeout(200)
# until it has looked twice more (the second look began after the call returned), not 200 ms: the verdict below is of the page as the call left it
assert wait_until(lambda: page.evaluate("window.__looks") >= looks_before + 2, 30, lambda: page.wait_for_timeout(50)), (
"the watcher of the page did not look again after the call")
from_sandbox = d.injected.evaluate(
frame, "(() => { const el = document.getElementById('b');"
@@ -13,6 +13,8 @@ real wheel on retail Windows Firefox is 6 to 14 ms below.
"""
from __future__ import annotations
import statistics
import pytest
pytestmark = pytest.mark.e2e
@@ -49,6 +51,17 @@ def test_every_key_and_move_is_born_before_its_handler_runs(firefox_binary):
assert rows, kind
kept = [r for r in rows if r[2]]
assert len(kept) == len(rows), (kind, rows)
# Born a few ms before, never far in the past: the timer's precision
# is 1 ms, the session's latency 2 to 30.
assert all(-40.0 < r[1] < 0.0 for r in rows), (kind, rows)
# Born BEFORE the handler, always (an order, not a duration) ...
ages = [r[1] for r in rows]
assert all(age < 0.0 for age in ages), (kind, rows)
# ... and a few ms before, never far in the past: the timer's precision is 1 ms, the session's latency 2 to 30.
if kind in ("keydown", "keyup"):
# A key is made in the content process and handed to the page in the same task (the text input processor dispatches
# it at once, born `latency` ms in the past): no stall of the machine can come between its birth and its handler, so
# EVERY key is held to the bound.
assert all(-40.0 < age for age in ages), (kind, rows)
else:
# A move or a wheel is made in the parent and crosses to the content process: a content process that stops for a
# moment ages the event that waits for it, which says nothing of when it was born. Said of the TYPICAL event (the
# median of the stream): a stream whose typical event is old is the defect.
assert -40.0 < statistics.median(ages), (kind, rows)
+3 -3
View File
@@ -65,7 +65,7 @@ def test_the_four_states_are_reached_on_a_real_page(firefox_binary):
{"removeOnDetach": True})
page = c.send("Browser.newPage",
{"browserContextId": ctx["browserContextId"]})
deadline = time.time() + 15
deadline = time.time() + 30
while page["targetId"] not in sessions and time.time() < deadline:
time.sleep(0.02)
v = sessions[page["targetId"]]
@@ -84,8 +84,8 @@ def test_the_four_states_are_reached_on_a_real_page(firefox_binary):
assert v.inflight == 0
tree = v.frame_tree()
children = [d for d in tree.values() if d["parent"]]
assert len(children) == 1, tree
iframes = [d for d in tree.values() if d["parent"]] # the frames of the page's tree: its one <iframe>, not a count of processes
assert len(iframes) == 1, tree
assert "load" in tree[v.main_frame]["states"]
finally:
c.close()
+63 -75
View File
@@ -21,6 +21,7 @@ from invisible_core.juggler.connection import EventListeners, ProtocolError
from _servers import LocalServer
from _browser_census import closes_with_the_test
from _waits import wait_until
PAGE = b"""<!doctype html><html><head><title>seam</title></head><body>
<button id=b onclick="this.dataset.n=(+(this.dataset.n||0)+1)">press</button>
@@ -193,7 +194,7 @@ def test_create_is_announced_BEFORE_anything_can_name_the_object():
# ── with a browser, through the public API ──────────────────────────────────
@pytest.mark.e2e
def test_the_public_API_drives_a_page_WITHOUT_node(firefox_binary):
def test_the_public_API_drives_a_page_WITHOUT_node(firefox_binary, monkeypatch):
"""⛔ THE TEST THIS WHOLE SUBSYSTEM EXISTS FOR.
Nothing below mentions `_juggler`. It is the ordinary user-facing API, and
@@ -202,7 +203,7 @@ def test_the_public_API_drives_a_page_WITHOUT_node(firefox_binary):
823 generated methods and the sync facade are all working against a
different object underneath - which is the entire claim of the detachment.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -222,19 +223,18 @@ def test_the_public_API_drives_a_page_WITHOUT_node(firefox_binary):
box = page.query_selector("#b").bounding_box()
assert box and box["width"] > 0
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_the_public_API_reads_MANY_elements_without_node(firefox_binary):
def test_the_public_API_reads_MANY_elements_without_node(firefox_binary, monkeypatch):
"""`query_selector_all`, `count` and `eval_on_selector_all`.
⛔ Each handle holds a DOM node alive until it is disposed, so a page with a
thousand matches leaks a thousand nodes. That is a property of the protocol,
not of this test, and it is written down where the handles are made.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -256,17 +256,16 @@ def test_the_public_API_reads_MANY_elements_without_node(firefox_binary):
assert page.eval_on_selector_all(
"li.x", "(els, n) => els.length * n", 2) == 6
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_the_public_API_WAITS_for_an_element_that_arrives_late(firefox_binary):
def test_the_public_API_WAITS_for_an_element_that_arrives_late(firefox_binary, monkeypatch):
"""⛔ THE POINT OF `wait_for_selector`, and the reason it cannot go through
the retry loop: that loop disposes what it resolves on every turn, so it
would hand back a handle it has just released - and a released handle does
not raise, it answers wrong. The element below arrives 3 s after the test schedules it."""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
not raise, it answers wrong. The element below arrives 1 s after the test asks for it."""
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -276,28 +275,30 @@ def test_the_public_API_WAITS_for_an_element_that_arrives_late(firefox_binary):
headless=True) as browser:
page = browser.new_page()
page.goto(url)
# The late element is the test's own, scheduled HERE, 3 s from now. The page's #slow comes from a timer started at its
# load, and on a Windows runner more than 800 ms can pass between the load and the first read (CI of 13/11, run
# 43383366904). Nothing of the page adds #later, so only this timer can. 3 s, not 800 ms: the absent check is two round
# trips (the reply of evaluate, then query_selector), and on a Windows runner each took up to 0.4-0.5 s (run 43389137758,
# 40 runs: evaluate up to 422 ms, query_selector up to 516 ms), so 800 ms was crossed once in 20 (run 43387760051).
# The late element is the test's own: the page only holds the function that adds it, and the test calls that
# AFTER it has seen the element absent. A timer started before the check judged the speed of the machine: the
# check is two round trips, up to 0.4-0.5 s each on a Windows runner (run 43389137758), and a delay of 800 ms was
# crossed once in 20 (run 43387760051); an element that arrives before the check turns the test red with
# "it proves nothing". Now nothing arrives until the check is done, however long it took.
page.evaluate("""() => {
const box = document.createElement('div');
document.body.appendChild(box);
setTimeout(() => { box.innerHTML = '<span id=later>arrived</span>'; }, 3000);
window.__showLater = () => setTimeout(() => {
box.innerHTML = '<span id=later>arrived</span>';
}, 1000);
}""")
assert page.query_selector("#later") is None, (
"the element was already there: the test proves nothing")
handle = page.wait_for_selector("#later", timeout=15000)
page.evaluate("() => window.__showLater()")
handle = page.wait_for_selector("#later", timeout=30000)
assert handle is not None
assert handle.text_content() == "arrived"
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_going_BACK_then_FORWARD_leaves_the_page_readable(firefox_binary):
def test_going_BACK_then_FORWARD_leaves_the_page_readable(firefox_binary, monkeypatch):
"""⛔ TWO MOVEMENTS, AND A READ FROM THE PAGE. One of each is what the two
earlier tests did, and between them they missed the defect entirely.
@@ -315,7 +316,7 @@ def test_going_BACK_then_FORWARD_leaves_the_page_readable(firefox_binary):
different and still valid reason. The three ways of being green stop looking
alike.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -344,12 +345,11 @@ def test_going_BACK_then_FORWARD_leaves_the_page_readable(firefox_binary):
page.reload()
assert page.locator("#t").inner_text() == "hello"
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_going_back_over_a_page_the_script_left_without_a_gesture(firefox_binary):
def test_going_back_over_a_page_the_script_left_without_a_gesture(firefox_binary, monkeypatch):
"""`go_back` goes back like `history.back()`, not like the Back button.
Firefox's Back button skips history entries the person never interacted
@@ -362,7 +362,7 @@ def test_going_back_over_a_page_the_script_left_without_a_gesture(firefox_binary
under load. Playwright's `go_back` is `history.back()`: it goes to the
previous entry, gesture or not.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -382,40 +382,36 @@ def test_going_back_over_a_page_the_script_left_without_a_gesture(firefox_binary
assert page.url == url, "go_back stayed on %s" % page.url
assert page.locator("#t").inner_text() == "hello"
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_set_content_runs_in_the_MAIN_world_without_node(firefox_binary):
def test_set_content_runs_in_the_MAIN_world_without_node(firefox_binary, monkeypatch):
"""⛔ THE KNOWN-BAD OF `set_content`. Run from the utility world it answers
`The operation is insecure` EVERY time: that world has an extended
principal, and Gecko requires `document.open()` to run under a principal
equal to the document's. The fork already fixed this inside the driver; the
Python server has to get it right for the same reason, not by luck.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
from invisible_playwright import InvisiblePlaywright
try:
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
headless=True) as browser:
page = browser.new_page()
page.set_content("<html><head><title>written</title></head>"
"<body><p id=w>from set_content</p></body></html>")
assert page.title() == "written"
assert page.text_content("#w") == "from set_content"
# And an apostrophe in the html must not close the JavaScript
# literal it travels inside: that is the 2026-08-24 defect.
page.set_content("<p id=q>it's fine</p>")
assert page.text_content("#q") == "it's fine"
finally:
os.environ.pop(factory.CHOICE_ENV, None)
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
headless=True) as browser:
page = browser.new_page()
page.set_content("<html><head><title>written</title></head>"
"<body><p id=w>from set_content</p></body></html>")
assert page.title() == "written"
assert page.text_content("#w") == "from set_content"
# And an apostrophe in the html must not close the JavaScript
# literal it travels inside: that is the 2026-08-24 defect.
page.set_content("<p id=q>it's fine</p>")
assert page.text_content("#q") == "it's fine"
@pytest.mark.e2e
def test_the_public_API_selects_and_checks_without_node(firefox_binary):
def test_the_public_API_selects_and_checks_without_node(firefox_binary, monkeypatch):
"""`select_option` and `check`, through the generated API."""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -435,7 +431,6 @@ def test_the_public_API_selects_and_checks_without_node(firefox_binary):
page.uncheck("#c")
assert not page.is_checked("#c")
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@@ -457,7 +452,7 @@ SHADOW = b"""<!doctype html><html><head><title>shadow</title></head><body>
@pytest.mark.e2e
def test_locators_reach_INSIDE_a_closed_shadow_root(firefox_binary):
def test_locators_reach_INSIDE_a_closed_shadow_root(firefox_binary, monkeypatch):
"""⛔ Side A of the closed-shadow-root research, verified on the product.
The engine patch lives in `Element::GetShadowRootForBindings` and is gated
@@ -465,7 +460,7 @@ def test_locators_reach_INSIDE_a_closed_shadow_root(firefox_binary):
page does not. This asserts the automation half; the test below asserts
the half that matters more - that the page gained nothing.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(SHADOW))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -480,12 +475,11 @@ def test_locators_reach_INSIDE_a_closed_shadow_root(firefox_binary):
assert page.text_content("#deep") == "two levels down", (
"a root nested inside a closed root was not reached")
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_the_PAGE_still_sees_nothing_of_a_closed_root(firefox_binary):
def test_the_PAGE_still_sees_nothing_of_a_closed_root(firefox_binary, monkeypatch):
"""⛔ THE HALF THAT MATTERS MORE, and it is the known-bad of the engine
patch. A real Firefox NEVER hands a closed root to content: if our build
did, `!!el.shadowRoot` on a closed host would be a one-line detector that
@@ -493,7 +487,7 @@ def test_the_PAGE_still_sees_nothing_of_a_closed_root(firefox_binary):
So the assertion is not "automation works" but "the page is unchanged".
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(SHADOW))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -518,12 +512,11 @@ def test_the_PAGE_still_sees_nothing_of_a_closed_root(firefox_binary):
) == '<div id="host"></div>', (
"the page's own serialisation changed")
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_content_SERIALISES_shadow_roots_including_closed_ones(firefox_binary):
def test_content_SERIALISES_shadow_roots_including_closed_ones(firefox_binary, monkeypatch):
"""⛔ Side B of the research, and what forking the client unlocked.
Upstream serialises with `documentElement.outerHTML`, which walks the light
@@ -531,7 +524,7 @@ def test_content_SERIALISES_shadow_roots_including_closed_ones(firefox_binary):
divergence is real and complete - open, closed, and a root NESTED inside a
closed one, which is where a depth-one walk would look right and be wrong.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(SHADOW))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -560,7 +553,6 @@ def test_content_SERIALISES_shadow_roots_including_closed_ones(firefox_binary):
assert "shadowrootmode" not in own, (
"the page can serialise its own shadow roots: %s" % own[:200])
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@@ -577,13 +569,13 @@ NOISY = b"""<!doctype html><html><head><title>events</title></head><body>
@pytest.mark.e2e
def test_console_messages_reach_the_page_listener(firefox_binary):
def test_console_messages_reach_the_page_listener(firefox_binary, monkeypatch):
"""⛔ `console` and `pageError` are emitted on the CONTEXT, not on the
Page, and `_browser_context.py` re-emits them on the page it finds in
`params["page"]`. Emitting them on the Page produces no error at all: the
handler simply never runs, and the user concludes their page prints
nothing."""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(NOISY))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -595,7 +587,10 @@ def test_console_messages_reach_the_page_listener(firefox_binary):
seen = []
page.on("console", lambda m: seen.append((m.type, m.text)))
page.goto(url)
page.wait_for_timeout(500)
# the two messages of the page are waited for (30 s is a deadline no healthy run comes near), not slept for
wait_until(lambda: any("first line" in text for _, text in seen)
and any(kind in ("warning", "warn") for kind, _ in seen),
30, lambda: page.wait_for_timeout(50))
assert seen, "no console message arrived at all"
kinds = {t for t, _ in seen}
texts = " | ".join(text for _, text in seen)
@@ -605,15 +600,14 @@ def test_console_messages_reach_the_page_listener(firefox_binary):
assert "warning" in kinds or "warn" in kinds, (
"the message type was lost: %s" % kinds)
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_an_uncaught_error_reaches_the_pageerror_listener(firefox_binary):
def test_an_uncaught_error_reaches_the_pageerror_listener(firefox_binary, monkeypatch):
"""A page that throws must reach `page.on("pageerror")`, with the message
intact - that is the only way a caller learns the site broke."""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(NOISY))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -626,18 +620,17 @@ def test_an_uncaught_error_reaches_the_pageerror_listener(firefox_binary):
page.on("pageerror", lambda e: errors.append(str(e)))
page.goto(url)
page.click("#boom")
page.wait_for_timeout(600)
wait_until(lambda: errors, 30, lambda: page.wait_for_timeout(50))
assert errors, "the uncaught error never arrived"
assert "undefinedFunctionCall" in " ".join(errors), (
"the message was lost: %s" % errors)
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_a_dialog_can_be_ANSWERED_and_not_answering_hangs_the_page(
firefox_binary):
firefox_binary, monkeypatch):
"""⛔ THE ONE OBJECT WHERE FORGETTING IS A HANG, NOT A LEAK. A dialog
blocks the content process inside `window.alert`, so an unanswered one
makes every later command time out with no hint about the cause.
@@ -646,7 +639,7 @@ def test_a_dialog_can_be_ANSWERED_and_not_answering_hangs_the_page(
that safety net only works if the event ARRIVES - which is what this
asserts. The second half then checks the explicit path.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(NOISY))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -664,23 +657,22 @@ def test_a_dialog_can_be_ANSWERED_and_not_answering_hangs_the_page(
page.on("dialog", answer)
page.goto(url)
page.click("#alert")
page.wait_for_timeout(600)
wait_until(lambda: seen, 30, lambda: page.wait_for_timeout(50))
assert seen == [("alert", "are you sure")], seen
# And the page is still alive: if the dialog had not been
# answered, this would time out instead of returning.
assert page.title() == "events"
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_an_unanswered_dialog_is_dismissed_by_the_client(firefox_binary):
def test_an_unanswered_dialog_is_dismissed_by_the_client(firefox_binary, monkeypatch):
"""⛔ The known-bad of the wiring above: with NO listener the client
dismisses on its own, and the page keeps running. If the event never
reached the client, this would hang - so a green here proves the event
arrives even when nobody visibly consumes it."""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(NOISY))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -694,7 +686,6 @@ def test_an_unanswered_dialog_is_dismissed_by_the_client(firefox_binary):
assert page.title() == "events", (
"the page is stuck: the dialog event never reached the client")
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@@ -714,8 +705,8 @@ def test_clearing_cookies_with_a_FILTER_is_refused_not_widened():
@pytest.mark.e2e
def test_cookies_round_trip_through_the_public_API(firefox_binary):
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
def test_cookies_round_trip_through_the_public_API(firefox_binary, monkeypatch):
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -733,17 +724,16 @@ def test_cookies_round_trip_through_the_public_API(firefox_binary):
context.clear_cookies()
assert not [c for c in context.cookies() if c["name"] == "a"]
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_a_screenshot_comes_back_as_real_png_bytes(firefox_binary):
def test_a_screenshot_comes_back_as_real_png_bytes(firefox_binary, monkeypatch):
"""⛔ THE MAGIC NUMBER, not the length. A screenshot that is the string
"None" or a base64 blob nobody decoded is still bytes and still non-empty:
the only assertion that separates a real image from a plausible one is the
PNG signature."""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -758,13 +748,12 @@ def test_a_screenshot_comes_back_as_real_png_bytes(firefox_binary):
"not a PNG: first bytes are %r" % shot[:12])
assert len(shot) > 1000, len(shot)
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_the_viewport_can_be_resized(firefox_binary):
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
def test_the_viewport_can_be_resized(firefox_binary, monkeypatch):
monkeypatch.setenv(factory.CHOICE_ENV, factory.JUGGLER)
srv = LocalServer(("127.0.0.1", 0), _serve(PAGE))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
@@ -778,7 +767,6 @@ def test_the_viewport_can_be_resized(firefox_binary):
assert page.evaluate("() => window.innerWidth") == 640
assert page.evaluate("() => window.innerHeight") == 480
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
+4 -1
View File
@@ -176,13 +176,16 @@ def test_only_one_place_reads_the_key_delay():
assert readers == {"_key_delay", "_pointer"}, readers
# The time of each event is `e.timeStamp`, which is when the browser CREATED the event, not `performance.now()` read when
# the handler happens to run: on a loaded machine the content process runs two handlers back to back (74 ms apart for
# keys the driver sent 150 ms apart, four reds), and the gap between the two reads says nothing about when the keys left.
PAGE = b"""<!doctype html><meta charset=utf-8>
<input id=f>
<script>
window.__ev = [];
for (const k of ["keydown", "keyup"])
document.getElementById("f").addEventListener(k, e =>
__ev.push([k, e.key, performance.now()]));
__ev.push([k, e.key, e.timeStamp]));
</script>"""
@@ -14,10 +14,11 @@ from __future__ import annotations
import http.server
import threading
import time
import pytest
from _waits import wait_until
pytestmark = pytest.mark.e2e
FRAME = (b"<!doctype html><title>f</title><body style='margin:0'><button id=b "
@@ -111,10 +112,14 @@ class _Handler(http.server.BaseHTTPRequestHandler):
pass
def _record(page, action):
def _record(page, action, count):
"""The events the action made, once the last one of the sequence expected has been heard (a deadline of 30 s, not a
pause: a slow machine delivers the same events later), then one frame more so an event that should not be there has
its turn to come, and the whole log is read."""
page.evaluate("window.__log.length = 0")
action()
time.sleep(0.4)
wait_until(lambda: page.evaluate("window.__log.length") >= count, 30, lambda: page.wait_for_timeout(50))
page.evaluate("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
return page.evaluate("window.__log.slice()")
@@ -127,8 +132,9 @@ def test_the_events_of_the_page_and_of_an_iframe_of_its_process_keep_their_order
with InvisiblePlaywright(binary_path=firefox_binary, headless=True, humanize=False) as browser:
page = browser.new_context().new_page()
page.goto("http://127.0.0.1:%d/" % server.server_address[1], wait_until="load")
page.wait_for_function("window.__log && document.getElementById('f').contentDocument.readyState === 'complete'")
time.sleep(0.5)
# the iframe's load handler has run: it hands the log to the frame and puts the recorders on its document
page.wait_for_function("window.__log && document.getElementById('f').contentDocument.readyState === 'complete'"
" && document.getElementById('f').contentWindow.__log === window.__log")
actions = {
"top click": lambda: (page.mouse.move(60, 35), page.mouse.down(), page.mouse.up()),
"frame click": lambda: (page.mouse.move(260, 150), page.mouse.down(), page.mouse.up()),
@@ -139,7 +145,7 @@ def test_the_events_of_the_page_and_of_an_iframe_of_its_process_keep_their_order
}
got = {}
for name, action in actions.items():
log = _record(page, action)
log = _record(page, action, len(EXPECTED[name]))
stamps = [row[-1] for row in log]
assert stamps == sorted(stamps), "%s: the time stamps go backwards" % name
assert all(stamp <= page.evaluate("performance.now()") for stamp in stamps), "%s: a time stamp in the future" % name
@@ -35,11 +35,11 @@ from _waits import awatch
pytestmark = pytest.mark.e2e
#: The longest any wait of this file lasts; no healthy run comes near it. It is the only clock the verdicts have.
DEADLINE = 8.0
DEADLINE = 30.0
#: The timeout of the gotos that are stopped or replaced below. A goto that is not stopped waits for its held answer and
#: ends at this timeout with another error: it is the bound of the waits that lead up to the stop, nothing narrower.
GOTO_TIMEOUT_MS = 15000
GOTO_TIMEOUT_MS = 30000
FISSION_ON = {
"fission.autostart": True,
@@ -183,8 +183,10 @@ def test_a_second_goto_to_a_third_site_interrupts_the_first_and_lands(firefox_bi
return first, second, page.url
first, second, url = _run(firefox_binary, scenario)
assert first is not None and "is interrupted by another navigation" in first, first
assert second is None, second
# what the server had been asked for: whether the second goto's request left at all, or waited behind the held response
asked = sorted(sites["arrived"])
assert first is not None and "is interrupted by another navigation" in first, (first, asked)
assert second is None, (second, asked)
assert url == "http://c.test:" + url.split(":")[2], url
@@ -224,7 +226,7 @@ def test_an_iframe_removed_while_it_loads_is_aborted_then_gone(firefox_binary, s
# insertion, whatever the machine: a test that only reads the list could read it before the frame existed)
seen = await awatch(lambda: (counts["attached"], counts["detached"], len(page.frames)),
lambda state: state[0] >= 1 and state[1] >= 1 and state[2] == 1,
DEADLINE + 2, lambda: page.wait_for_timeout(100))
DEADLINE, lambda: page.wait_for_timeout(100))
return [f.url for f in page.frames], seen.render()
urls, seen = _run(firefox_binary, scenario)
@@ -172,7 +172,7 @@ def test_networkidle_arrives_on_a_routed_page_through_a_served_browser(firefox_b
for attempt in range(3): # fresh pages, the way a client fetches one address after another
try:
# the timeout of the goto is the detector of a networkidle that never comes
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=20000)
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=30000)
except Exception as e:
pytest.fail("networkidle did not come on attempt %d (answers to a closed request: %s): %s" % (
attempt, ANSWER_ERRORS[:3], e))
@@ -215,7 +215,7 @@ def test_networkidle_arrives_when_the_client_answers_all_requests_concurrently_a
await ctx.route("**/*", route)
page = await ctx.new_page()
for attempt in range(3):
await page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
await page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=30000)
await ctx.close()
await browser.close()
@@ -243,7 +243,7 @@ def test_one_page_reused_for_many_addresses_reaches_networkidle_every_time(firef
page = ctx.new_page()
kinds = ["cancel_fetch", "cancel_img", "cancel_iframe", "beacon", "cancel_navigation", "oop_iframe"] * 2
for n, kind in enumerate(kinds):
page.goto(site + "?kind=%s&n=%d" % (kind, n), wait_until="networkidle", timeout=20000)
page.goto(site + "?kind=%s&n=%d" % (kind, n), wait_until="networkidle", timeout=30000)
ctx.close()
browser.close()
finally:
@@ -277,7 +277,7 @@ def test_a_plain_route_handler_is_not_poisoned_by_a_request_the_page_cancelled(f
ctx.route("**/*", plain)
page = ctx.new_page()
for attempt in range(3):
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=30000)
ctx.close()
browser.close()
finally:
@@ -49,7 +49,7 @@ pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
SCHEMES = ["context_only", "launch_and_context"]
#: How long to wait for a name the case must have asked to reach the DoH, in seconds.
ASKED_SECONDS = 25
ASKED_SECONDS = 30
#: How long the page of the `push` case may take to register its service worker and read its subscription, in seconds.
PUSH_SECONDS = 40
#: After the context of the `closing` case is closed, the browser lives on this long: the requests of the page's last moments are made now.
@@ -82,10 +82,12 @@ from _witness import Witness
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: How long the page waits for the browser to try the target, in milliseconds (the ICE agent retransmits STUN and TURN at 0, 0.1, 0.3, 0.7 s...).
#: How long the test leaves the probe alive AFTER the road it was meant to take has been seen (or, with no such road to see, after it started), in milliseconds:
#: the window in which a road around the proxy would show (the ICE agent retransmits STUN and TURN at 0, 0.1, 0.3, 0.7 s...). It looks for something that must
#: NOT happen, so a slow machine can only make it weaker, never red; the page does not hold the probe with a timer of its own, so the probe is alive for the whole of it.
WAIT_MS = {"fetch": 2500, "websocket": 2500, "stun": 5000, "turn_udp": 5000, "turn_tcp": 5000, "turns_tcp": 5000}
#: How long to wait, in seconds, for the proxy or the DoH to have been handed what the probe asked for.
EVIDENCE_SECONDS = 20
EVIDENCE_SECONDS = 30
#: The lab's own prefs, on top of the DoH provider of ``PREFS``. Every name of a probe is answered with the address of THIS host (the witness), and on
#: a LAN or a runner that is an RFC 1918 address: the engine's DoH client DROPS such an answer unless ``network.trr.allow-rfc1918`` is true
#: (TRR.cpp / DNSPacket.cpp: ``aAllowRFC1918 || !addr.IsIPAddrLocal()``), so the name would resolve to nothing and the probe would never connect
@@ -143,10 +145,10 @@ WINDOW_CASES = [WindowCase(w, p) for w in ("iframe", "popup") for p in ("socks5"
CONTROL_CASES = [WindowCase("attached", p) for p in ("socks5", "http")]
#: The two ICE servers of a window case, by name: the STUN server over UDP and the TURN server over TCP.
ICE_KINDS = ("stun", "turn")
#: How long the page waits for the gathering to end, in milliseconds (the witness answers nothing: the ICE agent retries until this ends).
GATHER_MS = 6000
#: How long the page waits for a closed popup to say ``closed``, in milliseconds.
CLOSED_MS = 5000
#: How long the page waits for the gathering of a window's PeerConnection to start, in milliseconds (the deadline of the wait: a healthy run takes a few hundred).
GATHER_MS = 30000
#: How long the page waits for a closed popup to say ``closed``, in milliseconds (the deadline of the wait).
CLOSED_MS = 30000
#: What each case is expected to do, by engine. "green" is the contract; "RED" names the road that leaves the proxy. Held by
#: test_the_egress_sink_helpers.py (every id is a case, and a RED has its reason).
@@ -194,24 +196,27 @@ EXPECTED_OCSP: Dict[str, Dict[str, str]] = {
#: How long the negative control waits for an OCSP request that must not come, in seconds (the soft-fail timeout of the engine is 2 s).
OCSP_SETTLE_SECONDS = 4
_FETCH_JS = """async ([host, port, waitMs]) => {
#: The probes START the thing and leave it alive (the page holds no timer of its own that would end it): the test waits for the road it was meant to take, leaves the
#: window of ``WAIT_MS``, then ends it with ``_STOP_JS``.
_FETCH_JS = """([host, port]) => {
fetch('http://' + host + ':' + port + '/f', {mode: 'no-cors'}).catch(() => {});
await new Promise((resolve) => setTimeout(resolve, waitMs));
}"""
_WEBSOCKET_JS = """async ([host, port, waitMs]) => {
try { const ws = new WebSocket('ws://' + host + ':' + port + '/s'); ws.onerror = () => {}; } catch (e) {}
await new Promise((resolve) => setTimeout(resolve, waitMs));
_WEBSOCKET_JS = """([host, port]) => {
try { window.__ws = new WebSocket('ws://' + host + ':' + port + '/s'); window.__ws.onerror = () => {}; } catch (e) {}
}"""
_STOP_JS = """() => {
try { if (window.__pc) window.__pc.close(); } catch (e) {}
try { if (window.__ws) window.__ws.close(); } catch (e) {}
}"""
def _ice_js(url_expression):
return """async ([host, port, waitMs]) => {
const pc = new RTCPeerConnection({iceServers: [{urls: [%s], username: 'u', credential: 'p'}]});
return """async ([host, port]) => {
const pc = window.__pc = new RTCPeerConnection({iceServers: [{urls: [%s], username: 'u', credential: 'p'}]});
pc.createDataChannel('d');
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve) => setTimeout(resolve, waitMs));
pc.close();
}""" % url_expression
@@ -275,11 +280,13 @@ _WINDOW_ICE_JS = """async ([how, stunHost, turnHost, port, gatherMs, closedMs])
} catch (e) { out.error = String(e && e.name ? e.name + ': ' + e.message : e); }
if (pc) {
try {
// until the gathering has STARTED (the state leaves 'new'), for gatherMs; the PeerConnection stays alive (window.__pc) and the test closes it after it has
// seen the road it was meant to take
window.__pc = pc;
const t0 = Date.now();
while (pc.iceGatheringState !== 'complete' && Date.now() - t0 < gatherMs) await sleep(100);
while (pc.iceGatheringState === 'new' && Date.now() - t0 < gatherMs) await sleep(50);
out.state = pc.iceGatheringState;
out.started = out.state !== 'new';
pc.close();
} catch (e) { out.error = (out.error ? out.error + '; ' : '') + String(e && e.name ? e.name + ': ' + e.message : e); }
}
return out;
@@ -393,9 +400,11 @@ def test_a_probe_of_a_context_leaves_only_through_its_proxy(case, firefox_binary
with _launch(firefox_binary) as browser:
context, page = _page_in(browser, proxy=proxy.proxy)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
page.evaluate(PROBE_JS[case.kind], [host, port, WAIT_MS[case.kind]])
page.evaluate(PROBE_JS[case.kind], [host, port])
done = _the_work_was_done(case, lab, doh, proxy)
reached = ds.wait_until(done, EVIDENCE_SECONDS) if done else None
ds.wait_until(lambda: False, WAIT_MS[case.kind] / 1000.0) # the window of a road around the proxy, with the probe alive
page.evaluate(_STOP_JS)
context.close()
watcher.stop()
@@ -423,8 +432,9 @@ def test_the_same_probe_with_no_proxy_is_heard_by_the_witness(kind, firefox_bina
with _launch(firefox_binary) as browser:
page = browser.new_context(ignore_https_errors=True).new_page()
page.goto("about:blank")
page.evaluate(PROBE_JS[kind], [lab.witness.address, lab.witness.port, WAIT_MS[kind]])
page.evaluate(PROBE_JS[kind], [lab.witness.address, lab.witness.port])
reached = ds.wait_until(lambda: lab.witness.heard()["tcp" if case.tcp else "udp"], EVIDENCE_SECONDS)
page.evaluate(_STOP_JS)
watcher.stop()
assert reached, "no proxy, and the %s probe by IP did not reach the witness at %s: %s" % (kind, lab.witness.target, lab.witness.heard())
@@ -466,7 +476,7 @@ def _run_window_case(case: WindowCase, firefox_binary, lab: Lab, doh, pages, gat
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
if case.window == "popup":
page.evaluate(_POPUP_BUTTON_JS)
page.click("#open-dead", timeout=10000)
page.click("#open-dead", timeout=30000)
outcome = page.evaluate(_WINDOW_ICE_JS, [case.window, stun_host, turn_host, port, GATHER_MS, CLOSED_MS])
if outcome["started"]:
def done() -> bool:
@@ -475,6 +485,8 @@ def _run_window_case(case: WindowCase, firefox_binary, lab: Lab, doh, pages, gat
return _was_handed(case, proxy, turn_host, port)
return (lab.witness.address, port) in proxy.connects and bool(doh.queries_for(stun_host, QTYPE_A))
reached = ds.wait_until(done, EVIDENCE_SECONDS)
ds.wait_until(lambda: False, WAIT_MS["turn_tcp"] / 1000.0) # the window of a road around the proxy, with the PeerConnection alive
page.evaluate(_STOP_JS)
context.close()
watcher.stop()
return proxy, outcome, reached
+6 -3
View File
@@ -67,11 +67,14 @@ def _rows(profile: str) -> list:
@pytest.mark.e2e
def test_cookies_and_local_storage_survive_to_the_next_session(firefox_binary):
def test_cookies_and_local_storage_survive_to_the_next_session(firefox_binary, local_https_page):
"""⛔ BOTH STORES, AND THE DISK IN BETWEEN. A cookie alone could survive a
fix that only moved cookies; the on-disk read separates "the second session
saw it" from "it was actually persisted", which is the property a login
relies on when the machine restarts.
The page is the test's own server on loopback, the same origin in both sessions (a real site is a third party: its outage, its redirect or the
network of the runner would be this test's red).
"""
from invisible_playwright import InvisiblePlaywright
@@ -79,7 +82,7 @@ def test_cookies_and_local_storage_survive_to_the_next_session(firefox_binary):
with InvisiblePlaywright(headless=True, seed=11, binary_path=firefox_binary,
profile_dir=profile) as ctx:
page = ctx.new_page()
page.goto("https://example.com", timeout=60000)
page.goto(local_https_page, timeout=60000)
page.evaluate("() => { localStorage.setItem('kept', 'yes');"
" document.cookie = 'kept=yes; max-age=86400; SameSite=Lax'; }")
assert page.evaluate("localStorage.getItem('kept')") == "yes"
@@ -92,7 +95,7 @@ def test_cookies_and_local_storage_survive_to_the_next_session(firefox_binary):
with InvisiblePlaywright(headless=True, seed=11, binary_path=firefox_binary,
profile_dir=profile) as ctx:
page = ctx.new_page()
page.goto("https://example.com", timeout=60000)
page.goto(local_https_page, timeout=60000)
assert page.evaluate("localStorage.getItem('kept')") == "yes", "localStorage did not survive"
assert "kept=yes" in page.evaluate("document.cookie"), "the cookie did not survive"
assert ("kept", "yes") in [(c["name"], c["value"]) for c in ctx.cookies()]
+28 -28
View File
@@ -106,7 +106,7 @@ def _open_context_page(browser):
def _goto_opener(page, harness):
page.goto(harness["opener_url"], wait_until="domcontentloaded",
timeout=30_000)
page.wait_for_selector("#open-simple", timeout=10_000)
page.wait_for_selector("#open-simple", timeout=30_000)
def test_window_open_plain_is_a_page(browser, harness):
@@ -118,10 +118,10 @@ def test_window_open_plain_is_a_page(browser, harness):
seen = []
page.on("popup", lambda p: seen.append(p))
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-simple")
popup = info.value
popup.wait_for_url(harness["popup_url"], timeout=10_000)
popup.wait_for_url(harness["popup_url"], timeout=30_000)
assert popup.url == harness["popup_url"], (
f"popup landed on the wrong URL: {popup.url!r}")
@@ -134,9 +134,9 @@ def test_window_open_plain_is_a_page(browser, harness):
"popup.opener() did not resolve to the opening page")
# A popup must behave like any other page.
popup.wait_for_selector("#ping", timeout=10_000)
popup.wait_for_selector("#ping", timeout=30_000)
popup.click("#ping")
popup.wait_for_function("document.title === 'pong'", timeout=10_000)
popup.wait_for_function("document.title === 'pong'", timeout=30_000)
assert popup.title() == "pong"
popup.close()
@@ -154,15 +154,15 @@ def test_window_open_with_features_is_a_page(browser, harness):
ctx, page = _open_context_page(browser)
try:
_goto_opener(page, harness)
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-features")
popup = info.value
popup.wait_for_url(harness["popup_url"], timeout=10_000)
popup.wait_for_url(harness["popup_url"], timeout=30_000)
assert popup.url == harness["popup_url"]
assert len(ctx.pages) == 2
assert popup.opener() == page
popup.wait_for_selector("#ping", timeout=10_000)
popup.wait_for_selector("#ping", timeout=30_000)
popup.close()
assert popup.is_closed()
finally:
@@ -185,11 +185,11 @@ def test_window_open_with_a_size_keeps_that_size(browser, harness):
try:
_goto_opener(page, harness)
tab_size = page.evaluate("[innerWidth, innerHeight]")
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-features")
popup = info.value
popup.wait_for_url(harness["popup_url"], timeout=10_000)
popup.wait_for_load_state("load", timeout=10_000)
popup.wait_for_url(harness["popup_url"], timeout=30_000)
popup.wait_for_load_state("load", timeout=30_000)
# The size is final when the window is shown; reading it once more
# after a beat catches a late resize to the context viewport.
first = popup.evaluate("[innerWidth, innerHeight]")
@@ -203,10 +203,10 @@ def test_window_open_with_a_size_keeps_that_size(browser, harness):
f"keep it.")
popup.close()
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-simple")
tab = info.value
tab.wait_for_url(harness["popup_url"], timeout=10_000)
tab.wait_for_url(harness["popup_url"], timeout=30_000)
assert tab.evaluate("[innerWidth, innerHeight]") == tab_size, (
"a window.open without features is a tab of the same window and "
"must have the opener's size")
@@ -224,10 +224,10 @@ def test_window_open_noopener_is_a_tracked_page(browser, harness):
ctx, page = _open_context_page(browser)
try:
_goto_opener(page, harness)
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-noopener")
popup = info.value
popup.wait_for_url(harness["popup_url"], timeout=10_000)
popup.wait_for_url(harness["popup_url"], timeout=30_000)
assert popup.url == harness["popup_url"]
assert popup in ctx.pages
@@ -236,9 +236,9 @@ def test_window_open_noopener_is_a_tracked_page(browser, harness):
assert popup.evaluate("window.opener === null"), (
"the test's noopener shape is broken: in-page window.opener "
"should be null")
popup.wait_for_selector("#ping", timeout=10_000)
popup.wait_for_selector("#ping", timeout=30_000)
popup.click("#ping")
popup.wait_for_function("document.title === 'pong'", timeout=10_000)
popup.wait_for_function("document.title === 'pong'", timeout=30_000)
assert popup.title() == "pong"
popup.close()
assert popup.is_closed()
@@ -252,10 +252,10 @@ def test_target_blank_link_expect_popup(browser, harness):
ctx, page = _open_context_page(browser)
try:
_goto_opener(page, harness)
with page.expect_popup(timeout=15_000) as info:
with page.expect_popup(timeout=30_000) as info:
page.click("#open-link")
popup = info.value
popup.wait_for_url(harness["popup_url"], timeout=10_000)
popup.wait_for_url(harness["popup_url"], timeout=30_000)
assert popup.url == harness["popup_url"]
assert popup in ctx.pages
@@ -276,15 +276,15 @@ def test_popup_in_persistent_context(firefox_binary, harness, tmp_path):
profile_dir=str(tmp_path / "profile")) as ctx:
page = ctx.new_page()
_goto_opener(page, harness)
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-simple")
popup = info.value
popup.wait_for_url(harness["popup_url"], timeout=10_000)
popup.wait_for_url(harness["popup_url"], timeout=30_000)
assert popup.url == harness["popup_url"]
assert popup in ctx.pages
assert popup.opener() == page
popup.wait_for_selector("#ping", timeout=10_000)
popup.wait_for_selector("#ping", timeout=30_000)
popup.close()
assert popup.is_closed()
@@ -376,13 +376,13 @@ def test_window_open_features_headed_humanized(firefox_binary, harness):
try:
page = ctx.new_page()
_goto_opener(page, harness)
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-features")
popup = info.value
popup.wait_for_url(harness["popup_url"], timeout=10_000)
popup.wait_for_url(harness["popup_url"], timeout=30_000)
assert popup.url == harness["popup_url"]
assert popup in ctx.pages
popup.wait_for_selector("#ping", timeout=10_000)
popup.wait_for_selector("#ping", timeout=30_000)
popup.close()
assert popup.is_closed()
finally:
@@ -403,10 +403,10 @@ def test_popup_document_reaches_the_context(browser, harness):
requests, responses = [], []
ctx.on("request", lambda r: requests.append(r.url))
ctx.on("response", lambda r: responses.append(r))
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-simple")
popup = info.value
popup.wait_for_load_state("load", timeout=10_000)
popup.wait_for_load_state("load", timeout=30_000)
url = harness["popup_url"]
# until the document's request and its response have been heard (a condition with a deadline, not 500 ms);
# then a short window is left only for a DUPLICATE, which is what the two counts below look for
@@ -429,7 +429,7 @@ def test_a_popup_the_site_closes_is_closed(browser, harness):
ctx, page = _open_context_page(browser)
try:
_goto_opener(page, harness)
with ctx.expect_page(timeout=15_000) as info:
with ctx.expect_page(timeout=30_000) as info:
page.click("#open-closing")
popup = info.value
closes = []
@@ -15,7 +15,17 @@ import pytest
TYPE = re.compile(r"Setting remoteType of process (\d+) to (\S+)")
def _remote_types(tmp_path, binary, **option):
def _read_types(tmp_path, base):
types = []
for path in sorted(tmp_path.glob(base.name + "*")):
types += [m.group(2) for m in TYPE.finditer(path.read_text(encoding="utf-8", errors="replace"))]
return types
def _remote_types(tmp_path, binary, until, window=0.0, **option):
"""The types of the processes the engine made. It waits (30 s) until ``until(types)`` holds, which is the positive thing the verdict needs to read, and then leaves
``window`` seconds in which a process that must NOT be born could show: that window looks for something that must not happen, so a slow machine can only make it weaker."""
from _waits import wait_until
from invisible_playwright import InvisiblePlaywright
mp = pytest.MonkeyPatch()
@@ -27,18 +37,16 @@ def _remote_types(tmp_path, binary, **option):
timezone="America/New_York", **option) as browser:
page = browser.new_context().new_page()
page.goto("about:blank")
time.sleep(10)
wait_until(lambda: until(_read_types(tmp_path, base)), 30, lambda: page.wait_for_timeout(100))
time.sleep(window)
finally:
mp.undo()
types = []
for path in sorted(tmp_path.glob(base.name + "*")):
types += [m.group(2) for m in TYPE.finditer(path.read_text(encoding="utf-8", errors="replace"))]
return types
return _read_types(tmp_path, base)
@pytest.mark.e2e
def test_without_the_option_the_new_tab_page_is_preloaded_in_its_own_process(firefox_binary, tmp_path):
types = _remote_types(tmp_path, firefox_binary)
types = _remote_types(tmp_path, firefox_binary, lambda found: "privilegedabout" in found)
assert types, "the engine wrote no line about its processes: the control cannot judge"
assert "privilegedabout" in types, "the retail keeps the New Tab page preloaded: %s" % sorted(set(types))
@@ -49,6 +57,6 @@ def test_asked_to_turn_the_preload_off_there_is_no_privileged_about_process(fire
if "preload_newtab" not in inspect.signature(core_prefs.compose_session_prefs).parameters:
pytest.skip("this core does not know preload_newtab yet")
types = _remote_types(tmp_path, firefox_binary, preload_newtab=False)
types = _remote_types(tmp_path, firefox_binary, bool, window=10, preload_newtab=False)
assert types, "the engine wrote no line about its processes: the control cannot judge"
assert "privilegedabout" not in types, "a process of the preloaded New Tab page was born: %s" % sorted(set(types))
+2 -2
View File
@@ -64,7 +64,7 @@ def test_navigation_wait(firefox_binary, redirect_origins, wait, requestless):
page.goto(start + "/start")
url = destination if requestless else start + "/redirect"
if wait == "expect_navigation":
with page.expect_navigation(url=destination, timeout=5000) as navigation:
with page.expect_navigation(url=destination, timeout=30000) as navigation:
page.evaluate("url => { location.href = url; }", url)
response = navigation.value
if requestless:
@@ -74,5 +74,5 @@ def test_navigation_wait(firefox_binary, redirect_origins, wait, requestless):
assert response.url == destination
else:
page.evaluate("url => { setTimeout(() => location.href = url, 100); }", url)
page.wait_for_url(destination, timeout=5000)
page.wait_for_url(destination, timeout=30000)
assert page.url == page.evaluate("location.href") == destination
+36 -29
View File
@@ -31,6 +31,7 @@ from invisible_core.juggler.connection import EventListeners
from _screencast_evidence import Stream, engine_screencast_lines
from _servers import LocalServer
from _waits import wait_until
PAGE = b"""<!doctype html><html><head><title>screencast</title>
<style>html,body{margin:0;background:#FF00FF;height:100%}</style>
@@ -205,15 +206,13 @@ def test_a_screencast_frame_is_a_jpeg_of_the_whole_window(firefox_binary):
pytest.skip("this engine has no screencast (it needs "
"firefox-28 or later): %s" % refused)
raise
deadline = time.time() + 15
while len(frames) < 3 and time.time() < deadline:
time.sleep(0.1)
wait_until(lambda: len(frames) >= 3, 30, lambda: time.sleep(0.1))
page.screencast.stop()
if not frames:
evidence = engine_screencast_lines(page)
finally:
srv.shutdown()
assert frames, ("no frame arrived in 15 s\n%s\n"
assert frames, ("no frame arrived in 30 s\n%s\n"
"engine output (lines starting with 'screencast:'):\n%s"
% (stream.describe(), evidence))
first = frames[0]
@@ -304,9 +303,11 @@ def test_asking_for_a_higher_rate_actually_delivers_more_frames(firefox_binary):
Interleaved is not possible here - a screencast is per page and the rate is
fixed at start - so the arms are two pages of the same browser, same page
served, same duration, and the assertion is on the RATIO rather than on
either count: the absolute rate depends on the machine, and the claim is
that asking for more gets more.
served, each waited for until it has delivered a number of frames (not for
a fixed time: a loaded machine delivered none in 3 s), and the assertion is
on the RATIO of the rates of the frames that came, not on either count: the
absolute rate depends on the machine, and the claim is that asking for more
gets more.
Measured 2026-09-08 on this machine: 10 asked delivered 9.6-9.8 fps, 25
asked delivered 23.8-24.0. The floor below is deliberately far from that -
@@ -338,7 +339,9 @@ def test_asking_for_a_higher_rate_actually_delivers_more_frames(firefox_binary):
url = "http://127.0.0.1:%d/" % srv.server_address[1]
from invisible_playwright import InvisiblePlaywright
def count(page, fps, seconds=3.0):
def count(page, fps, wanted):
"""Starts a stream at ``fps`` and waits until ``wanted`` frames have come (a deadline of 30 s, not a pause: a loaded
machine takes longer for the same frames), then stops it."""
stream = Stream("asking for %d fps" % fps)
page.goto(url)
try:
@@ -348,50 +351,55 @@ def test_asking_for_a_higher_rate_actually_delivers_more_frames(firefox_binary):
pytest.skip("this engine has no screencast (it needs "
"firefox-28 or later): %s" % refused)
raise
time.sleep(seconds)
wait_until(lambda: len(stream.frames) >= wanted, 30, lambda: time.sleep(0.05))
page.screencast.stop()
return stream
seconds = 3.0
slow_fps, fast_fps = 2, 25
slow_wanted, fast_wanted = 6, 10
try:
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
headless=True) as browser:
slow_page, fast_page = browser.new_page(), browser.new_page()
slow_stream = count(slow_page, slow_fps, seconds)
fast_stream = count(fast_page, fast_fps, seconds)
slow_stream = count(slow_page, slow_fps, slow_wanted)
fast_stream = count(fast_page, fast_fps, fast_wanted)
# Read while the browser is up: the output goes with the process.
evidence = engine_screencast_lines(fast_page)
finally:
srv.shutdown()
slow, fast = len(slow_stream.frames), len(fast_stream.frames)
assert slow and fast, (
"no frames at all: %d and %d\n%s\n%s\n"
assert slow >= slow_wanted and fast >= fast_wanted, (
"not the frames asked for within 30 s: %d of %d and %d of %d\n%s\n%s\n"
"engine output (lines starting with 'screencast:'):\n%s"
% (slow, fast, slow_stream.describe(), fast_stream.describe(), evidence))
% (slow, slow_wanted, fast, fast_wanted, slow_stream.describe(), fast_stream.describe(), evidence))
# The rates are those of the frames that came, from the engine's stamp of the first to that of the last: how long the
# first took to start, how long a window was, and a burst a stalled client received at once are no part of them.
slow_rate, fast_rate = slow_stream.rate(), fast_stream.rate()
assert slow_rate is not None and fast_rate is not None, "no time between the frames: %s / %s" % (
slow_stream.stamps, fast_stream.stamps)
# The half that does not depend on the machine: a cap only pushes the rate
# down, so this one is answerable however slow the runner is.
ceiling = slow_fps * seconds * 2
assert slow <= ceiling, (
"asking for %d frames a second delivered %d in %.0f seconds (%.1f "
"fps), which is not a cap being honoured - it is what this machine "
ceiling = slow_fps * 2
assert slow_rate <= ceiling, (
"asking for %d frames a second delivered %d frames at %.1f fps, which is "
"not a cap being honoured - it is what this machine "
"produces when nothing limits it, so the rate the caller asks for is "
"not reaching the engine"
% (slow_fps, slow, seconds, slow / seconds))
% (slow_fps, slow, slow_rate))
assert fast > slow * 1.5, (
"asking for %d frames a second delivered %d in %.0f seconds and "
"asking for %d delivered %d: the rate the caller asks for is not "
assert fast_rate > slow_rate * 1.5, (
"asking for %d frames a second delivered %.1f fps and "
"asking for %d delivered %.1f fps: the rate the caller asks for is not "
"reaching the engine.\n"
" Before believing that, check the second number against the "
"machine: the fast arm is limited by what this host can render, not "
"by what was asked (%d would be %.0f frames), so a fast arm far below "
"by what was asked (%d fps asked), so a fast arm far below "
"its request means the host is the ceiling and this comparison cannot "
"answer the question."
% (fast_fps, fast, seconds, slow_fps, slow,
fast_fps, fast_fps * seconds))
% (fast_fps, fast_rate, slow_fps, slow_rate, fast_fps))
def test_a_dead_stream_is_described_with_the_engine_lines_and_the_clock():
@@ -407,9 +415,8 @@ def test_a_dead_stream_is_described_with_the_engine_lines_and_the_clock():
b"JavaScript warning: something\n"
b"screencast: StartCapture failed\n"
b" screencast: this widget has no native window id\n"))
deadline = time.time() + 5
while len(output.tail()) < 3 and time.time() < deadline:
time.sleep(0.01)
# the reader thread of the output has taken the three lines (a deadline of 30 s, not 5: a loaded machine runs it late)
assert wait_until(lambda: len(output.tail()) >= 3, 30, lambda: time.sleep(0.01)), output.tail()
server = SimpleNamespace(object=lambda guid: SimpleNamespace(
conn=SimpleNamespace(output=output)))
page = SimpleNamespace(_impl_obj=SimpleNamespace(
+5 -1
View File
@@ -197,7 +197,11 @@ def shots(tmp_path_factory, firefox_binary):
# reads back where it actually went rather than assuming, which
# is the same mistake in miniature as the defect it covers.
page.evaluate("() => window.scrollTo(1400, 0)")
page.wait_for_timeout(300)
# until the page IS where the clamp puts it (the scrollable width, at most 1400), not 300 ms; if it never lands, `landed` below is
# read at the deadline and the assertions on it say so
wait_until(lambda: page.evaluate(
"() => Math.round(window.scrollX) === Math.round(Math.min(1400, document.documentElement.scrollWidth"
" - document.documentElement.clientWidth))"), 30, lambda: page.wait_for_timeout(50))
landed = page.evaluate("() => Math.round(window.scrollX)")
page.screenshot(path=str(out / "sideways.png"))
wide = page.evaluate(
@@ -25,7 +25,7 @@ pytestmark = [
pytest.mark.skipif(not sys.platform.startswith("linux"), reason="the Linux text path"),
]
DEADLINE_S = 15
DEADLINE_S = 30
PAGE = ("<!doctype html><meta charset=utf-8><body style='margin:8px;background:#fff;color:#000'>"
"<h1 style='font-family:serif'>Serif heading</h1>"
@@ -157,7 +157,7 @@ def test_the_compositor_is_webrender_software_whatever_the_machine(firefox_binar
#: RTCPeerConnection with no ICE servers and waits for the gather, draws 200 DOM elements and one 2D canvas frame; the browser goes to
#: the next copy of it, 10 times.
ROUNDS = 10
ICE_WAIT_MS = 15000
ICE_WAIT_MS = 30000
SCENE = """<!doctype html><meta charset=utf-8><title>scenario</title>
<body><div id=root></div><canvas id=c width=320 height=200></canvas>
<script>
@@ -201,22 +201,20 @@ window.__ready = (async () => {
#: 1.5 s is about 4.7 times what the declared engine used and 0.55 times the least the undeclared one used: a run that is slow for
#: the runner's sake stays under it, and the hardware WebRender, which keeps the GPU process busy for every frame, does not.
#: This test starts ONE browser, which the GPU process has to itself, so it is at most what a browser used when four shared the runner.
#: It is CPU time (user + kernel of the process, `_cpu_by_type`), not wall-clock: a runner that is slow stretches the clock, not the CPU.
#:
#: LINUX: THERE IS NO GPU PROCESS. Software WebRender composites in the parent, and the engine's tree on Linux is the parent, the
#: forkserver, the content processes (`tab`), the socket, the RDD and utility processes (WSL, firefox-64, /proc read; e2e Linux run
#: 43701692047 saw the same). The test says so, and holds the PARENT, where the compositing runs, to a bound measured on the Linux
#: runner: PARENT_CPU_LIMIT_LINUX_S below.
#: 43701692047 saw the same). The test says so and asserts that fact: no GPU process. The CPU of the parent is printed and judged by
#: nothing (20 runs on two runners, run 43707494271: 2.11 to 2.46 s, and a CPU time depends on the machine and on what else runs).
GPU_CPU_LIMIT_S = {"windows": 1.5}
#: CPU seconds the parent may use for the 10 scenes of ONE browser on the ubuntu-latest runner: 3.5 s. Measured there with this test,
#: 20 runs on two runners (run 43707494271): parent 2.11 to 2.46 s, median 2.31 s; tab 0.41 to 0.54 s; no GPU process in any run.
#: 3.5 s is 1.4 times the most a run used: a slow runner stays under it, and a parent that composites at half again its cost does not.
PARENT_CPU_LIMIT_LINUX_S = 3.5
def test_the_gpu_process_is_idle_on_a_fixed_scene(firefox_binary, capsys):
import os
from _cpu_by_type import CpuSampler
from _cpu_by_type import CpuSampler, engine_processes
from _waits import watch
from invisible_playwright import InvisiblePlaywright
server, base = _a_page_server(SCENE)
@@ -224,6 +222,12 @@ def test_the_gpu_process_is_idle_on_a_fixed_scene(firefox_binary, capsys):
try:
with InvisiblePlaywright(binary_path=firefox_binary, **LAUNCH) as browser:
page = browser.new_page()
# The sampling begins when the engine has a content process: one that is born after the start is counted from
# zero, but a tree that is seen before it has one gave "seen: ['parent']" twice. Waited for with a deadline, and
# what the tree held at each look is in the message if it never comes.
tree = watch(lambda: tuple(sorted({kind for kind, _cpu in engine_processes(os.getpid()).values()})),
lambda kinds: "parent" in kinds and "tab" in kinds, 30, lambda: page.wait_for_timeout(100))
assert tree.ok, "no content process (`tab`) of the engine below the test process within 30 s; types seen: %s" % tree.render()
sampler = CpuSampler(os.getpid())
sampler.begin()
try:
@@ -244,10 +248,6 @@ def test_the_gpu_process_is_idle_on_a_fixed_scene(firefox_binary, capsys):
"no parent and content process of the engine below the test process (seen: %r): the process tree is cut and the CPU is not the browser's" % (seen,)
if OS_NAME == "linux":
assert "gpu" not in seen, "the Linux engine has a GPU process (seen: %r): software WebRender was measured without one" % (seen,)
assert cpu["parent"] < PARENT_CPU_LIMIT_LINUX_S, (
"the parent, where software WebRender composites on Linux, used %.2f s of CPU for %d scenes of one browser, the bound is "
"%.1f s (all types: %s)" % (cpu["parent"], ROUNDS, PARENT_CPU_LIMIT_LINUX_S,
json.dumps({k: round(v, 2) for k, v in cpu.items() if v})))
return
limit = GPU_CPU_LIMIT_S[OS_NAME]
assert "gpu" in seen, "the Windows engine has no GPU process (seen: %r); the measurement of the bound had one" % (seen,)
@@ -10,20 +10,22 @@ What is asserted, with a gateway that answers every step of the handshake after
1. an association the gateway granted was completed before the PeerConnection was created (the page loaded through the same
proxy first, which is when Firefox learns the proxy); alone this does not tell the processes apart (the parent's pool is
warmed by the page load), the second line does;
2. the first STUN datagram of the PeerConnection reaches the relay within a fraction of a handshake of its birth (a cold
association needs three answered steps, 3 x 130 ms, before it can send).
2. the first STUN datagram of the PeerConnection leaves on one of those associations (the gateway says which association carried
each datagram), not on one made after the birth: a cold association needs three answered steps, 3 x 130 ms, before it can
send, so a datagram that leaves on one is the defect. It is an identity, not a number of milliseconds, so it does not depend
on how loaded the machine is (a bound of 250 ms was crossed by 419 and 425 ms on a loaded runner, three reds).
Hermetic: a local SOCKS5 gateway with a relay and a fake STUN server, a local page reached through the proxy, no external network.
Red on an engine that warms the pool only in the process of the HTTP connections: measured on the giro 2 binary, the first datagram left
396 ms after the birth of the PeerConnection (3 x 130 ms) instead of at once.
396 ms after the birth of the PeerConnection (3 x 130 ms) instead of at once, on an association made after the birth.
"""
from __future__ import annotations
import time
import pytest
from _e2e_verdicts import cold_association_problem
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
from _udp_line import egress_by_proxy
from _waits import wait_until
from test_webrtc_realness import _e2e_binary, _launch # noqa: F401
# Bound to the engine that carries the UDP line: red before the UDP line (firefox-63): skips on the published engine; runs on the candidate.
@@ -38,7 +40,7 @@ _PC_JS = """async (stun) => {
let t_srflx = null;
pc.onicecandidate = e => { if (e.candidate && e.candidate.type === 'srflx' && t_srflx === null) t_srflx = Date.now(); };
await pc.setLocalDescription(await pc.createOffer());
const deadline = Date.now() + 8000;
const deadline = Date.now() + 30000;
while (t_srflx === null && Date.now() < deadline) await new Promise(r => setTimeout(r, 5));
pc.close();
return {t_pc, t_srflx};
@@ -62,24 +64,15 @@ def test_the_first_datagram_does_not_wait_for_a_handshake(local_https_page, monk
with _launch(binary_path=binary, proxy=gateway.proxy, extra_prefs=prefs, seed=7) as browser:
page = browser.new_context().new_page()
page.goto(local_https_page, wait_until="load", timeout=60000) # through the proxy: Firefox learns it here
page.wait_for_timeout(2500) # the pool has time to make its associations
# the pool makes its associations: wait until the gateway has granted one of the engine's (the first granted is the
# core's probe), with a deadline; the verdict below names what it saw if none came
wait_until(lambda: len([a for a in gateway.associations if a[1] is not None]) >= 2, 30,
lambda: page.wait_for_timeout(50))
result = page.evaluate(_PC_JS, "%s:%d" % (STUN_NUMBER, STUN_PORT))
t_pc = result["t_pc"] / 1000.0
granted = [a for a in gateway.associations if a[1] is not None]
first = next((t for host, port, _atyp, t in gateway.datagram_log if host == STUN_NUMBER), None)
assert granted, "the proxy was never asked for an association"
# the first association of the gateway is the core's own UDP probe, made before the browser exists: it is no pool
# association of the engine, and counting it made this test pass with an engine that asked for none
granted = granted[1:]
assert granted, "the engine never asked the proxy for an association (only the core's probe did): the session's UDP was not declared coherent"
ready_before = [a for a in granted if gateway.wall0 + a[1] < t_pc]
assert ready_before, (
"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(a[1], 3) for a in granted], t_pc - gateway.wall0))
assert first is not None, "no STUN datagram of the PeerConnection reached the relay"
wait = gateway.wall0 + first - t_pc
assert wait < 0.25, (
"the first STUN datagram left %.0f ms after the PeerConnection was born; a ready association sends at once, a cold one "
"needs three answered steps of %d ms" % (wait * 1000, RTT_MS))
associations = [list(a) for a in gateway.associations]
via = list(gateway.datagram_via)
wall0 = gateway.wall0
problem = cold_association_problem(associations, via, STUN_NUMBER, t_pc - wall0)
assert problem is None, "%s; the gateway saw associations %s and datagrams %s" % (problem, associations, via)
assert result["t_srflx"] is not None, "no srflx candidate came back through the relay"
+2 -2
View File
@@ -52,7 +52,7 @@ def page(firefox_binary):
def _settled_on_next(page):
deadline = time.monotonic() + 20
deadline = time.monotonic() + 30
while page.title() != "next":
assert time.monotonic() < deadline, "the page never reached /next"
time.sleep(0.05)
@@ -103,5 +103,5 @@ def test_a_read_declared_free_of_effects_answers_from_the_page_that_replaced_it(
def test_wait_for_function_goes_on_through_a_navigation(page, site):
page.goto(site)
page.evaluate("setTimeout(() => { location.href = '/next'; }, 300)")
page.wait_for_function("document.title === 'next'", timeout=15_000)
page.wait_for_function("document.title === 'next'", timeout=30_000)
assert page.title() == "next"
@@ -0,0 +1,284 @@
"""The verdicts of `test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py` are red on the defect and green on the fix, without a browser.
The e2e judges no duration: a loop that is held is told by WHERE its thread was, and a browser that answers by the ORDER of the events.
Here the instrument of that test (its own source, taken out of the client script) runs on a loop in a thread of this process:
* a step of the close that waits, run on the loop's thread, is seen there and the verdict is red; the same step run in a thread of its
own is not on the loop's stack and the verdict is green;
* the control that holds the loop on purpose is seen in the function that holds it, and one that does not hold it is a watcher that
could not see (red);
* a loop the machine did not schedule is not charged for the time it waited: what is charged never exceeds what the same samples saw run;
* the other browsers: calls that did not begin and end inside the close, or a removal of the profile that only went on at its deadline
because nothing could answer while it waited, are red.
Every wait here ends when the thing it waits for happened (30 s is the deadline of a hang): nothing decides by a number of milliseconds.
"""
from __future__ import annotations
import asyncio
import json
import os
import shutil
import sys
import threading
import time
import traceback
import psutil
import pytest
import _close_loop_verdicts as verdicts
import test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e as e2e
pytestmark = pytest.mark.unit
_CLOSE_STEP_FILE = "/checkout/src/invisible_playwright/_juggler/transport.py"
_STEP_SOURCE = (
"import time\n"
"def shutdown(done):\n"
" while not done():\n"
" time.sleep(0.005)\n"
)
_HOLDER_SOURCE = (
"import time\n"
"def hold_the_loop(done):\n"
" while not done():\n"
" time.sleep(0.005)\n"
)
def _function(source, filename, name):
scope = {}
exec(compile(source, filename, "exec"), scope)
return scope[name]
def _instrument_class(main_id):
"""The `Instrument` of the client, exactly as the e2e writes it, bound to the thread that will run the loop."""
text = e2e._CLIENT
source = text[text.index("class Instrument:"):text.index("def engines():")]
scope = {"asyncio": asyncio, "json": json, "os": os, "shutil": shutil, "sys": sys, "threading": threading,
"time": time, "traceback": traceback, "psutil": psutil, "main_id": main_id}
exec(compile(source, "client_instrument", "exec"), scope)
return scope["Instrument"]
def _run_on_a_loop(scenario):
"""Run ``scenario(Instrument)`` (a coroutine function) as the main coroutine of a loop that lives in a thread of its own."""
out = {}
def target():
Instrument = _instrument_class(threading.get_ident())
try:
out["value"] = asyncio.run(asyncio.wait_for(scenario(Instrument), 60))
except BaseException as failure: # noqa: BLE001 - handed to the test
out["failure"] = failure
thread = threading.Thread(target=target, name="the-loop-under-test")
thread.start()
thread.join(90)
assert not thread.is_alive(), "the scenario did not end"
if "failure" in out:
raise out["failure"]
return out["value"]
def test_the_client_script_compiles():
compile(e2e._CLIENT, "client.py", "exec")
# ---------------------------------------------------------------------------------------------------------------------------------
# a step of the close that waits: on the loop's thread (red), in a thread of its own (green)
# ---------------------------------------------------------------------------------------------------------------------------------
def test_a_step_of_the_close_run_on_the_loop_is_seen_and_the_verdict_is_red():
shutdown = _function(_STEP_SOURCE, _CLOSE_STEP_FILE, "shutdown")
async def scenario(Instrument):
instrument = Instrument()
await instrument.start()
# Held until the watcher has seen the thread inside it: the loop's thread is what is seen, whatever the speed of the machine.
end = time.monotonic() + 30
shutdown(lambda: bool(verdicts.blocked_by(instrument.inside)) or time.monotonic() > end)
await instrument.finish()
return instrument.report()
report = _run_on_a_loop(scenario)
problem = verdicts.close_on_the_loop_problem(report["inside"])
assert problem is not None
assert _CLOSE_STEP_FILE + ":shutdown" in problem
assert "sleep" in report["on_the_loop"]
def test_the_same_step_in_a_thread_of_its_own_leaves_the_loop_free_and_the_verdict_is_green():
shutdown = _function(_STEP_SOURCE, _CLOSE_STEP_FILE, "shutdown")
async def scenario(Instrument):
instrument = Instrument()
await instrument.start()
ended = threading.Event()
began = threading.Event()
def step():
began.set()
# The same step, the same wait, until the loop has gone on twice (the sentinel has beaten after it began): the loop was
# served while it waited.
beats = len(instrument.gaps)
shutdown(lambda: len(instrument.gaps) >= beats + 2)
ended.set()
threading.Thread(target=step, name="the-step").start()
while not ended.is_set():
await asyncio.sleep(0.01)
await instrument.finish()
return instrument.report()
report = _run_on_a_loop(scenario)
assert verdicts.close_on_the_loop_problem(report["inside"]) is None, verdicts.close_on_the_loop_problem(report["inside"])
assert report["on_the_loop"] == []
# ---------------------------------------------------------------------------------------------------------------------------------
# the control that holds the loop on purpose
# ---------------------------------------------------------------------------------------------------------------------------------
_HOLDER = (("/client.py", ("hold_the_loop",)),)
def test_the_control_sees_a_loop_held_in_the_function_that_holds_it():
hold_the_loop = _function(_HOLDER_SOURCE, "/tmp/client.py", "hold_the_loop")
async def scenario(Instrument):
instrument = Instrument()
await instrument.start()
end = time.monotonic() + 30
hold_the_loop(lambda: bool(verdicts.blocked_by(instrument.inside, _HOLDER)) or time.monotonic() > end)
await instrument.finish()
return instrument.report()
report = _run_on_a_loop(scenario)
assert verdicts.blind_instrument_problem(report["inside"], _HOLDER) is None
def test_a_watcher_that_never_saw_the_held_loop_is_red():
# An instrument that saw nothing of where the thread was (the loop idle, or a watcher that reads no stack) is not a control.
assert verdicts.blind_instrument_problem({}, _HOLDER) is not None
assert verdicts.blind_instrument_problem({"/tmp/other.py:main": {"n": 3, "stack": []}}, _HOLDER) is not None
async def scenario(Instrument):
instrument = Instrument()
await instrument.start()
await asyncio.sleep(0.1)
await instrument.finish()
return instrument.report()
assert verdicts.blind_instrument_problem(_run_on_a_loop(scenario)["inside"], _HOLDER) is not None
# ---------------------------------------------------------------------------------------------------------------------------------
# a loop the machine did not schedule
# ---------------------------------------------------------------------------------------------------------------------------------
def test_a_loop_the_machine_did_not_schedule_is_charged_no_more_than_the_time_it_ran():
"""The second control of the e2e, on the real instrument: late by the pause of the sentinel, then a callback that runs."""
async def scenario(Instrument):
unscheduled = Instrument()
await unscheduled.start()
await asyncio.sleep(0.05)
unscheduled.pause_once = 0.3
ran = threading.Event()
def burst():
# Runs until the watcher has seen the thread run for 45 ms in a row (30 s at most): the callback is what holds the loop.
end = time.monotonic() + 30
while unscheduled.busy_run < 0.045 and time.monotonic() < end:
pass
ran.set()
asyncio.get_running_loop().call_later(0.15, burst)
while not ran.is_set():
await asyncio.sleep(0.01)
await asyncio.sleep(0.4)
await unscheduled.finish()
return unscheduled.report()
report = _run_on_a_loop(scenario)
assert report["gap"] > 0.25, "the sentinel was not late: %r" % report["gap"]
assert report["busy_run"] > 0, "the watcher never saw the callback run"
problem = verdicts.charged_more_than_ran_problem(report["held"], report["busy_run"])
assert problem is None, problem
def test_charging_the_wait_in_the_selector_as_held_is_red():
# What the first instrument did (candidate 43727128285): 145 ms in the selector and a 45 ms callback charged as 195 ms.
assert verdicts.charged_more_than_ran_problem(0.195, 0.045) is not None
assert verdicts.charged_more_than_ran_problem(0.094, 0.0) is not None
assert verdicts.charged_more_than_ran_problem(0.045, 0.045) is None
assert verdicts.charged_more_than_ran_problem(0.0, 0.0) is None
# ---------------------------------------------------------------------------------------------------------------------------------
# which frames are a step of the close that waits
# ---------------------------------------------------------------------------------------------------------------------------------
@pytest.mark.parametrize("frame", [
"C:/w/src/invisible_playwright/_juggler/transport.py:shutdown",
"C:/w/src/invisible_playwright/_juggler/transport.py:_join_workers",
"C:/w/src/invisible_playwright/_juggler/server.py:op_close",
"C:/venv/Lib/site-packages/invisible_core/process.py:reap",
"C:/venv/Lib/site-packages/psutil/__init__.py:wait_procs",
"C:/Python312/Lib/shutil.py:rmtree",
"C:/Python312/Lib/threading.py:join",
])
def test_a_step_that_waits_is_a_blocking_step(frame):
assert verdicts.blocked_by({frame: {"n": 1, "stack": [frame]}}) == [frame]
@pytest.mark.parametrize("frame", [
"C:/Python312/Lib/asyncio/base_events.py:shutdown_asyncgens",
"C:/Python312/Lib/concurrent/futures/thread.py:shutdown",
"C:/Python312/Lib/asyncio/tasks.py:wait_for",
"C:/w/src/invisible_playwright/async_api.py:_teardown",
"C:/w/src/invisible_playwright/_juggler/transport.py:request_stop",
"C:/w/src/invisible_playwright/_juggler/transport.py:wait_until_stopped",
"C:/venv/Lib/site-packages/invisible_core/_offloop.py:off_the_loop",
])
def test_what_the_loop_runs_between_two_awaits_of_the_close_is_not_a_blocking_step(frame):
assert verdicts.blocked_by({frame: {"n": 9, "stack": [frame]}}) == []
# ---------------------------------------------------------------------------------------------------------------------------------
# the other browsers
# ---------------------------------------------------------------------------------------------------------------------------------
def _others(inside=(2, 2, 2), removal=(1, 1, 1)):
return [{"inside": a, "during_removal": b, "slowest": 9.9} for a, b in zip(inside, removal)]
def test_the_others_that_answered_inside_the_close_and_during_the_removal_are_green_whatever_the_seconds_they_took():
# The calls took 9.9 s each in these records: the seconds decide nothing.
assert verdicts.others_answered_problem(_others(), {"reached": True, "released_by": "answered"}) is None
def test_a_browser_that_answered_nothing_inside_the_close_is_red():
problem = verdicts.others_answered_problem(_others(inside=(4, 0, 4)), {"reached": True, "released_by": "answered"})
assert problem is not None and "[1]" in problem
def test_a_removal_that_went_on_only_at_its_deadline_is_red():
# The loop could not run while the removal waited for the answers: the removal ran on it. Calls that began and ended inside the
# close after the deadline do not make it green.
problem = verdicts.others_answered_problem(_others(inside=(5, 5, 5), removal=(0, 0, 0)), {"reached": True, "released_by": "deadline"})
assert problem is not None and "deadline" in problem
def test_the_hold_of_the_removal_is_not_asked_when_no_removal_ran_in_the_close():
# Another test says the removal must have run (`test_the_removal_of_the_profile_ran_inside_the_close`); this verdict still asks
# for the calls inside the close.
assert verdicts.others_answered_problem(_others(), {"reached": False, "released_by": None}) is None
assert verdicts.others_answered_problem(_others(inside=(1, 1, 0)), {"reached": False, "released_by": None}) is not None
def test_fewer_than_three_other_browsers_followed_is_red():
assert verdicts.others_answered_problem(_others()[:2], {"reached": True, "released_by": "answered"}) is not None
@@ -0,0 +1,354 @@
"""The e2e tests do not wait on clocks, share ports, write the environment or reach the world: an AST check with a reviewed list (no browser).
An e2e test is red for no fault of the product when its verdict depends on the speed of the machine (a fixed pause and then a read, an absolute bound on a duration), on a
resource the workers share (a literal port, ``os.environ``), or on the world (a real site, a service of the internet). The audit of the e2e tests found 342 such places, and
each was found after a red run. This reads the e2e files and the helpers of ``tests/`` with ``ast`` and refuses a new one (``tests/_e2e_clocks.py``: the rules and what each
accepts by its shape), the way ``test_the_consecutive_port_tests_run_serially.py`` refuses a test that asserts consecutive ports and does not carry the marker.
Two lists in ``tests/gates/e2e_clock_exceptions.json``, each item named by ``(file, scope, rule, nth)`` and never by a line:
* ``entries``: occurrences a person reviewed and found deliberate (a window in which nothing must happen, a slow server on purpose, a port nobody binds), with a ``kind`` of a closed
vocabulary and a ``reason`` that is a sentence;
* ``debt``: every other occurrence, the dangerous ones not yet corrected. It is MADE from the sources (``python scripts/e2e_clock_exceptions.py --write``), never edited, so
that a branch that corrects tests only has to run it when it merges. It may not grow: the occurrences it names must all be in the ``debt`` of main.
A stale item of either list (it matches no occurrence any more) is red: the list shortens with the code. Known-bad inputs: a fake file with every violation is red, a wait on a
condition with a deadline is green, a list that names an occurrence the sources no longer have is red, a debt that holds an occurrence main does not is red.
"""
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path
import pytest
import _e2e_clocks as clocks
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parent.parent
GATE = "tests/gates/e2e_clock_exceptions.json"
def rules_of(source: str, file: str = "test_fake_e2e.py"):
return sorted({v.rule for v in clocks.analyze(source, file)})
def fake(body: str) -> str:
return "import pytest\n\npytestmark = pytest.mark.e2e\n\n" + body
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
# The check on the real tree
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
def test_no_occurrence_is_outside_the_reviewed_lists():
found = clocks.scan()
difference = clocks.compare(found, clocks.load())
lines = {v.key: v for v in found}
new = ["%s:%d %s [%s #%d] %s" % (v.file, v.line, v.scope, v.rule, v.nth, v.text) for v in (lines[k] for k in difference["new"])]
assert not new, (
"an e2e test (or a helper) depends on a clock, a shared resource or the world, and no list names it:\n " + "\n ".join(new) +
"\nWait for the condition with a deadline (tests/_waits.py), bind port 0, use monkeypatch.setenv, serve the page from the test's own server. A deliberate case is "
"reviewed into `entries` of " + GATE + " with a kind and a reason; `debt` is made by scripts/e2e_clock_exceptions.py --write and may not grow against main.")
def test_a_stale_item_of_either_list_is_refused():
difference = clocks.compare(clocks.scan(), clocks.load())
assert difference["stale_entries"] == [], (
"these `entries` match no occurrence any more (the code changed): drop them with scripts/e2e_clock_exceptions.py --write --prune: %s" % difference["stale_entries"])
assert difference["stale_debt"] == [], (
"this `debt` is of a correction that has merged: make it again with scripts/e2e_clock_exceptions.py --write: %s" % difference["stale_debt"])
assert difference["both"] == [], "an occurrence is both reviewed and debt: %s" % difference["both"]
def test_the_debt_on_disk_is_what_the_script_writes():
document = clocks.load()
assert (ROOT / GATE).read_text(encoding="utf-8") == clocks.dump(clocks.regenerate(document, clocks.scan())), (
"the debt is not what scripts/e2e_clock_exceptions.py --write makes of the sources")
def test_an_entry_is_a_reviewed_sentence_of_a_closed_kind():
document = clocks.load()
reasons = {}
for item in document["entries"]:
label = "%s %s %s #%s" % (item["file"], item["scope"], item["rule"], item["nth"])
assert item["kind"] in clocks.KINDS, "%s: kind %r is not one of %s" % (label, item["kind"], clocks.KINDS)
assert item["rule"] in clocks.RULES, label
assert isinstance(item["nth"], int) and item["nth"] >= 1, label
reason = item["reason"]
assert len(reason) >= 40 and reason.rstrip().endswith("."), "%s: the reason is not a sentence: %r" % (label, reason)
reasons.setdefault(reason, set()).add(item["rule"])
shared = [r for r, rules in reasons.items() if len(rules) > 1]
assert shared == [], "one reason written for entries of different rules says nothing of either: %s" % shared
for item in document["debt"]:
assert item["rule"] in clocks.RULES and item["class"] == clocks.CLASS[item["rule"]], item
def _main_document():
"""The list of main, or None when it has none; the reason of the miss otherwise."""
for ref in ("origin/main", "main"):
shown = subprocess.run(["git", "show", "%s:%s" % (ref, GATE)], cwd=ROOT, capture_output=True, text=True)
if shown.returncode == 0:
return json.loads(shown.stdout), ref
if subprocess.run(["git", "cat-file", "-e", ref], cwd=ROOT, capture_output=True).returncode == 0:
return None, ref # the ref exists and the file does not: main has no list yet (the merge that brings this one)
return "no ref", None
def test_the_debt_does_not_grow_against_main():
"""THE HONEST LIMIT OF A UNIT TEST: it can be changed together with the list. Reading the list from MAIN is what stops that, and main is only there when the
checkout has it: the pull-request job fetches it (tests.yml); a developer without it skips, and a CI run without it is red (a comparison that compares nothing is
not a green)."""
document, ref = _main_document()
if document == "no ref":
if os.environ.get("GITHUB_ACTIONS"):
pytest.fail("origin/main is not in this checkout, so the debt cannot be compared with it: fetch it (git fetch origin main) before the tests")
pytest.skip("no origin/main in this checkout: the debt is not compared with main (CI does)")
if document is None:
return # main has no list: this is the change that brings it, there is nothing to grow from
main_debt = {clocks.key_of(i) for i in document["debt"]}
main_entries = {clocks.key_of(i) for i in document["entries"]}
grown = sorted(k for k in (clocks.key_of(i) for i in clocks.load()["debt"]) if k not in main_debt and k not in main_entries)
assert grown == [], (
"the debt has occurrences that %s does not have: a test that was clean on main now waits on a clock, shares a port or reaches the world. Correct it; "
"the debt only shrinks. %s" % (ref, grown))
def test_the_conftest_declares_the_exit_of_the_lab():
assert clocks.analyze_conftest((ROOT / "tests" / "conftest.py").read_text(encoding="utf-8")) == []
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
# Known-bad inputs: each rule refuses its own case
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
def test_a_sleep_then_an_assert_is_refused():
source = fake("import time\n\n" "@pytest.mark.e2e\ndef test_x(page):\n page.click('#go')\n time.sleep(0.5)\n assert page.title() == 'done'\n")
assert rules_of(source) == ["sleep"]
found = clocks.analyze(source, "test_fake_e2e.py")[0]
assert (found.scope, found.nth, found.line) == ("test_x", 1, 10)
def test_a_wait_for_timeout_then_a_read_is_refused():
source = fake("def test_x(page):\n page.wait_for_timeout(300)\n assert page.inner_text('#a') == 'x'\n page.wait_for_timeout(300)\n")
assert rules_of(source) == ["sleep"]
assert [v.nth for v in clocks.analyze(source, "test_fake_e2e.py")] == [1, 2], "the nth occurrence is how a list tells two pauses of one test apart"
def test_an_asyncio_sleep_is_refused_and_a_yield_is_not():
assert rules_of(fake("import asyncio\n\nasync def test_x():\n await asyncio.sleep(1.0)\n")) == ["sleep"]
assert rules_of(fake("import asyncio\n\nasync def test_x():\n await asyncio.sleep(0)\n")) == []
def test_a_timer_in_a_page_of_the_test_is_refused():
assert rules_of(fake("PAGE = '<script>setTimeout(() => { go(); }, 300)</script>'\n")) == ["js-timer"]
assert rules_of(fake("def test_x(page):\n page.evaluate('setInterval(tick, 10)')\n")) == ["js-timer"]
def test_a_literal_port_is_refused():
assert rules_of(fake("import socket\n\ndef helper():\n s = socket.socket()\n s.bind(('127.0.0.1', 8080))\n")) == ["port"]
assert rules_of(fake("from http.server import HTTPServer\n\ndef helper(h):\n return HTTPServer(('127.0.0.1', 18080), h)\n")) == ["port"]
assert rules_of(fake("MARIONETTE_PORT = 28431\n")) == ["port"]
# the number is put in by `%` so that this line is not itself a fixed port to the guard of test_the_marionette_helpers.py
assert rules_of(fake("def prefs():\n return {'marionette.port': %d}\n" % 28431)) == ["port"]
assert rules_of(fake("def launch(f):\n return f(port=9222)\n")) == ["port"]
assert rules_of(fake("import socket\n\ndef helper():\n s = socket.socket()\n s.bind(('127.0.0.1', 0))\n return f(port=0)\n")) == [], "port 0 is the answer"
def test_an_environ_write_is_refused_and_monkeypatch_is_not():
for body in ("import os\n\ndef test_x():\n os.environ['A'] = '1'\n", "import os\n\ndef test_x():\n os.environ.pop('A', None)\n",
"import os\n\ndef test_x():\n del os.environ['A']\n", "import os\n\ndef test_x():\n os.environ.update({'A': '1'})\n",
"import os\n\ndef test_x():\n os.putenv('A', '1')\n"):
assert rules_of(fake(body)) == ["env"], body
assert rules_of(fake("import os\n\ndef test_x(monkeypatch):\n monkeypatch.setenv('A', '1')\n assert os.environ.get('A') == '1'\n")) == []
def test_an_absolute_upper_bound_is_refused_and_a_lower_bound_is_not():
assert rules_of(fake("def test_x(took):\n assert took < 4.0\n")) == ["bound"]
assert rules_of(fake("import time\n\ndef test_x(t0):\n assert time.monotonic() - t0 <= 10\n")) == ["bound"]
assert rules_of(fake("LIMIT_S = 5\n\ndef test_x(elapsed):\n assert elapsed < LIMIT_S\n")) == ["bound"]
assert rules_of(fake("def test_x(took):\n assert 4.0 > took\n")) == ["bound"]
assert rules_of(fake("def test_x(took):\n assert 24.0 < took < 40.0\n")) == ["bound"], "the upper half of a band is an upper bound"
assert rules_of(fake("def test_x(took):\n assert took >= 0.25\n")) == [], "a lower bound cannot fail because the machine is slow"
assert rules_of(fake("def test_x(took, control):\n assert took <= control * 3\n")) == [], "a bound against a measure of the same run is relative"
assert rules_of(fake("def test_x(count):\n assert count < 4\n")) == [], "not a duration"
def test_a_limit_that_is_a_named_variable_or_has_a_slack_added_is_refused_and_a_relative_one_is_not():
assert rules_of(fake("def test_x(took, limit_s):\n assert took < limit_s\n")) == ["bound"], "a limit is a limit when it is not written in capitals"
assert rules_of(fake("def test_x(elapsed, max_ms):\n assert elapsed <= max_ms\n")) == ["bound"]
assert rules_of(fake("def test_x(limit_s, took):\n assert limit_s > took\n")) == ["bound"]
assert rules_of(fake("def test_x(wait, rtt_ms):\n assert wait < rtt_ms + 250\n")) == ["bound"], "an absolute slack added to a measure is an absolute limit"
assert rules_of(fake("def test_x(took, control):\n assert took <= control + 0.5\n")) == ["bound"]
assert rules_of(fake("def test_x(res):\n assert res['opened'] < 3000\n")) == ["bound"], "the time a connection took to open is a duration"
assert rules_of(fake("def test_x(took, control):\n assert took <= control * 3\n")) == [], "a factor of a measure of the same run is relative"
assert rules_of(fake("def test_x(took, control):\n assert took <= control\n")) == []
assert rules_of(fake("def test_x(took, control):\n assert took >= control - 0.5\n")) == [], "a lower bound with a slack cannot fail because the machine is slow"
assert rules_of(fake("import time\n\ndef test_x(ready, deadline):\n assert time.monotonic() < deadline, 'never'\n")) == [], "a point in time that ends a wait is no limit on a duration"
def test_a_real_url_is_refused_and_a_local_one_is_not():
assert rules_of(fake("def test_x(page):\n page.goto('https://example.com/')\n")) == ["net"]
assert rules_of(fake("import urllib.request\n\ndef test_x():\n urllib.request.urlopen('http://127.0.0.1:1/')\n")) == ["net"]
assert rules_of(fake("import requests\n\ndef test_x():\n requests.get(URL)\n")) == ["net"]
assert rules_of(fake("import subprocess\n\ndef test_x():\n subprocess.run(['pip', 'install', 'x'])\n")) == ["net"]
for url in ("http://127.0.0.1:%d/", "http://localhost:3000/", "http://a.test/x", "http://x/", "http://203.0.113.80/", "http://[::1]:1/", "http://%s/", "http://{host}/"):
assert rules_of(fake("def test_x(page):\n page.goto(%r)\n" % url)) == [], url
def test_a_real_url_is_accepted_in_the_files_of_the_round_after_a_publication():
source = fake("def test_x(page):\n page.goto('https://example.com/')\n")
assert rules_of(source, "test_release_e2e.py") == [] and rules_of(source, "test_upgrade_e2e.py") == []
def test_a_deadline_under_thirty_seconds_on_a_wait_for_something_that_must_happen_is_refused():
for call in ("page.goto('http://x.test/', timeout=20000)", "page.wait_for_selector('#a', timeout=10000)", "page.locator('#a').click(timeout=5000)",
"page.set_default_timeout(5000)", "page.set_default_navigation_timeout(20000)", "page.wait_for_function('1', timeout=29999)",
"expect(page.locator('#a')).to_be_visible(timeout=500)", "thread.join(timeout=5)", "subprocess.run(cmd, timeout=10)",
"socket.create_connection(addr, timeout=10)", "actions.click('#a', timeout=15)"):
assert rules_of(fake("def test_x(page, thread, cmd, addr, actions):\n %s\n" % call)) == ["timeout"], call
def test_a_deadline_of_thirty_seconds_or_more_or_no_deadline_is_accepted():
for call in ("page.goto('http://x.test/', timeout=30000)", "page.goto('http://x.test/', timeout=60_000)", "page.wait_for_selector('#a', timeout=30_000)",
"page.set_default_timeout(30000)", "thread.join(timeout=30)", "socket.create_connection(addr, timeout=30)", "subprocess.run(cmd, timeout=300)",
"lifecycle.goto(url, until='load', timeout=30)", "actions.click('#a', timeout=45)", "page.goto(url, timeout=0)", "page.goto(url, timeout=timeout_ms)",
"page.goto(url, timeout=None)", "run(cmd, timeout=1800)"):
assert rules_of(fake("def test_x(page, thread, cmd, url, addr, actions, lifecycle, timeout_ms):\n %s\n" % call)) == [], call
def test_a_deadline_that_is_a_named_constant_or_a_default_is_read_as_what_it_is():
assert rules_of(fake("GOTO_MS = 20000\n\ndef test_x(page):\n page.goto('http://x.test/', timeout=GOTO_MS)\n")) == ["timeout"]
assert rules_of(fake("LIMIT_S = 10\n\ndef test_x(page):\n page.goto('http://x.test/', timeout=int(LIMIT_S * 1000))\n")) == ["timeout"]
assert rules_of(fake("GOTO_MS = 30000\n\ndef test_x(page):\n page.goto('http://x.test/', timeout=GOTO_MS)\n")) == []
assert rules_of(fake("def wait_until_ready(timeout=5):\n pass\n")) == ["timeout"], "every call that leaves the deadline out waits that long"
assert rules_of(fake("def wait_until_ready(timeout=30.0):\n pass\n")) == []
def test_a_wait_for_something_that_must_not_happen_is_accepted_by_its_shape():
"""A window in which the call is EXPECTED to run out of time can only be a weaker check on a slow machine, never a red."""
raises = fake("def test_x(page):\n with pytest.raises(Exception):\n page.click('#a', timeout=500)\n")
assert rules_of(raises) == []
assert rules_of(fake("NEGATIVE_S = 0.3\n\ndef test_x(actions):\n actions.click('#a', timeout=NEGATIVE_S)\n")) == []
swallowed = fake("def test_x(page):\n try:\n page.go_back(timeout=3000)\n except TimeoutError:\n pass\n")
assert rules_of(swallowed) == []
failing = fake("def test_x(page):\n try:\n page.go_back(timeout=3000)\n except TimeoutError:\n pytest.fail('late')\n")
assert rules_of(failing) == ["timeout"], "a timeout that fails the test is a wait for something that must happen"
assert rules_of(fake("def test_x(page):\n with pytest.raises(Exception):\n pass\n page.click('#a', timeout=500)\n")) == ["timeout"], "after the block it is a positive wait"
def test_a_judge_that_reports_a_duration_over_an_absolute_margin_is_refused_like_an_assert():
judge = "def judge(walls_ms):\n problems = []\n if walls_ms[1] > walls_ms[0] + MARGIN_MS:\n problems.append('slow')\n return problems\n"
assert rules_of(fake("MARGIN_MS = 1500\n\n" + judge), "_judge.py") == ["bound"]
assert rules_of(fake("def judge(took):\n if took > 4.0:\n raise AssertionError('slow')\n"), "_judge.py") == ["bound"]
assert rules_of(fake("def judge(took):\n if 4.0 < took:\n raise AssertionError('slow')\n"), "_judge.py") == ["bound"]
assert rules_of(fake("def judge(took, control):\n if took > control * 3:\n raise AssertionError('slow')\n"), "_judge.py") == [], "relative to the same run"
assert rules_of(fake("def judge(took):\n if took > 4.0:\n print('slow')\n"), "_judge.py") == [], "an if that reports nothing is the logic of the test"
assert rules_of(fake("def judge(took):\n if took < 4.0:\n raise AssertionError('too fast')\n"), "_judge.py") == [], "a lower bound cannot fail because the machine is slow"
def test_a_count_of_processes_is_refused_outside_the_helpers_that_count():
source = fake("def test_x(pids):\n assert len(pids) == 1\n")
assert rules_of(source) == ["count"]
assert clocks.analyze(source, "_processes.py") == []
def test_a_polling_step_with_a_deadline_is_accepted():
for body in (
"import time\n\ndef test_x(ready):\n deadline = time.monotonic() + 30\n while not ready() and time.monotonic() < deadline:\n time.sleep(0.05)\n",
"import time\n\ndef test_x(ready):\n end = time.time() + 30\n while True:\n if ready():\n break\n assert time.time() < end, 'never'\n time.sleep(0.05)\n",
"import time\n\ndef test_x(ready):\n for _ in range(100):\n if ready():\n break\n time.sleep(0.1)\n",
"def test_x(page, ready):\n wait_until(ready, 30, lambda: page.wait_for_timeout(50))\n",
"def test_x(page, ready):\n watch(ready, bool, 30, pump=lambda: page.wait_for_timeout(50))\n",
"def pump(page):\n page.wait_for_timeout(50)\n",
"async def test_x(ready):\n async def ask():\n await asyncio.sleep(0.1)\n await awatch(ready, bool, 30, ask)\n",
"def _wait_for_the_frame(page):\n page.wait_for_timeout(50)\n",
"import time\n\nclass SlowHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n time.sleep(1.0)\n",
):
assert rules_of(fake(body)) == [], body
def test_a_wait_without_a_deadline_or_a_condition_is_not_a_polling_step():
assert rules_of(fake("import time\n\ndef test_x(ready):\n while not ready():\n time.sleep(0.05)\n")) == ["sleep"]
assert rules_of(fake("import time\n\ndef test_x(ready):\n for _ in range(3):\n time.sleep(0.05)\n")) == ["sleep"]
assert rules_of(fake("def test_wait_for_the_title(page):\n page.wait_for_timeout(500)\n")) == ["sleep"], "a test is not a wait helper because of its name"
def test_a_unit_test_and_a_fake_clock_are_not_read():
assert rules_of("import pytest\nimport time\n\n" "@pytest.mark.unit\ndef test_x():\n time.sleep(0.1)\n", "test_unit_fake.py") == []
assert rules_of("import time\n\ndef test_x():\n time.sleep(0.1)\n", "test_no_marker.py") == [], "a file with no e2e marker is not an e2e file"
source = fake("class Clock:\n def sleep(self, seconds):\n self.now += seconds\n\ndef test_x():\n clock = Clock()\n assert clock\n")
assert rules_of(source) == [], "a definition of sleep is not a call"
assert rules_of("import time\n\ndef pause():\n time.sleep(0.1)\n\ndef helper():\n time.sleep(0.1)\n", "_helper.py") == ["sleep"], "a helper is always read"
def test_a_word_in_a_docstring_or_a_comment_counts_for_nothing():
source = fake('def test_x():\n """Used to call time.sleep(1) and setTimeout(f, 10); port=8080; os.environ["A"] = "1"."""\n # time.sleep(2)\n assert True\n')
assert rules_of(source) == []
def test_the_nth_occurrence_and_the_scope_do_not_depend_on_the_line():
a = fake("def test_x(page):\n page.wait_for_timeout(100)\n\n page.wait_for_timeout(200)\n")
b = fake("# a comment\n\n\n\ndef test_x(page):\n\n page.wait_for_timeout(100)\n page.wait_for_timeout(200)\n")
key = lambda source: [v.key for v in clocks.analyze(source, "test_fake_e2e.py")] # noqa: E731
assert key(a) == key(b) == [("test_fake_e2e.py", "test_x", "sleep", 1), ("test_fake_e2e.py", "test_x", "sleep", 2)]
def test_a_file_with_every_violation_is_red_and_one_that_waits_on_conditions_is_green():
bad = fake(
"import os, time, socket, asyncio\n"
"PAGE = '<script>setTimeout(go, 300)</script>'\n"
"def test_x(page, took, pids):\n"
" os.environ['A'] = '1'\n"
" s = socket.socket(); s.bind(('127.0.0.1', 8080))\n"
" page.goto('https://example.org/')\n"
" page.click('#go', timeout=5000)\n"
" time.sleep(1)\n"
" assert took < 3\n"
" assert len(pids) == 2\n")
assert rules_of(bad) == sorted(set(clocks.RULES) - {"egress"})
good = fake(
"import time\n"
"def test_x(page, took, control, ready):\n"
" page.goto('http://127.0.0.1:%d/' % PORT)\n"
" deadline = time.monotonic() + 30\n"
" while not ready() and time.monotonic() < deadline:\n"
" page.wait_for_timeout(50)\n"
" assert took <= control * 3\n")
assert clocks.analyze(good, "test_fake_e2e.py") == []
def test_a_conftest_without_the_declared_exit_is_refused():
assert [v.rule for v in clocks.analyze_conftest("import pytest\n\n" "@pytest.fixture\ndef x():\n pass\n")] == ["egress"]
wrong_scope = "import pytest\n\n" "@pytest.fixture(autouse=True)\ndef _the_lab_declares_the_exit():\n _lab_egress.install(None, None)\n"
assert [v.rule for v in clocks.analyze_conftest(wrong_scope)] == ["egress"], "a function-scoped fixture is too late for the module browsers"
def test_a_list_that_names_what_the_sources_no_longer_have_is_red_and_a_new_occurrence_is_not_covered():
found = clocks.analyze(fake("def test_x(page):\n page.wait_for_timeout(100)\n"), "test_fake_e2e.py")
entry = {"file": "test_fake_e2e.py", "scope": "test_x", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "x" * 50 + "."}
assert clocks.compare(found, {"entries": [entry], "debt": []}) == {"new": [], "stale_entries": [], "stale_debt": [], "both": []}
assert clocks.compare([], {"entries": [entry], "debt": []})["stale_entries"] == [clocks.key_of(entry)]
assert clocks.compare(found, {"entries": [], "debt": []})["new"] == [clocks.key_of(entry)]
assert clocks.compare([], {"entries": [], "debt": [dict(entry, **{"class": "A"})]})["stale_debt"] == [clocks.key_of(entry)]
def test_the_debt_is_made_again_from_the_sources_and_an_entry_is_never_made():
found = clocks.analyze(fake("def test_x(page):\n page.wait_for_timeout(100)\n page.wait_for_timeout(200)\n"), "test_fake_e2e.py")
reviewed = {"file": "test_fake_e2e.py", "scope": "test_x", "rule": "sleep", "nth": 1, "kind": "negative-window", "reason": "x" * 50 + "."}
stale = {"file": "gone.py", "scope": "test_y", "rule": "sleep", "nth": 1, "kind": "instrument", "reason": "y" * 50 + "."}
before = {"version": 1, "entries": [reviewed, stale], "debt": [{"file": "gone.py", "scope": "f", "rule": "bound", "nth": 1, "class": "B", "reason": "z"}]}
after = clocks.regenerate(before, found)
assert [clocks.key_of(i) for i in after["entries"]] == [clocks.key_of(reviewed), clocks.key_of(stale)], "--write leaves the reviewed entries as they are"
assert [clocks.key_of(i) for i in after["debt"]] == [("test_fake_e2e.py", "test_x", "sleep", 2)], "the corrected occurrence left, the new one is debt"
assert clocks.regenerate(before, found, prune_entries=True)["entries"] == [reviewed]
assert clocks.regenerate(after, found) == after, "made twice, the same"
assert all(i["class"] == "A" and i["reason"] for i in after["debt"])
assert clocks.dump(after) == clocks.dump(clocks.regenerate(after, found)) and clocks.dump(after).endswith("}\n")
def test_every_rule_has_a_known_bad_case_in_this_file():
this = Path(__file__).read_text(encoding="utf-8")
for rule in clocks.RULES:
assert ('"%s"' % rule) in this or ("== ['%s']" % rule) in this or ('["%s"]' % rule) in this, "no known-bad input for the rule %s" % rule
+1 -1
View File
@@ -233,4 +233,4 @@ def test_a_process_that_reads_no_filter_while_it_starts_is_read_again_and_one_th
def test_the_filter_wait_of_the_sandbox_test_is_bounded():
import test_the_socket_process_is_sandboxed_e2e as sandbox
assert 0 < sandbox.STARTUP_SECONDS <= 15
assert 0 < sandbox.STARTUP_SECONDS <= 30
@@ -84,7 +84,7 @@ def test_the_favicon_goes_to_the_site_and_nothing_of_it_to_the_client(firefox_bi
# and nothing above noticed: networkidle reaches the client from
# the lifecycle's timer, not from the reader. A round trip to the
# engine does need the reader.
page.wait_for_function("() => document.title === 'f'", timeout=10000)
page.wait_for_function("() => document.title === 'f'", timeout=30000)
release.set()
# What a client could be told of the favicon comes when its answer is over: wait for the site to have
# written it (a condition with a deadline), then leave the client a short window to say anything. The
@@ -0,0 +1,78 @@
"""The e2e files that install from the index and read GitHub run only in the round after a publication (no browser).
``test_release_e2e.py`` and ``test_upgrade_e2e.py`` (pip, uv, PyPI, the GitHub release and API) can be red for a reason that is nobody's change, and the rule
of the project is that no gate depends on a real site: the gates of a pull request and of a candidate (``e2e.yml``, ``scripts/run_e2e.py``, the hunt) must
not collect them, and ``user-install.yml`` (the round after the publication, weekly and by hand) must still run both. See ``tests/_post_publication.py``.
* the helper: a file is left out unless the command line names it (as ``path`` or ``path::test``), and only the files of the list are touched;
* a real collection (``pytest --collect-only``, no browser): ``-m e2e`` over the whole tests directory holds no test of the two files, and naming them
brings them back; a unit-marked test of the same files is not an e2e test and is not touched;
* the wiring: ``user-install.yml`` names both files with ``-m e2e``, no suite of ``ci/required-suites.json`` lists them (a suite that did would be red when
they are left out), and no other workflow names them.
"""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
import pytest
import _post_publication as post
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parent.parent
TESTS = ROOT / "tests"
def test_a_file_of_the_list_is_left_out_unless_the_command_line_names_it():
release = TESTS / "test_release_e2e.py"
other = TESTS / "test_doh_through_the_proxy_e2e.py"
assert post.is_left_out(release, [])
assert post.is_left_out(release, [str(TESTS)]) and post.is_left_out(release, ["tests"])
assert not post.is_left_out(release, [str(release)])
assert not post.is_left_out(release, ["%s::test_x" % release])
assert post.is_left_out(release, [str(TESTS / "test_upgrade_e2e.py")]), "naming the other file does not name this one"
assert not post.is_left_out(other, []), "only the files of the list are touched"
def _collect(*args: str) -> str:
out = subprocess.run([sys.executable, "-m", "pytest", "--collect-only", "-q", "-m", "e2e", "-o", "addopts=", "-p", "no:cacheprovider", *args],
cwd=ROOT, capture_output=True, text=True, timeout=300)
assert out.returncode in (0, 5), out.stdout[-2000:] + out.stderr[-2000:]
return out.stdout
def test_a_collection_of_the_e2e_that_names_no_file_holds_none_of_the_two():
listed = _collect("-k", "release_e2e or upgrade_e2e or persistent_profile", "tests")
assert "test_persistent_profile_keeps_state.py" in listed, "the selection finds nothing: the check below would pass for no reason\n" + listed[-500:]
assert "test_release_e2e" not in listed and "test_upgrade_e2e" not in listed, listed
def test_naming_the_two_files_brings_back_their_e2e_tests_and_only_those():
listed = _collect("tests/test_release_e2e.py", "tests/test_upgrade_e2e.py")
assert "test_release_e2e.py::test_clean_install_the_way_a_user_does_it" in listed
assert "test_upgrade_e2e.py::test_upgrading_from_the_previous_release_moves_the_core_too" in listed
assert "test_every_test_that_installs_from_the_index_has_the_install_deadline" not in listed, "a test with no e2e marker is not collected by -m e2e"
def test_the_round_after_the_publication_names_both_files_and_nothing_else_does():
user_install = (ROOT / ".github" / "workflows" / "user-install.yml").read_text(encoding="utf-8")
runs = re.findall(r"python -m pytest (tests/test_release_e2e\.py tests/test_upgrade_e2e\.py) -m e2e", user_install)
assert len(runs) == 2, "user-install.yml runs the two files on Linux and on Windows, each named with -m e2e: %r" % runs
for name in post.FILES:
assert (TESTS / name).is_file(), name
suites = json.loads((ROOT / "ci" / "required-suites.json").read_text(encoding="utf-8"))
listed = [t for row in suites for t in row["tests"] if Path(t.split("::")[0]).name in post.FILES]
assert listed == [], "a required suite lists a file that the runs leave out: %s" % listed
for workflow in sorted((ROOT / ".github" / "workflows").glob("*.yml")):
if workflow.name == "user-install.yml":
continue
text = workflow.read_text(encoding="utf-8")
for line in text.splitlines():
if line.lstrip().startswith("#"):
continue
assert not any(name in line for name in post.FILES), "%s runs a post-publication file outside user-install.yml: %s" % (workflow.name, line.strip())
@@ -69,7 +69,7 @@ def _children_of(binary: str):
#: start-up, and Firefox pre-launches content processes, so a process sampled while it starts legitimately reads 0 (run 43523960399: the newest tab
#: process, pid 4090 of [3905, 4002, 4005, 4090], read 0 and the same suite was green on the candidates before). A process that is still 0 after this
#: long has finished starting and runs without a filter: that is the failure the test is for.
STARTUP_SECONDS = 10
STARTUP_SECONDS = 30
def _settled_seccomp(pids, seconds: float = STARTUP_SECONDS) -> dict:
@@ -104,7 +104,7 @@ def test_the_socket_process_and_a_tab_process_have_a_seccomp_filter(firefox_bina
await new Promise(r => setTimeout(r, 1500));
}""")
sockets, tabs = [], []
deadline = time.monotonic() + 20
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
kids = _children_of(firefox_binary)
sockets = [pid for pid, kind in kids if kind == "socket"]
@@ -39,11 +39,13 @@ def test_every_test_that_compares_a_near_and_a_far_duration_runs_in_the_serial_g
assert unserial(FILE.read_text(encoding="utf-8")) == []
def test_the_two_known_tests_are_found():
def test_no_test_of_the_file_compares_a_near_and_a_far_duration_any_more():
tree = ast.parse(FILE.read_text(encoding="utf-8"))
found = sorted(n.name for n in tree.body if isinstance(n, ast.FunctionDef) and _compares_near_and_far(n))
assert found == ["test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server",
"test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away"], found
# Neither of the two known tests does: the first-candidate test holds the far gateway's handshake and waits for the host
# candidate, and the gather after a page judges the association the datagram left on and the order of the candidates
# (tests/test_the_timing_of_the_e2e_tests_is_the_browsers_not_the_runners.py). A new comparison is found by the guard above.
assert found == [], found
def test_a_comparison_without_the_marker_is_refused():
@@ -0,0 +1,476 @@
"""The e2e tests of the first audit fix judge the browser's own time and what happened, not the speed of the runner.
Each test below (no browser, no sleep that decides anything) runs the judgement of an e2e on the case it must still call
red and the case it must call green:
* the first STUN datagram of a PeerConnection is judged by WHICH association carried it, and the gateway says which;
* a handshake the test holds (`Gateway.gate` for all of them, `Gateway.hold` for the ones it chooses) answers nothing until the test
lets it go;
* the road of a TURN server written as a name is judged by an ORDER (the Allocate was answered while the later handshakes were held)
and by a COUNT (the exchanges the gateway, the DoH and the TURN server recorded), never by a duration;
* the page of the key-delay test and of the typing-pause test stamp each event with `event.timeStamp` (the browser's own
creation time), not with `performance.now()` read when the handler happens to run;
* the pages of the `networkidle` cases of `test_a_page_that_moves_on_e2e.py` have no timer: they move from inside `load`
or from the first bytes of a response the server holds open;
* the rate of a screencast is the rate of the frames that came, and a cap that is not honoured is above its ceiling;
* the screenshot of a frame of another site is taken again until it is painted, and says what it saw if it never is.
"""
from __future__ import annotations
import socket
import struct
import threading
import time
import pytest
from _e2e_verdicts import cold_association_problem
from _screencast_evidence import Stream
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
from _waits import wait_until
pytestmark = pytest.mark.unit
# ---------------------------------------------------------------------------
# the first datagram goes out on an association that was ready before the birth
# ---------------------------------------------------------------------------
BORN = 10.0
#: [start, end] of each association granted: #0 is the core's probe, #1 and #2 are the pool of the engine, #3 is made later
ASSOCIATIONS = [[0.1, 0.3], [9.0, 9.4], [9.1, 9.5], [10.05, 10.5]]
def test_a_first_datagram_on_a_ready_association_is_green_at_any_speed():
for at in (10.01, 10.4, 25.0, 300.0): # the same identity whether the machine is quick or three minutes late
assert cold_association_problem(ASSOCIATIONS, [(STUN_NUMBER, STUN_PORT, 1, at)], STUN_NUMBER, BORN) is None
assert cold_association_problem(ASSOCIATIONS, [(STUN_NUMBER, STUN_PORT, 2, at)], STUN_NUMBER, BORN) is None
def test_a_first_datagram_on_an_association_made_after_the_birth_is_red_even_when_it_is_fast():
problem = cold_association_problem(ASSOCIATIONS, [(STUN_NUMBER, STUN_PORT, 3, 10.06)], STUN_NUMBER, BORN)
assert problem and "association #3" in problem and "a cold association" in problem
def test_an_engine_that_asked_for_nothing_or_whose_pool_was_late_or_that_sent_nothing_is_red():
assert "never asked" in cold_association_problem([[0.1, 0.3]], [], STUN_NUMBER, BORN)
assert "no association was completed before" in cold_association_problem(
[[0.1, 0.3], [10.2, 10.6]], [(STUN_NUMBER, STUN_PORT, 1, 10.7)], STUN_NUMBER, BORN)
assert "no STUN datagram" in cold_association_problem(ASSOCIATIONS, [("203.0.113.9", 9, 1, 10.1)], STUN_NUMBER, BORN)
def test_the_first_datagram_is_the_earliest_of_the_log_whatever_the_order_it_was_written_in():
log = [(STUN_NUMBER, STUN_PORT, 1, 10.9), (STUN_NUMBER, STUN_PORT, 3, 10.06)]
assert "association #3" in cold_association_problem(ASSOCIATIONS, log, STUN_NUMBER, BORN)
def _hello(port):
t = socket.create_connection(("127.0.0.1", port), timeout=10)
t.sendall(b"\x05\x01\x00")
return t
def test_the_gateway_says_which_association_carried_each_datagram():
with coherent() as gateway:
clients = []
try:
for _ in range(2):
t = _hello(gateway.port)
assert t.recv(2) == b"\x05\x00"
t.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
reply = t.recv(10)
assert reply[1] == 0
clients.append((t, (socket.inet_ntoa(reply[4:8]), struct.unpack("!H", reply[8:10])[0])))
for _t, relay in clients:
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.sendto(b"\x00\x00\x00\x01" + socket.inet_aton(STUN_NUMBER) + struct.pack("!H", STUN_PORT) + b"x", relay)
udp.close()
assert wait_until(lambda: len(gateway.datagram_via) == 2, 10, lambda: time.sleep(0.01))
finally:
for t, _relay in clients:
t.close()
assert sorted((index, host) for host, _port, index, _at in gateway.datagram_via) == [(0, STUN_NUMBER), (1, STUN_NUMBER)]
# ---------------------------------------------------------------------------
# a handshake the test holds
# ---------------------------------------------------------------------------
def test_a_gateway_with_its_gate_closed_answers_nothing_until_the_gate_opens():
with coherent() as gateway:
gateway.gate = threading.Event()
t = _hello(gateway.port)
t.settimeout(0.4)
with pytest.raises(socket.timeout): # a window of observation: it can only hide a failure, never make one
t.recv(2)
gateway.gate.set()
t.settimeout(10)
assert t.recv(2) == b"\x05\x00"
t.close()
def test_a_gateway_with_no_gate_holds_nothing():
with coherent() as gateway:
assert gateway.gate is None
t = _hello(gateway.port)
t.settimeout(10)
assert t.recv(2) == b"\x05\x00"
t.close()
def _associate(port):
t = _hello(port)
assert t.recv(2) == b"\x05\x00"
t.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
return t
def test_a_gateway_holds_one_handshake_by_its_connection_and_what_it_asked_for_and_the_others_run():
from _socks_servers import WEB_ADDRESS
with coherent() as gateway:
held = threading.Event()
gateway.hold = lambda index, kind: held if kind == "associate" and index == 0 else None
first = _associate(gateway.port) # connection 0: its greeting is answered, its ASSOCIATE is held
assert wait_until(lambda: any(r[2] == "associate" for r in gateway.requests), 10, lambda: time.sleep(0.01))
first.settimeout(0.4)
with pytest.raises(socket.timeout): # a window of observation: it can only hide a failure, never make one
first.recv(10)
# the others are not held, with the first one still held: a CONNECT, and another ASSOCIATE (what a road that does not wait for
# a handshake does), each read with a long timeout that decides nothing
second = _hello(gateway.port)
second.settimeout(10)
assert second.recv(2) == b"\x05\x00"
second.sendall(b"\x05\x01\x00\x01" + socket.inet_aton(WEB_ADDRESS) + struct.pack("!H", 80))
assert second.recv(10)[1] == 0
third = _associate(gateway.port)
third.settimeout(10)
assert third.recv(10)[1] == 0
assert gateway.associations[0][1] is None # the held one is still not answered
held.set()
first.settimeout(10)
assert first.recv(10)[1] == 0
assert [r[1:3] for r in gateway.requests if r[2] != "greeting"] == [(0, "associate"), (1, "connect"), (2, "associate")]
assert [r[2] for r in gateway.requests].count("greeting") == 3
for t in (first, second, third):
t.close()
def test_a_gateway_holds_the_greeting_of_one_connection_when_it_is_asked_to_and_not_the_others():
with coherent() as gateway:
held = threading.Event()
gateway.hold = lambda index, kind: held if index == 1 and kind is None else None
a = _hello(gateway.port)
assert wait_until(lambda: len(gateway.accepted) == 1, 10, lambda: time.sleep(0.01))
b = _hello(gateway.port) # connection 1: its greeting is held
a.settimeout(10)
assert a.recv(2) == b"\x05\x00"
b.settimeout(0.4)
with pytest.raises(socket.timeout):
b.recv(2)
held.set()
b.settimeout(10)
assert b.recv(2) == b"\x05\x00"
a.close()
b.close()
# ---------------------------------------------------------------------------
# the pages stamp events with the browser's time
# ---------------------------------------------------------------------------
def test_the_keys_of_the_delay_test_are_stamped_when_the_browser_made_them():
import test_key_delay_reaches_the_keyboard as module
assert b"e.timeStamp" in module.PAGE and b"performance.now" not in module.PAGE
def test_the_focus_and_the_first_key_of_the_typing_pause_test_are_stamped_when_the_browser_made_them():
import test_a_field_is_typed_after_a_pause as module
page = module.STORE_PAGE.decode()
script = page[page.index("window.__events"):page.index("const answer")]
assert "e.timeStamp" in script and "performance.now" not in script
# ---------------------------------------------------------------------------
# a page that moves with no timer
# ---------------------------------------------------------------------------
def test_the_networkidle_pages_of_a_page_that_moves_have_no_timer_in_them():
import test_a_page_that_moves_on_e2e as module
for name in ["/ir0", "/ir50", "/ix0", "/ix50"]:
page = module.PAGES[name].decode()
assert "setTimeout" not in page and "setInterval" not in page, name
assert "location.replace" in page, name
# 0: inside the load handler itself; 50: when the first bytes of a response the server holds open come in
assert "/hold" not in module.PAGES["/ir0"].decode() and "/hold" in module.PAGES["/ir50"].decode()
assert "127.0.0.1','localhost'" in module.PAGES["/ix0"].decode()
# the pages of the read-at-once test keep their timers: they are the stimulus there, and each read accepts either page
assert "setTimeout" in module.PAGES["/r50"].decode()
# ---------------------------------------------------------------------------
# the rate of the frames that came
# ---------------------------------------------------------------------------
def test_the_rate_of_a_screencast_is_that_of_its_frames_from_the_first_to_the_last():
stream = Stream("x")
assert stream.rate() is None
stream.stamps = [5.0]
assert stream.rate() is None
stream.stamps = [100.0 + 0.5 * i for i in range(6)] # a cap of 2 fps honoured: 5 gaps of 0.5 s
assert stream.rate() == pytest.approx(2.0)
stream.stamps = [100.0 + 0.04 * i for i in range(6)] # a cap that is not honoured: 25 fps
assert stream.rate() == pytest.approx(25.0) and stream.rate() > 2 * 2
# a machine that took ten seconds to deliver the first frame does not change the rate of the ones that came
stream.stamps = [110.0 + 0.5 * i for i in range(6)]
assert stream.rate() == pytest.approx(2.0)
def test_the_rate_is_read_on_the_engines_stamps_not_on_when_a_stalled_client_heard_the_frames():
"""The known-bad input: a cap of 2 fps honoured by the engine, heard by a client that stalled for 2 s and then
received four frames at once. On the arrival times that reads 5 fps, above the ceiling of 4 (red with no defect);
on the engine's stamps it is 2."""
stream = Stream("x")
for i, heard in enumerate([102.0, 102.0, 102.0, 102.0, 102.5, 103.0]):
stream.on_frame({"data": b"", "timestamp": 100.0 + 0.5 * i})
stream.arrivals[-1] = heard
assert stream.rate(stream.arrivals) == pytest.approx(5.0) # what the old rate read
assert stream.rate() == pytest.approx(2.0)
# ---------------------------------------------------------------------------
# the screenshot taken again until the frame is painted
# ---------------------------------------------------------------------------
class _Page:
def wait_for_timeout(self, ms):
time.sleep(ms / 1000.0)
def _looks(colours):
"""A fake decode: the colour at every point, from the list of looks the page will give (the last one repeats)."""
looks = iter(colours)
last = [next(looks)]
def decode(_data):
last[0] = next(looks, last[0])
shade = last[0]
return (1, 1, lambda x, y: shade)
return decode
def test_a_frame_that_is_painted_late_is_waited_for_and_one_never_painted_is_red_with_what_was_seen(monkeypatch):
import test_fission_frames_tree_input_and_pixels_e2e as module
pink = module.PINK
monkeypatch.setattr(module, "decode_png", _looks([(255, 255, 255)] * 3 + [pink]))
taken = []
found = module.painted_shot(_Page(), lambda: taken.append(1) or b"png", [((5, 5), pink)], seconds=5.0)
assert found[2](0, 0) == pink and len(taken) == 3 # two looks too early, the third painted
monkeypatch.setattr(module, "decode_png", _looks([(255, 255, 255)]))
with pytest.raises(AssertionError) as red:
module.painted_shot(_Page(), lambda: b"png", [((5, 5), pink)], seconds=0.3)
assert "never painted" in str(red.value) and "(255, 255, 255)" in str(red.value)
# ---------------------------------------------------------------------------
# the road of a TURN server written as a name: an order and a count, never a duration
# ---------------------------------------------------------------------------
from _e2e_verdicts import (held_handshake_problem, turn_chain_problem, turn_exchanges, turn_exchanges_most, # noqa: E402
turn_exchanges_problem)
TURN_BORN = 10.0
HOST = "198.51.100.7"
#: #0 the core's probe, #1 and #2 the pool of the engine (granted before the birth), #3 begun after it (held by the test)
TURN_ASSOCIATIONS = [[0.1, 0.3], [9.0, 9.26], [9.1, 9.36], [10.1, None]]
#: what the gateway read: the pool's two ASSOCIATEs before the birth, then the CONNECT to the DoH that carries the question
REQUESTS = [(9.0, 1, "associate", "association #1"), (9.1, 2, "associate", "association #2"),
(10.02, 3, "connect", "192.0.2.53:443"), (10.1, 4, "associate", "association #3")]
QUESTIONS = [("turn.relay-only.test", 1)]
#: the Allocate without credentials (answered 401), then the one with them: two transactions
ALLOCATES = [(10.5, b"\x01" * 12, 3, False), (10.8, b"\x02" * 12, 3, True)]
VIA = [(HOST, 3478, 1, 10.5), (HOST, 3478, 1, 10.8)]
def _scaled(k, requests, allocates, associations, via):
"""The same road on a machine k times slower: every stamp is k times later. An order and a count do not notice."""
return ([[None if t is None else t * k for t in a] for a in associations],
[(r[0] * k,) + tuple(r[1:]) for r in requests],
[(a[0] * k,) + tuple(a[1:]) for a in allocates],
[v[:3] + (v[3] * k,) for v in via])
def _road(k=1.0, allocated=10.8, released=11.5, held=(10.1,), requests=REQUESTS, questions=QUESTIONS, allocates=ALLOCATES,
via=VIA, auth=False):
associations, requests, allocates, via = _scaled(k, requests, allocates, TURN_ASSOCIATIONS, via)
return turn_chain_problem(TURN_BORN * k, None if allocated is None else allocated * k, released * k, [h * k for h in held], requests,
questions, allocates, associations, via, HOST, auth)
def test_a_road_that_costs_what_the_protocols_cost_is_green_at_the_speed_of_any_machine():
for k in (1.0, 0.01, 40.0, 5000.0): # a quick one, and a machine so slow that every stamp is five thousand times later
assert _road(k) is None, k
assert turn_exchanges(TURN_BORN, 10.8, REQUESTS, QUESTIONS, ALLOCATES) == (turn_exchanges_most(), []) # exactly the protocols' five
# the connection that loaded the page still carries the question: no CONNECT after the birth, three exchanges
kept = [r for r in REQUESTS if r[2] != "connect"]
assert _road(requests=kept) is None and turn_exchanges(TURN_BORN, 10.8, kept, QUESTIONS, ALLOCATES)[0] == 3
# nothing was held (no association was begun after the pool was ready): nothing to wait for
assert _road(held=()) is None
def test_the_most_the_road_may_cost_is_five_exchanges_and_six_with_a_user_and_a_password():
assert turn_exchanges_most() == 5 and turn_exchanges_most(auth=True) == 6 # 2 + 1 + 2, and the sub-negotiation of RFC 1929
assert turn_exchanges(TURN_BORN, 10.8, REQUESTS, QUESTIONS, ALLOCATES, auth=True)[0] == 6
assert _road(auth=True) is None
def test_handshakes_that_wait_for_each_other_are_red_even_when_the_machine_is_quick():
# the Allocate was answered only after the test let the held handshakes go: it was waiting for one
problem = _road(allocated=11.6, released=11.5, held=(10.1, 10.4, 10.7))
assert problem and "after the 3 held association handshake(s)" in problem and "one handshake waits for another" in problem
for k in (0.001, 1.0, 5000.0):
assert _road(k, allocated=11.6, released=11.5), k
# and one that never came at all
assert "never answered an Allocate" in _road(allocated=None)
def test_the_held_verdict_is_an_order_of_two_stamps_not_a_distance_between_them():
assert held_handshake_problem(11.499, 11.5, [10.1]) is None
assert held_handshake_problem(11.5, 11.5, [10.1]) is None # at the same instant: not after
assert held_handshake_problem(11.501, 11.5, [10.1])
assert held_handshake_problem(1e-6, 1e6, [10.1]) is None # however late the let-go
def test_one_exchange_more_than_the_protocols_ask_for_is_red_and_at_the_most_is_not():
# a second question for the name (an AAAA nobody needs)
problem = _road(questions=QUESTIONS + [("turn.relay-only.test", 28)])
assert problem and "6 exchanges" in problem and "5 at most" in problem and "2 DoH questions" in problem
# a second CONNECT: the DoH connection made again for the question
again = REQUESTS + [(10.05, 5, "connect", "192.0.2.53:443")]
problem = _road(requests=again)
assert problem and "7 exchanges" in problem and "2 SOCKS5 control connections" in problem
# a third Allocate transaction (a transaction id that is not a retransmission)
problem = _road(allocates=ALLOCATES + [(10.7, b"\x03" * 12, 3, True)])
assert problem and "6 exchanges" in problem and "3 Allocate transactions" in problem
# none of those is a matter of speed
for k in (0.01, 5000.0):
assert _road(k, questions=QUESTIONS * 2), k
def test_the_exchanges_are_the_ones_between_the_birth_and_the_allocation_and_an_association_is_none_of_them():
# before the birth: the DoH connection of the page; after the allocation: the POST of the page
around = [(9.5, 0, "connect", "192.0.2.53:443"), (11.9, 9, "connect", "127.0.0.1:8000")] + REQUESTS
assert turn_exchanges_problem(TURN_BORN, 10.8, around, QUESTIONS, ALLOCATES) is None
# a later Allocate is not on the road, and another type of transaction (a Refresh) is not an Allocate
late = ALLOCATES + [(12.0, b"\x04" * 12, 3, True), (10.7, b"\x05" * 12, 4, True)]
assert turn_exchanges_problem(TURN_BORN, 10.8, REQUESTS, QUESTIONS, [a for a in late if a[2] == 3]) is None
# five associations begun after the birth cost the road nothing it counts (the held test and the cold check judge them)
pool = REQUESTS + [(10.2 + i / 10, 20 + i, "associate", "association #%d" % (4 + i)) for i in range(5)]
assert turn_exchanges_problem(TURN_BORN, 10.8, pool, QUESTIONS, ALLOCATES) is None
def test_an_allocation_on_an_association_made_after_the_birth_is_red_too():
problem = _road(via=[(HOST, 3478, 3, 10.5), (HOST, 3478, 3, 10.8)])
assert problem and "a cold association" in problem and "association #3" in problem
def test_the_turn_server_counts_transactions_and_a_retransmission_is_not_another():
import hashlib
import _turn_chain as chain_mod
server = chain_mod.TurnServer()
try:
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.settimeout(5)
first = struct.pack("!HHI", 0x0003, 8, chain_mod.MAGIC) + b"\x07" * 12 + struct.pack("!HH", 0x0019, 4) + b"\x11\x00\x00\x00"
for _ in range(3): # the request, and the retransmissions ICE makes of it
udp.sendto(first, server.address)
udp.recvfrom(65536)
key = hashlib.md5(b"u:" + chain_mod.REALM.encode() + b":" + chain_mod.PASSWORD.encode(), usedforsecurity=False).digest()
body = (chain_mod._attr(0x0019, b"\x11\x00\x00\x00") + chain_mod._attr(0x0006, b"u") +
chain_mod._attr(0x0014, chain_mod.REALM.encode()) + chain_mod._attr(0x0015, chain_mod.NONCE.encode()))
udp.sendto(chain_mod._message(0x0003, b"\x08" * 12, body, key), server.address)
udp.recvfrom(65536)
udp.close()
assert len(server.seen) == 4
assert [(t[1], t[2], t[3]) for t in server.transactions()] == [(b"\x07" * 12, 0x0003, False), (b"\x08" * 12, 0x0003, True)]
finally:
server.close()
def test_a_client_that_walks_the_road_by_the_protocols_spends_exactly_the_exchanges_the_verdict_allows():
"""The number is the protocols', not a slack: a plain client (no browser) that takes an association, resolves the name through the
DoH and asks for the Allocate twice (the first request three times: ICE retransmits) is judged green and spends all of it."""
import hashlib
import _turn_chain as chain_mod
from _doh_servers import QTYPE_A
from test_the_udp_chain_helper import _resolve_through_doh, _socks_associate, _via
with chain_mod.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
t, relay = _socks_associate(chain) # the pool: before the birth
born = time.monotonic() - chain.t0
_resolve_through_doh(chain, chain_mod.TURN_NAME)
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
u.settimeout(5)
alloc = struct.pack("!HHI", 0x0003, 8, chain_mod.MAGIC) + b"\x01" * 12 + struct.pack("!HH", 0x0019, 4) + b"\x11\x00\x00\x00"
for _ in range(3):
_via(u, relay, chain_mod.TURN_IP, chain_mod.TURN_PORT, alloc)
key = hashlib.md5(b"u:" + chain_mod.REALM.encode() + b":" + chain_mod.PASSWORD.encode(), usedforsecurity=False).digest()
body = (chain_mod._attr(0x0019, b"\x11\x00\x00\x00") + chain_mod._attr(0x0006, b"u") +
chain_mod._attr(0x0014, chain_mod.REALM.encode()) + chain_mod._attr(0x0015, chain_mod.NONCE.encode()))
answer = _via(u, relay, chain_mod.TURN_IP, chain_mod.TURN_PORT, chain_mod._message(0x0003, b"\x02" * 12, body, key))
assert struct.unpack("!H", answer[:2])[0] == 0x0103
u.close()
t.close()
allocated_at = chain.turn.allocations[0][3] - chain.t0
questions = [(q.name, q.qtype) for q in chain.doh.queries if q.name == chain_mod.TURN_NAME]
allocates = [(a[0] - chain.t0,) + tuple(a[1:]) for a in chain.turn.transactions()]
assert questions == [(chain_mod.TURN_NAME, QTYPE_A)] and len(chain.turn.seen) == 4 and len(allocates) == 2
requests = list(chain.requests)
assert [r[2] for r in requests] == ["greeting", "associate", "greeting", "connect"]
assert requests[3][3].startswith("192.0.2.53:")
assert turn_exchanges(born, allocated_at, requests, questions, allocates) == (turn_exchanges_most(), [])
assert turn_exchanges_problem(born, allocated_at, requests, questions, allocates) is None
def test_the_gateway_logs_the_greeting_the_connect_and_the_associate_of_each_connection_and_only_those():
import _turn_chain as chain_mod
from _doh_servers import DOH_BOOTSTRAP
from test_the_udp_chain_helper import _socks_connect
with chain_mod.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
assert chain.requests == []
s, code = _socks_connect(chain, "192.0.2.77", 9) # refused: not the DoH, and still a CONNECT the gateway read
s.close()
assert code == 2
s, code = _socks_connect(chain, DOH_BOOTSTRAP, 443)
s.close()
assert code == 0
kinds = [(r[1], r[2], r[3]) for r in chain.requests]
assert kinds == [(0, "greeting", ""), (0, "connect", "192.0.2.77:9"), (1, "greeting", ""), (1, "connect", DOH_BOOTSTRAP + ":443")]
assert all(0 <= r[0] < 30 for r in chain.requests)
def test_a_connection_that_opened_after_the_retry_is_red_on_a_page_that_ran_and_not_on_one_the_machine_stopped():
from _e2e_verdicts import opened_at_the_retry_problem
assert opened_at_the_retry_problem(60, 12) is None
assert opened_at_the_retry_problem(2999, 5) is None
assert opened_at_the_retry_problem(3100, 40) is not None, "the slow road: the page ran all along and the connection opened at the retry"
assert "3100" in opened_at_the_retry_problem(3100, 40)
assert opened_at_the_retry_problem(3100, 2400) is None, "the page's own loop stopped for 2.4 s: the machine, not the road"
assert opened_at_the_retry_problem(9000, 999) is not None
assert opened_at_the_retry_problem(9000, 1000) is None
def test_the_turn_page_reports_its_birth_reads_a_srflx_after_its_tick_and_has_an_empty_twin():
import _turn_chain as chain_mod
page = chain_mod.PAGE_HTML
assert "window.__result.born = Date.now()" in page[:page.index("new RTCPeerConnection")]
handler = page[page.index("pc.onicecandidate"):]
guard = handler[:handler.index("clearInterval(tick)")]
assert "status !== 'PENDING' ||" not in guard and "window.__result.late = status !== 'PENDING'" in guard
assert "window.__result.posted = true" in handler
assert "await" not in handler[handler.index("window.__result.posted = true"):], "the status is final in the step that says `posted`: a read made at that moment sees DONE"
assert handler.index("(await r.json()).ok") < handler.index("window.__result.posted = true")
with chain_mod.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
assert chain.page.warm_url.endswith(chain_mod.WARM_PATH)
import urllib.request
body = urllib.request.urlopen("http://127.0.0.1:%d%s" % (chain.page.port, chain_mod.WARM_PATH), timeout=10).read()
assert b"RTCPeerConnection" not in body and b"warm" in body
@@ -256,8 +256,9 @@ def test_a_frame_that_shares_the_process_keeps_the_assertion_red_and_one_that_do
url = "http://localhost:1/grid"
monkeypatch.setattr(ff, "spin_trial", lambda observer, frame: _same_process_trial(2500))
seconds = iter(range(0, 10_000, 7)) # a clock that moves 7 s at each look, so the 30 s of the proof are spent without waiting
with pytest.raises(AssertionError) as red:
ff.assert_other_process(Observer(), Frame())
ff.assert_other_process(Observer(), Frame(), clock=lambda: next(seconds))
assert "shares the process of the observer" in str(red.value) and "(0, " in str(red.value)
calls = []
@@ -268,3 +269,20 @@ def test_a_frame_that_shares_the_process_keeps_the_assertion_red_and_one_that_do
monkeypatch.setattr(ff, "spin_trial", starved_then_healthy)
ff.assert_other_process(Observer(), Frame())
assert len(calls) == 3
# a machine that starves the observer for more spins than the fixed count of the old proof is still waited for, until the deadline
calls.clear()
def starved_for_a_long_time(observer, frame):
calls.append(1)
return _other_process_trial(starved=len(calls) <= 2 * ff.TRIALS)
monkeypatch.setattr(ff, "spin_trial", starved_for_a_long_time)
ff.assert_other_process(Observer(), Frame(), clock=lambda: 0)
assert len(calls) == 2 * ff.TRIALS + 1
def test_the_proof_of_another_process_has_no_fixed_pause_and_no_fixed_count():
import inspect
spin = inspect.getsource(ff.spin_trial)
assert "wait_for_timeout" not in spin, "the spin is waited for as a condition (its end), not for spin_ms + 800 ms"
assert "range(TRIALS)" not in inspect.getsource(ff.assert_other_process), "the proof of another process is waited for until a deadline"
+61 -8
View File
@@ -3,7 +3,8 @@
A page asks for a TURN allocation at a server written as a NAME (`turn:turn.relay-only.test:3478`), as the real leak-test pages
do: no STUN, so a server-reflexive candidate can only be born from a successful allocation. Its logic is the logic of such a page:
a tick of 2 seconds from the start of the page that marks TIMEOUT, cleared the moment the srflx arrives (before the POST made for
it, so the verdict does not depend on the POST coming back within the tick); the server compares the address of that srflx with the source the TURN server saw for the allocation.
it); the server compares the address of that srflx with the source the TURN server saw for the allocation. The tick is the model of
the page and decides nothing here: the verdict is read off the stamps of the gateway, the DoH and the TURN server (see below).
The only road to anything is a gateway at 130 ms of round trip (every step of its control connection, every datagram, every
chunk of a tunnel): the TURN server is at an unroutable documentation address that only the gateway maps to it; the names (the
@@ -16,7 +17,15 @@ What the product must do, to be what a retail Firefox is with no proxy at all (t
* the name of the ICE server is resolved by the DoH of Firefox (`network.trr.mode` 3, found with no DNS at 162.159.61.4),
whose request leaves THROUGH the proxy of the context: a SOCKS5 CONNECT to 162.159.61.4:443; no local resolution;
* the UDP to the address the DoH gave leaves through the gateway's relay (address type 1);
* and all of it, with the DoH and the handshakes of the associations the browser needs, fits in the tick of the page.
* and nothing of it waits for a handshake it does not need, nor costs an exchange more than the protocols ask for. Neither is a
number of milliseconds (`_e2e_verdicts.turn_chain_problem`): (1) from the instant the pool of associations is ready the test HOLDS
the answer of every association handshake begun after it (`Gateway.hold`), and the TURN server has to answer the Allocate with
credentials all the same, BEFORE the test lets them go: a handshake that waits for another leaves the road waiting for the test,
on any machine, and a quick or a slow one makes no difference; (2) from the birth of the PeerConnection to that Allocate the
gateway, the DoH and the TURN server recorded at most one SOCKS5 control connection with its CONNECT to the DoH (greeting and
CONNECT, RFC 1928), one DoH question (the A record, RFC 8484), and the two transactions of an Allocate (the first answered 401, the
second with the long-term credential, RFC 8656 and RFC 8489): five exchanges, and one more is red; (3) the Allocate leaves on an
association that was ready before the birth. The page is waited for until its srflx is posted (30 s), not until its tick.
It fails on an engine that does not keep this (the one of the wrong candidate), and says WHY: the explanation lists what the
DoH, the gateway, the TURN server and the page each saw. The engine refuses to resolve a name that is not a literal behind a
@@ -28,11 +37,16 @@ context made with `ignore_https_errors=True` (applied per user context to the Do
the provider is the FakeDoh's own name (`doh.gateway.test`, declared through `extra_prefs`): the DoH of Mozilla is HSTS-preloaded
and Firefox never accepts an override for it.
"""
import threading
import time
import pytest
import _turn_chain as chain_mod
from _doh_servers import DOH_PROVIDER_PREFS
from _e2e_verdicts import turn_chain_problem
from _udp_line import declared_udp, egress_by_proxy, measure_servers
from _waits import wait_until
pytestmark = pytest.mark.e2e
@@ -103,20 +117,59 @@ def _walk(gateway, firefox_binary, engine_at_least, prefs):
proxy=gateway.proxy, udp_stun_servers=measure_servers(gateway),
extra_prefs={**prefs, **DOH_PROVIDER_PREFS}) as browser:
page = browser.new_context(ignore_https_errors=True).new_page()
page.goto(gateway.page.url, wait_until="domcontentloaded", timeout=60000)
# An empty page first, through the proxy: Firefox learns the proxy there and its pool makes the associations. The
# PeerConnection is born once the gateway has granted one (the first granted is the core's own probe, no association of the
# engine), so "ready before the birth" is a fact of the road and not a race with the load of the machine.
page.goto(gateway.page.warm_url, wait_until="domcontentloaded", timeout=60000)
wait_until(lambda: len([a for a in gateway.associations if a[1] is not None]) >= 2, 30, lambda: page.wait_for_timeout(50))
# From here on every association handshake the engine begins is HELD (the gateway answers nothing on it): the pool is ready and
# the road of the name needs none, so the Allocate must be answered while they are held. The page is waited for until it has
# posted its srflx (30 s); its tick of 2 s is its model and decides nothing.
first_held = len(gateway.accepted)
held = threading.Event()
held_from = time.monotonic() - gateway.t0
gateway.hold = lambda index, kind: held if kind == "associate" and index >= first_held else None
loaded = "the page loaded"
try:
page.wait_for_function("window.__done === true", timeout=9000)
except Exception: # noqa: BLE001
pass
try:
page.goto(gateway.page.url, wait_until="domcontentloaded", timeout=60000)
page.wait_for_function("window.__result.posted === true", timeout=30000)
except Exception as error: # noqa: BLE001 - the verdict below says what the road did; this says where the page stopped
loaded = "the page stopped: %s" % str(error).splitlines()[0][:200]
finally:
released_at = time.monotonic() - gateway.t0
gateway.hold = None
held.set()
try:
page.wait_for_function("window.__result.candidates.some(c => c.indexOf(' typ relay ') >= 0)", timeout=3000)
page.wait_for_function("window.__result.candidates.some(c => c.indexOf(' typ relay ') >= 0)", timeout=30000)
except Exception: # noqa: BLE001
pass
result = page.evaluate("window.__result")
# what the road looked like, read before anything else asks the gateway for an association (the declared_udp below does)
t0, wall0 = gateway.t0, gateway.wall0
born = (result.get("born") or wall0 * 1000.0) / 1000.0 - wall0 # the asserts below name a page that never ran
associations = [list(a) for a in gateway.associations]
via = list(gateway.datagram_via)
requests = list(gateway.requests)
doh_questions = [(q.name, q.qtype) for q in gateway.doh.queries if q.name == chain_mod.TURN_NAME]
allocates = [(t - t0, tid, mtype, credentials) for t, tid, mtype, credentials in gateway.turn.transactions()]
allocated_at = gateway.turn.allocations[0][3] - t0 if gateway.turn.allocations else None
held_starts = [a[0] for a in associations if a[0] >= held_from]
auth = gateway.user is not None
declared = declared_udp(gateway.proxy, measure_servers(gateway))
assert declared == "coherent", "the core did not measure the chain's UDP coherent (%s): the engine would not use the relay" % declared + gateway.explain(result)
ok = result.get("status") == "DONE" and gateway.page.verdicts and gateway.page.verdicts[-1]["ok"]
assert ok, "the page did not get a server-reflexive candidate that the TURN server saw, before its tick of 2 s:" + gateway.explain(result)
assert ok, "the page did not get a server-reflexive candidate that the TURN server saw (the page was waited for 30 s):" + gateway.explain(result)
problem = turn_chain_problem(born, allocated_at, released_at, held_starts, requests, doh_questions, allocates, associations, via,
chain_mod.TURN_IP, auth)
seen = ("%s; the page's tick of 2 s %s; associations %s (held from %.3f s, let go at %.3f s); datagrams to the TURN server %s; requests of "
"the gateway %s; DoH questions for the TURN name %s; Allocate transactions %s; the PeerConnection born at %.3f s; the "
"allocation at %s s" % (
loaded, "had passed (the srflx was late)" if result.get("late") else "had not passed", associations, held_from, released_at,
[d for d in via if d[0] == chain_mod.TURN_IP], [(round(r[0], 3),) + tuple(r[1:]) for r in requests], doh_questions,
[(round(a[0], 3), a[2], "credentials" if a[3] else "no credentials") for a in allocates], born,
None if allocated_at is None else round(allocated_at, 3)))
assert problem is None, "%s; %s%s" % (problem, seen, gateway.explain(result))
# what the PAGE reads: a server-reflexive candidate that is the gateway's exit, and the relay of the TURN server it asked
srflx = (result.get("srflx") or "").split()
assert len(srflx) > 5 and srflx[4] == gateway.exit_ip, "the srflx of the page is not the exit of the gateway %s: %r" % (gateway.exit_ip, result.get("srflx"))
+1 -1
View File
@@ -33,7 +33,7 @@ READ = """() => new Promise(resolve => {
if (read().length) return resolve(read());
speechSynthesis.addEventListener('voiceschanged', () => resolve(read()),
{once: true});
setTimeout(() => resolve(read()), 5000);
setTimeout(() => resolve(read()), 30000);
})"""
+150 -66
View File
@@ -31,7 +31,7 @@ from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler, HTTPServer
import pytest
from _host_address import this_host_address
from _socks_servers import MEASURE_NUMBER, STUN_PORT, Socks5TcpOnly
from _socks_servers import MEASURE_NUMBER, STUN_NUMBER, STUN_PORT, Socks5TcpOnly
from _udp_line import bench_report, declared_udp, declared_udp_or_absent, egress_by_proxy, measure_servers
# ──────────────────────────────────────────────────────────────────────────
@@ -269,15 +269,22 @@ def test_no_orphan_prefs_in_baseline():
# ──────────────────────────────────────────────────────────────────────────
# Fake-proxy infrastructure for e2e: a tiny TCP-only SOCKS5 server (Socks5TcpOnly, in _socks_servers.py).
# ──────────────────────────────────────────────────────────────────────────
# Same per-event probe CreepJS runs (kept tiny; raw string = one escape level).
_PROBE_JS = r"""async () => {
const pc = new RTCPeerConnection({iceCandidatePoolSize:1, iceServers:[{urls:[
'stun:stun4.l.google.com:19302','stun:stun3.l.google.com:19302']}]});
# The per-event probe a fingerprinting page runs (kept tiny; raw string = one escape level). Its STUN server is an argument: a test names one of its own
# (a server on this host, or a number nothing answers), never a public one.
_PROBE_JS = r"""async (stun) => {
const pc = new RTCPeerConnection({iceCandidatePoolSize:1, iceServers:[{urls:[stun]}]});
pc.createDataChannel('');
const cands = [];
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
await pc.setLocalDescription(await pc.createOffer({offerToReceiveAudio:1, offerToReceiveVideo:1}));
await new Promise(r => setTimeout(r, 3500));
// until the gather says it is complete (what the page reads is the whole of it), or 30 s: the deadline of the wait, not a
// window the verdict depends on
await new Promise(resolve => {
const timer = setTimeout(resolve, 30000);
const done = () => { if (pc.iceGatheringState === 'complete') { clearTimeout(timer); resolve(); } };
pc.addEventListener('icegatheringstatechange', done);
done();
});
const sdp = (pc.localDescription && pc.localDescription.sdp) || '';
try { pc.close(); } catch(e) {}
return { candidates: cands, sdp };
@@ -329,10 +336,22 @@ def test_the_gather_is_real_without_a_proxy(local_https_page):
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
with _launch(binary_path=binary) as browser:
page = browser.new_context().new_page()
page.goto(local_https_page, wait_until="domcontentloaded", timeout=60000)
res = page.evaluate(_PROBE_JS)
from _socks_servers import FakeStun
# The STUN server is the test's own, on the address of this host (a real one is a third party and the runner's network): the engine's UDP is
# real, the server answers with the address it is reached at, and a srflx born from it is judged as before.
try:
host = this_host_address()
except pytest.skip.Exception: # no default route: the same gather against a server on loopback (no srflx is born from it)
host = "127.0.0.1"
stun = FakeStun(host, bind_host=host)
try:
with _launch(binary_path=binary) as browser:
page = browser.new_context().new_page()
page.goto(local_https_page, wait_until="domcontentloaded", timeout=60000)
res = page.evaluate(_PROBE_JS, "stun:%s:%d" % stun.address)
finally:
stun.close()
cands = candidates(res["candidates"])
assert cands, "ICE produced ZERO candidates (blocked)"
assert host_is_mdns(cands), [c["address"] for c in host_candidates(cands)]
@@ -345,7 +364,7 @@ def test_the_gather_is_real_without_a_proxy(local_https_page):
@pytest.mark.e2e
def test_not_blocked_behind_tcp_only_socks(socks5_tcp_only):
def test_not_blocked_behind_tcp_only_socks(socks5_tcp_only, local_https_page):
"""Behind a TCP-only SOCKS proxy on a remote origin, ICE must still complete
(host .local candidates), not return zero candidates: a fully blocked
WebRTC is itself a tell. The session declares its network from the seed
@@ -354,15 +373,14 @@ def test_not_blocked_behind_tcp_only_socks(socks5_tcp_only):
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
proxy = {"server": f"socks5://127.0.0.1:{socks5_tcp_only.port}"}
try:
with _launch(binary_path=binary, proxy=proxy) as browser:
page = browser.new_context().new_page()
# remote origin loaded THROUGH the local SOCKS proxy (not localhost,
# so no proxy-bypass) -> WebRTC proxy config active.
page.goto("https://example.com/", wait_until="domcontentloaded", timeout=70000)
res = page.evaluate(_PROBE_JS)
except Exception as exc: # network/proxy unavailable in this environment
pytest.skip(f"proxy/network path unavailable: {exc!r}")
# The page is the test's own, carried THROUGH the proxy (the local address is let through the proxy by the two prefs, as the declared-network tests
# do): a real site is a third party, and a proxy or network that fails is a failure here, not a skip. The STUN server is a number nothing answers;
# behind a TCP-only proxy no UDP leaves at all.
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
with _launch(binary_path=binary, proxy=proxy, extra_prefs=prefs) as browser:
page = browser.new_context().new_page()
page.goto(local_https_page, wait_until="domcontentloaded", timeout=70000)
res = page.evaluate(_PROBE_JS, "stun:%s:%d" % (STUN_NUMBER, STUN_PORT))
cands = candidates(res["candidates"])
assert cands, "behind SOCKS the gather returned ZERO candidates (blocked)"
assert host_is_mdns(cands)
@@ -384,7 +402,7 @@ _RELAY_PROBE_JS = r"""async (stun) => {
pc.addEventListener('icecandidateerror', e => { errors.push({code: e.errorCode, text: e.errorText, url: e.url}); at.error = Math.round(performance.now() - t0); });
await pc.setLocalDescription(await pc.createOffer());
await new Promise(resolve => {
const timer = setTimeout(resolve, 25000);
const timer = setTimeout(resolve, 30000);
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') { at.complete = Math.round(performance.now() - t0); clearTimeout(timer); resolve(); }
});
@@ -407,7 +425,7 @@ _ICE_IDS = ["ice_in_the_socket_process", "the_caller_asks_for_ice_in_the_content
"the_caller_asks_for_no_socket_process_and_the_lock_wins"]
def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms, page_first_ms=None):
def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms):
"""Launch the default engine behind a local gateway with coherent UDP, `rtt_ms` away, gather with a STUN server only
its relay reaches, and say whether the page's request took the relay and what the gather looked like."""
binary = _e2e_binary()
@@ -415,7 +433,7 @@ def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_m
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
from _socks_servers import STUN_NUMBER, STUN_PORT, WEB_ADDRESS, coherent
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
user, password = credentials or (None, None)
# The relay sits on the address of this host, as a real gateway's does: the engine's ICE sockets are bound to an
@@ -428,12 +446,7 @@ def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_m
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True, **ice_prefs}
with _launch_behind(gateway, binary_path=binary, extra_prefs=extra_prefs) as browser:
page = browser.new_context().new_page()
if page_first_ms is None:
page.goto("about:blank")
else:
# A page that is loaded through the gateway, and a while later asks for WebRTC.
page.goto("http://%s/" % WEB_ADDRESS) # by address: the browser resolves names itself
page.wait_for_timeout(page_first_ms)
page.goto("about:blank")
res = page.evaluate(_RELAY_PROBE_JS, stun)
carried = [(host, port) for host, port, _payload in gateway.datagrams]
stun_requests = gateway.stun.requests
@@ -497,7 +510,25 @@ def test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_it
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
@pytest.mark.wall_clock # its verdict compares two durations (near and far): the e2e run gives it the machine alone
_START_A_GATHER_JS = r"""async (stun) => {
const g = window.__gather = {host: null, srflx: null, complete: false, candidates: [], errors: [], born: Date.now()};
const t0 = performance.now();
const pc = window.__pc = new RTCPeerConnection({iceServers: [{urls: [stun]}]});
pc.createDataChannel('');
pc.addEventListener('icecandidate', e => {
if (!e.candidate || !e.candidate.candidate) return;
g.candidates.push(e.candidate.candidate);
const typ = (e.candidate.candidate.match(/ typ (\w+)/) || [])[1];
if (typ === 'host' && g.host === null) g.host = Math.round(performance.now() - t0);
if (typ === 'srflx' && g.srflx === null) g.srflx = Math.round(performance.now() - t0);
});
pc.addEventListener('icecandidateerror', e => g.errors.push({code: e.errorCode, text: e.errorText, url: e.url}));
pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') g.complete = true; });
await pc.setLocalDescription(await pc.createOffer());
return true;
}"""
@pytest.mark.e2e
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
@pytest.mark.usefixtures("the_udp_line")
@@ -505,43 +536,91 @@ def test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away. The layer made its associations one after the other on the thread of
the ICE sockets, a connect, a greeting, an authentication and the ASSOCIATE each, so the first candidate of the page
came out after about twelve round trips (host candidate at 2.3 s on Linux and 3.0 s on Windows, against well under a
second next to the gateway), and a page that times `icecandidate` reads it. A candidate does not wait for the proxy:
the host candidate of the far gather comes within a round trip and a quarter of a second of the near one, and the
srflx within the handshake (four round trips) and a STUN request (one) of its host candidate."""
rtt_ms = 250
near_ok, near_verdict, near = _gather_behind_a_coherent_gateway(monkeypatch, ("alice", "s3cret"), ice_prefs, 0)
far_ok, far_verdict, far = _gather_behind_a_coherent_gateway(monkeypatch, ("alice", "s3cret"), ice_prefs, rtt_ms)
print(f"[first candidate] near {near}, {rtt_ms} ms away {far}")
assert near_ok, near_verdict
assert far_ok, far_verdict
assert far["host"] - near["host"] <= rtt_ms + 250, (
f"the first candidate waited for the gateway: host candidate at {far['host']} ms behind a gateway {rtt_ms} ms away, "
f"{near['host']} ms next to it. {far_verdict}")
assert far["srflx"] - far["host"] <= 5 * rtt_ms + 250, (
f"the srflx came {far['srflx'] - far['host']} ms after the host candidate. {far_verdict}")
second next to the gateway), and a page that times `icecandidate` reads it. A candidate does not wait for the proxy.
The gateway here is not far, it is HELD: from the moment the page asks for the gather, every answer of the gateway on a
control connection waits for the test (`Gateway.gate`). The host candidate has to come while the gateway has answered
nothing, which no speed of the machine changes (a host candidate that waits for the gateway never comes, and the test
is red at its deadline); then the gateway is let go and the srflx has to be born through its relay."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
from _socks_servers import STUN_NUMBER, coherent
from _waits import watch
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
with coherent(user="alice", password="s3cret", relay_host=this_host_address()) as gateway:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True, **ice_prefs}
with _launch_behind(gateway, binary_path=binary, extra_prefs=extra_prefs) as browser:
page = browser.new_context().new_page()
page.goto("about:blank")
granted_before = len([a for a in gateway.associations if a[1] is not None])
gateway.gate = threading.Event() # held: nothing the gateway answers reaches the engine from here on
try:
page.evaluate(_START_A_GATHER_JS, stun)
host = watch(lambda: page.evaluate("window.__gather.host"), lambda at: at is not None, 30,
lambda: page.wait_for_timeout(50))
granted_while_held = len([a for a in gateway.associations if a[1] is not None]) - granted_before
finally:
gateway.gate.set()
srflx = watch(lambda: page.evaluate("window.__gather.srflx"), lambda at: at is not None, 30,
lambda: page.wait_for_timeout(50))
res = page.evaluate("window.__gather")
carried = [(host_, port) for host_, port, _payload in gateway.datagrams]
seen = (f"candidates: {res['candidates']}; ICE errors: {res['errors']}; associations granted while the gateway was held: "
f"{granted_while_held}; datagrams the relay carried: {carried}; host candidate looks: {host.render()}; "
f"srflx looks: {srflx.render()}")
assert host.ok, "the first candidate waited for the gateway: no host candidate while the gateway answered nothing. " + seen
assert srflx.ok and (STUN_NUMBER, STUN_PORT) in carried, (
"the srflx was not born through the relay once the gateway was let go. " + seen)
@pytest.mark.wall_clock # its verdict compares two durations (near and far): the e2e run gives it the machine alone
@pytest.mark.e2e
@pytest.mark.usefixtures("the_udp_line")
def test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server(monkeypatch):
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away, a page loaded through it, and two seconds later the page asks for
WebRTC. Next to a gateway the srflx comes at once; behind this one it may come later by the road itself, the round
trip of the relay to the STUN server and back, and by nothing else: the connect, the greeting, the authentication and
the ASSOCIATE of each socket (about 0.56 s against the real driver) are made before the page asks, when the proxy
of the context is first used, not after. A target without the proxy has no such cost to show."""
rtt_ms = 250
near_ok, near_verdict, near = _gather_behind_a_coherent_gateway(
monkeypatch, ("alice", "s3cret"), {}, 0, page_first_ms=2000)
far_ok, far_verdict, far = _gather_behind_a_coherent_gateway(
monkeypatch, ("alice", "s3cret"), {}, rtt_ms, page_first_ms=2500)
print(f"[page first] near {near}, {rtt_ms} ms away {far}")
assert near_ok, near_verdict
assert far_ok, far_verdict
assert far["host"] - near["host"] <= 100, f"the host candidate waited: {far_verdict}"
assert far["srflx"] - near["srflx"] <= rtt_ms + 250, (
f"the srflx came {far['srflx']} ms after the offer behind a gateway {rtt_ms} ms away, {near['srflx']} ms next to "
f"it: more than the road to the server ({rtt_ms} ms). {far_verdict}")
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away, a page loaded through it, and a while later the page asks for WebRTC.
The connect, the greeting, the authentication and the ASSOCIATE of each socket (about 0.56 s against the real driver) are made
before the page asks, when the proxy of the context is first used, not after: the STUN request of the page leaves on an
association the gateway had granted before the PeerConnection was born, and the host candidate does not wait for the srflx.
Both are facts the gateway and the page record, whatever the speed of the machine (a comparison with the same gather next to a
gateway was a comparison of two launches of a browser): the gateway says which association carried the datagram, and the
page orders its candidates. The page waits until the gateway has granted an association of the engine (30 s), not 2.5 s."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
from _e2e_verdicts import cold_association_problem
from _socks_servers import STUN_NUMBER, STUN_PORT, WEB_ADDRESS, coherent
from _waits import wait_until, watch
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
with coherent(user="alice", password="s3cret", relay_host=this_host_address(), rtt_ms=250) as gateway:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
with _launch_behind(gateway, binary_path=binary, extra_prefs=extra_prefs) as browser:
page = browser.new_context().new_page()
page.goto("http://%s/" % WEB_ADDRESS) # by address: the browser resolves names itself
# the pool makes its associations: wait until the gateway has granted one of the engine's (the first granted is the
# core's probe); the verdict names what it saw if none came
wait_until(lambda: len([a for a in gateway.associations if a[1] is not None]) >= 2, 30,
lambda: page.wait_for_timeout(50))
page.evaluate(_START_A_GATHER_JS, stun)
srflx = watch(lambda: page.evaluate("window.__gather.srflx"), lambda at: at is not None, 30,
lambda: page.wait_for_timeout(50))
gather = page.evaluate("window.__gather")
associations = [list(a) for a in gateway.associations]
via = list(gateway.datagram_via)
born = gather["born"] / 1000.0 - gateway.wall0
seen = (f"candidates: {gather['candidates']}; ICE errors: {gather['errors']}; associations (start, end) seen by the gateway: "
f"{associations}; datagrams and the association each left on: {via}; srflx looks: {srflx.render()}")
assert srflx.ok, "no srflx within 30 s behind a gateway 250 ms away. " + seen
problem = cold_association_problem(associations, via, STUN_NUMBER, born)
assert problem is None, f"{problem}. {seen}"
assert gather["host"] is not None and gather["host"] < gather["srflx"], (
f"the host candidate (at {gather['host']} ms) did not come before the srflx ({gather['srflx']} ms): it waited for the "
f"road to the server. {seen}")
@pytest.mark.e2e
@@ -588,6 +667,7 @@ def test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context(m
from invisible_core import _geo
from _socks_servers import coherent
from _waits import wait_until
host = this_host_address()
turn_host, turn_port = "198.51.100.9", 3478
with coherent(exit_ip="203.0.113.7", user="alice", password="s3cret", relay_host=host) as session, coherent(exit_ip="198.51.100.77", user="bob", password="hunter2", relay_host=host) as context:
@@ -596,13 +676,15 @@ def test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context(m
with _launch_behind(session, binary_path=binary, extra_prefs=extra_prefs) as browser:
page = browser.new_context(proxy=context.proxy).new_page()
page.goto("about:blank")
# the page starts the ICE agent and leaves it alive; it is closed AFTER the gateway of the context has been handed the TURN address (a
# condition with a deadline, not 6 s of a timer of the page: an agent closed first would never have tried the server on a slow machine)
page.evaluate("""async (turn) => {
const pc = new RTCPeerConnection({iceServers: [{urls: [turn], username: 'u', credential: 'p'}]});
const pc = window.__pc = new RTCPeerConnection({iceServers: [{urls: [turn], username: 'u', credential: 'p'}]});
pc.createDataChannel('');
await pc.setLocalDescription(await pc.createOffer());
await new Promise(r => setTimeout(r, 6000));
pc.close();
}""", f"turn:{turn_host}:{turn_port}?transport=tcp")
wait_until(lambda: (turn_host, turn_port) in context.connects, 30, lambda: page.wait_for_timeout(50))
page.evaluate("() => window.__pc.close()")
in_context = [c for c in context.connects if c == (turn_host, turn_port)]
in_session = [c for c in session.connects if c == (turn_host, turn_port)]
assert in_context and not in_session, (
@@ -645,7 +727,9 @@ def _gather_where_the_udp_is_dropped(gateway, monkeypatch, measured):
# an immediate error, never a candidate that nothing allocated.
protocols = sorted({c["proto"].upper() for c in candidates(res["candidates"]) if c["typ"] == "host"})
assert protocols == ["TCP", "UDP"], f"host candidates of a retail on a network that drops UDP: {res['candidates']}"
assert 10_000 <= res["at_ms"]["error"] <= 13_000, (
# The floor only (an error that comes at once is a request that was never sent); a slow machine can only stretch nICEr's
# 11.1-11.3 s, and the page waits 30 s for the end of the gather.
assert res["at_ms"]["error"] >= 10_000, (
f"the 701 of the UDP request came at {res['at_ms']['error']} ms; nICEr's time on a network that drops UDP is 11.1-11.3 s")