Files
playwright/tests/test_pin_dicts_are_valid.py
Federico 8ade6f90ad One implementation of the humanize pref contract, and the pin surface follows the core (#200)
* One implementation of the humanize pref contract, not two

`_cursor.humanize_prefs` was a second answer to "which stealthfox.humanize*
prefs does this session get", and no code in src/ called it. The live answer is
the core's `compose_session_prefs`, reached through `_session.build_prefs`,
which the two front doors share.

The two disagreed. The core emits `stealthfox.humanize.stepMs`; the deleted
duplicate did not, so two tests were green about a pref set the product has
never produced. That is the shape that makes a dead path look maintained: it
had tests, so it read as load-bearing.

The properties those tests asserted are real and they move to the live path -
the two front doors emit the same humanize prefs, and a cap is never written
without the toggle - now measured through `build_prefs`. A known-bad mutation
of the live decision (always pass the cap through, which is what the duplicate
effectively did) turns them red.

`max_seconds_for` stays: it has two callers in `_session.py` and is the only
thing left that knows what a `humanize=` value means in seconds.

* The shim test stops passing an argument that is going away

`generate_profile` loses `fixed_gpu_class=` in the next core: it was a second
spelling of `pin["gpu.class_tier"]`. It was incidental here - what this file
protects is that the shim path and the core path produce the same prefs - so
dropping it leaves the property intact and the test working against the
published core as well as the next one.

The `forced_gpu_class` import stays, and gains an assertion. The import SHAPE
is what this file exists to protect, and that name is still exported; it is a
query now rather than a knob.

* The pinning page and its gate follow two keys out of the pin table

`codec.webspeech_synth` and `screen.tier` stop being pinnable in the next core:
one was drawn and never read (the pref is a constant, so the sampled value only
made the profile disagree with the browser on about 12% of seeds), the other
could not work by construction, since pins land after the draw.

The page loses both rows and says where they went, because a reader who
remembers a key needs to be told rather than find it absent - the rule this
file's own `fonts` test already enforces.

The gate gains the third level of an idiom it already had twice:
`_NOT_PINNABLE` for top-level scalars, `_NOT_PINNABLE_GROUPS` for whole groups,
and now `_NOT_PINNABLE_FIELDS` for a field inside a group. Each carries a
reason, and each refuses an excuse that has gone stale - either because the
field came back to the pin table or because it left the profile entirely.

* The page and the gate follow screen.avail_* out of the pin table

* Pin invisible-core 30.21.0, and say what it removes

0.16.0 has not shipped, so these entries join it rather than inventing a
version: the three pin keys that could not work, the sampled codec field that
contradicted the browser, and the deleted duplicate of the humanize pref
contract.

* Two e2e modules stop pinning keys that no longer exist, and a gate that would have said so

`screen.avail_width` and `screen.avail_height` left the pin surface, and these
two modules kept pinning them. Both are marked `e2e`, so the default selection
deselects them: every local run was green and the failure appeared on the Linux
CI leg as 81 errors, four minutes in. The migration was not incomplete because
it was hard - it was incomplete because the only thing that would have noticed
needed a browser.

Nothing about the question needs one. A pin dict is a dict of strings and
`_validate_pin_key` is a pure function, so `test_pin_dicts_are_valid.py` reads
every pin dict in src/, tests/, scripts/ and examples/ and asks the real
validator. It finds the two shapes this repository writes - `pin=` inline and a
module-level PIN shared across an e2e module - and it is killed by both: a
removed key returning to an e2e PIN, and an invented key in an inline dict.

Its first draft was red on a healthy repository, which is the state where a gate
teaches people to ignore it. Two exclusions came out of that, both deliberate
and both documented in the file: dicts inside `with pytest.raises(...)` hold
keys that are SUPPOSED to be refused, and `_NOT_PINNABLE` is a table of reasons
whose name merely contains the letters PIN.

The assertions in the two e2e modules get stronger for the change: availWidth
and availHeight are now read as values the engine computed, not as values the
caller believed it had set.
2026-09-15 04:32:53 +02:00

150 lines
6.0 KiB
Python

"""Every pin dict written anywhere in this repository is accepted by the validator.
WHY THIS EXISTS. On 2026-09-15 three keys left the pin surface in
`invisible_core`, and two test files here kept pinning two of them. Both files
are marked `e2e`, so the default selection - `-m 'not slow and not e2e'` -
deselects them: every local run was green, and the failure appeared on a CI leg
that launches a browser, as **81 errors** in a job that takes four minutes to
say so. The migration was not incomplete because it was hard. It was incomplete
because the only thing that would have noticed needed a browser.
Nothing here needs a browser. A pin dict is a dict of strings, and
`_validate_pin_key` is a pure function, so the question "does this key exist"
can be answered by reading the source and calling it. That is the whole gate.
It finds pin dicts two ways, because the repository writes them two ways:
* a dict passed as `pin=` to any call, anywhere;
* a module-level dict named `PIN`, `*_PIN` or `PIN_*`, which is the shape the
e2e files use so one profile can be shared by a module of tests.
And it skips two things on purpose, both found by the first draft going red on a
perfectly healthy repository - the state in which a gate teaches people to
ignore it:
* anything inside `with pytest.raises(...)`. Those dicts hold keys that are
SUPPOSED to be refused; flagging them would be flagging the test for
testing. Four files do this deliberately.
* names that merely contain the letters PIN. `_NOT_PINNABLE` is a table of
reasons, not a pin dict, and matching it read its explanations as keys.
Only STRING keys are checked. A key built at runtime is not something a reader
can check either, and there are none today.
"""
from __future__ import annotations
import ast
import pathlib
import pytest
from invisible_core._fpforge.profile import _validate_pin_key
pytestmark = pytest.mark.unit
_ROOT = pathlib.Path(__file__).resolve().parents[1]
_TREES = ("src", "tests", "scripts", "examples")
def _python_files():
for tree in _TREES:
d = _ROOT / tree
if not d.is_dir():
continue
for f in d.rglob("*.py"):
if "__pycache__" in str(f) or "/_pw/" in str(f).replace("\\", "/"):
continue
yield f
def _is_pin_name(name: str) -> bool:
u = name.upper()
return u == "PIN" or u.endswith("_PIN") or u.startswith("PIN_")
def _raising_lines(tree) -> set:
"""Every line inside a `with pytest.raises(...)` block."""
out = set()
for node in ast.walk(tree):
if not isinstance(node, (ast.With, ast.AsyncWith)):
continue
for item in node.items:
call = item.context_expr
if (isinstance(call, ast.Call)
and isinstance(call.func, ast.Attribute)
and call.func.attr == "raises"):
out.update(range(node.lineno, (node.end_lineno or node.lineno) + 1))
return out
def _pin_dicts(path: pathlib.Path):
"""(line, [keys]) for every pin dict literal in one file."""
try:
tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
except SyntaxError: # not ours to judge
return
refused = _raising_lines(tree)
for node in ast.walk(tree):
if isinstance(node, ast.Call):
for kw in node.keywords:
if (kw.arg == "pin" and isinstance(kw.value, ast.Dict)
and kw.value.lineno not in refused):
yield kw.value.lineno, _string_keys(kw.value)
elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict):
names = [t.id for t in node.targets if isinstance(t, ast.Name)]
if any(_is_pin_name(n) for n in names):
yield node.value.lineno, _string_keys(node.value)
def _string_keys(d: ast.Dict):
return [k.value for k in d.keys
if isinstance(k, ast.Constant) and isinstance(k.value, str)]
def test_every_pin_dict_in_the_repository_uses_keys_that_exist():
bad = []
for path in _python_files():
for line, keys in _pin_dicts(path):
for key in keys:
try:
_validate_pin_key(key)
except ValueError as exc:
bad.append("%s:%d %r - %s"
% (path.relative_to(_ROOT), line, key,
str(exc).split(".")[0]))
assert not bad, (
"these pin dicts name keys the validator refuses, so every call that "
"uses them raises:\n " + "\n ".join(bad) +
"\nThe pin surface lives in invisible_core; a key that left it has to "
"leave here too.")
def test_the_scan_actually_finds_the_dicts_it_claims_to():
"""A gate that scanned nothing would pass this file forever.
Both shapes have to be found, because both exist: the e2e modules build a
module-level PIN and share it across a module of tests, while the unit tests
pass `pin=` inline. If either count goes to zero, the scan stopped matching
the way the repository is written rather than the repository becoming clean.
"""
inline = module_level = 0
for path in _python_files():
src = path.read_text(encoding="utf-8", errors="replace")
try:
tree = ast.parse(src)
except SyntaxError:
continue
for node in ast.walk(tree):
if isinstance(node, ast.Call):
inline += sum(1 for kw in node.keywords
if kw.arg == "pin" and isinstance(kw.value, ast.Dict))
elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict):
if any(_is_pin_name(t.id) for t in node.targets
if isinstance(t, ast.Name)):
module_level += 1
assert inline >= 5, f"only {inline} inline `pin=` dicts found; the scan is blind"
assert module_level >= 2, (
f"only {module_level} module-level PIN dicts found; the e2e modules use "
f"that shape and they are what this gate was written for")