mirror of
https://github.com/daijro/camoufox.git
synced 2026-11-19 00:07:28 +00:00
* fix(screen): cache the spoofed screen per nsScreen so availWidth costs what stock's does getter-cost-parity failed on main (run 40142262379): screen.availHeight took 361 ns against stock Firefox 158.0's 178 ns on the CI runner, just over the 2x bound. Under the default fingerprinting protection, GetAvailRect does stock's work and then read the context id twice, two per-context memo entries (each a __tls_get_addr call from libxul), the global screen size, and the context's navigator.platform, which it copied and converted to UTF-8 on every call. nsScreen now keeps the spoofed rect and OS for its context and re-reads them only when RoverfoxStorageManager's generation moves (a new Generation() accessor; the same staleness rule its own memo uses). SpoofedOSFor also takes UTF-16, so NavigatorManager::GetSpoofedOS no longer converts. Local, same host, fastest of 3 guard runs each (stock 88-90 ns): availHeight, launch identity 117-122 ns -> 107-110 ns availHeight, context identity 132-134 ns -> 107 ns screen.width 76-78 ns -> 71 ns (stock 54-56) Launch and context identities now cost the same, and availHeight / height is 1.5, as stock's is (it was 1.74 here, 2.3 on the runner). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(virtdisplay): count a process reaped mid-read as dead _alive opens /proc/<pid>/stat and then reads it. When Xvfb exits between the two, which is the moment test_xvfb_dies_with_the_process_that_started_it waits for, the read raises ProcessLookupError (ESRCH), not FileNotFoundError, and the test failed instead of passing (PR #950's pythonlib job). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(virtdisplay): judge Xvfb's exit on the wait loop's own reading The loop stops when it sees Xvfb as a zombie, and the assert then read /proc again. That second read lands while Xvfb's new parent reaps it, the window in which open() succeeds and read() raises ESRCH. Asserting on the loop's last reading removes the second read; _alive already counts ESRCH as gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(guards): run on the binary under test, never the installed release audio-matches-stock failed PR #950's spoofing job with a GitHub API 403 (rate limit). Re-encoding its config, it called get_env_vars without path=, so the fontconfig lookup fell back to camoufox_path(): on a runner with no release installed that fetched one through the anonymous GitHub API (31.7 s of the guard on main) and read the released bundle, not the build under test. launch_camoufox, which system-ui-font-spoofing uses, passed no executable_path at all, so that guard tested an installed or downloaded release and could not catch a regression in the build. Both now use the binary under test, and helpers makes camoufox_path() raise in every guard, so a fallback to the installed release fails at once on a dev box with a cached release as well as on a runner without one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
181 lines
5.6 KiB
Python
181 lines
5.6 KiB
Python
"""
|
|
Tests for camoufox.virtdisplay.
|
|
|
|
Mirrors typescript/tests/virtdisplay.test.ts.
|
|
|
|
Run with:
|
|
cd python && python -m pytest tests/test_virtdisplay.py -v
|
|
|
|
VIRTDISPLAY_TEST_N controls the concurrent-launch count. Default is kept
|
|
low so the test passes on any developer box; set to e.g. 1000 to exercise
|
|
real scaling. At high N you will need `ulimit -n` headroom -- each Xvfb
|
|
takes one X11 socket plus our -displayfd pipe.
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
import signal
|
|
import subprocess # nosec
|
|
import sys
|
|
import time
|
|
from typing import List, Set
|
|
|
|
import pytest
|
|
|
|
from camoufox.virtdisplay import VirtualDisplay
|
|
|
|
DISPLAY_RE = re.compile(r"^:\d+$")
|
|
N = int(os.environ.get("VIRTDISPLAY_TEST_N", "50"))
|
|
|
|
pytestmark = pytest.mark.skipif(
|
|
sys.platform != "linux", reason="VirtualDisplay is Linux-only"
|
|
)
|
|
|
|
|
|
# Track every VirtualDisplay we spawn so the fixture can guarantee
|
|
# cleanup even if an assertion fails mid-test.
|
|
@pytest.fixture
|
|
def tracked() -> List[VirtualDisplay]:
|
|
items: List[VirtualDisplay] = []
|
|
yield items
|
|
for vd in items:
|
|
try:
|
|
vd.kill()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _track(items: List[VirtualDisplay], vd: VirtualDisplay) -> VirtualDisplay:
|
|
items.append(vd)
|
|
return vd
|
|
|
|
|
|
def _wait_for_exit(vd: VirtualDisplay, timeout_s: float = 5.0) -> None:
|
|
deadline = time.monotonic() + timeout_s
|
|
while time.monotonic() < deadline:
|
|
if vd.proc is None or vd.proc.poll() is not None:
|
|
return
|
|
time.sleep(0.025)
|
|
|
|
|
|
def test_single_launch_returns_valid_display_and_kill_terminates_xvfb(tracked):
|
|
vd = _track(tracked, VirtualDisplay())
|
|
display = vd.get()
|
|
assert DISPLAY_RE.match(display), display
|
|
assert vd.proc is not None
|
|
assert vd.proc.poll() is None # alive
|
|
|
|
vd.kill()
|
|
_wait_for_exit(vd)
|
|
# kill() reaps the child and clears the handle, so `proc is None` is the
|
|
# post-condition; a surviving handle must at least report an exit code.
|
|
assert vd.proc is None or vd.proc.poll() is not None # exited
|
|
|
|
|
|
def test_get_is_idempotent_within_one_virtual_display(tracked):
|
|
vd = _track(tracked, VirtualDisplay())
|
|
a = vd.get()
|
|
b = vd.get()
|
|
assert a == b
|
|
|
|
|
|
def test_concurrent_reservations_all_get_unique_displays(tracked):
|
|
# Every VirtualDisplay spawns its own Xvfb. Each Xvfb scans up from :0
|
|
# and atomically claims the first free X11 socket (kernel-mediated
|
|
# bind, no userspace race). -displayfd reports the chosen number back
|
|
# to us. A duplicate here would mean we mis-parsed or mis-routed the
|
|
# displayfd output, or two Xvfbs somehow bound the same socket.
|
|
vds = [_track(tracked, VirtualDisplay()) for _ in range(N)]
|
|
|
|
displays = [vd.get() for vd in vds]
|
|
|
|
for d in displays:
|
|
assert DISPLAY_RE.match(d), d
|
|
|
|
unique: Set[str] = set(displays)
|
|
assert len(unique) == len(displays), (
|
|
f"duplicate displays: {len(displays) - len(unique)} of {len(displays)}"
|
|
)
|
|
|
|
# Every Xvfb is alive.
|
|
for vd in vds:
|
|
assert vd.proc is not None and vd.proc.poll() is None
|
|
|
|
# Tear them all down and confirm every Xvfb actually exited -- no
|
|
# leaked processes.
|
|
for vd in vds:
|
|
vd.kill()
|
|
for vd in vds:
|
|
_wait_for_exit(vd)
|
|
for vd in vds:
|
|
assert vd.proc is None or vd.proc.poll() is not None
|
|
|
|
|
|
def test_released_display_numbers_can_be_reused_on_the_next_launch(tracked):
|
|
a = _track(tracked, VirtualDisplay())
|
|
a_display = a.get()
|
|
|
|
a.kill()
|
|
_wait_for_exit(a)
|
|
|
|
# Spawning a new Xvfb after release must succeed. The new display
|
|
# number may or may not equal a_display -- Xvfb's allocation order is
|
|
# its concern -- but we must get *some* display.
|
|
b = _track(tracked, VirtualDisplay())
|
|
b_display = b.get()
|
|
assert DISPLAY_RE.match(b_display), b_display
|
|
|
|
b.kill()
|
|
_wait_for_exit(b)
|
|
|
|
# Sanity: a_display was a valid form too.
|
|
assert DISPLAY_RE.match(a_display), a_display
|
|
|
|
|
|
def _alive(pid: int) -> bool:
|
|
"""True while `pid` runs; a zombie waiting for its new parent counts as dead."""
|
|
try:
|
|
with open(f"/proc/{pid}/stat") as f:
|
|
return f.read().rsplit(")", 1)[1].split()[0] != "Z"
|
|
# ProcessLookupError: reaped between open() and read(), which is how a
|
|
# zombie's /proc entry goes away under a reader.
|
|
except (FileNotFoundError, ProcessLookupError):
|
|
return False
|
|
|
|
|
|
def test_xvfb_dies_with_the_process_that_started_it():
|
|
"""A SIGKILLed launcher never runs kill(), so the kernel must stop Xvfb (#868).
|
|
|
|
Supervisors, `timeout` and CI cancellation end the Python process with a
|
|
signal that skips every `finally`. Xvfb then has to go on its own, and
|
|
remove its lock and socket on the way out.
|
|
"""
|
|
child = subprocess.Popen( # nosec
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
"import sys, time\n"
|
|
"from camoufox.virtdisplay import VirtualDisplay\n"
|
|
"vd = VirtualDisplay()\n"
|
|
"print(vd.get()[1:], vd.proc.pid, flush=True)\n"
|
|
"time.sleep(60)\n",
|
|
],
|
|
stdout=subprocess.PIPE,
|
|
text=True,
|
|
)
|
|
display, pid = child.stdout.readline().split()
|
|
xvfb = int(pid)
|
|
assert _alive(xvfb)
|
|
|
|
child.send_signal(signal.SIGKILL)
|
|
child.wait()
|
|
|
|
deadline = time.monotonic() + 5
|
|
# Judged on the loop's last reading: once it sees a zombie, its new parent
|
|
# is about to reap it, and a second /proc read lands in that reap.
|
|
while (alive := _alive(xvfb)) and time.monotonic() < deadline:
|
|
time.sleep(0.025)
|
|
assert not alive, f"Xvfb {xvfb} outlived the process that started it"
|
|
assert not os.path.exists(f"/tmp/.X{display}-lock")
|
|
assert not os.path.exists(f"/tmp/.X11-unix/X{display}")
|