Skip to content

The agent that grows with you

tests: resolve platforms() specs in the lane selector and runner note

ethernet4fda664b0f8d
diff --git a/scripts/ci/list_os_marked_tests.py b/scripts/ci/list_os_marked_tests.py
index 5eeba0f99a9..abf0fa8e20e 100644
--- a/scripts/ci/list_os_marked_tests.py
+++ b/scripts/ci/list_os_marked_tests.py
@@ -18,10 +18,14 @@ never which tests run. Over-selecting here is harmless (the skips drop the
extras); the failure mode to care about is UNDER-selecting, which is why
the workflow fails the job when zero tests end up selected.
-A file matches when a quoted ``platforms("...")`` spec names the platform —
-including negated (``"not macos"``) and any-of lists. The match is anchored
-inside the string literal so bare identifiers (a variable named ``windows``)
-don't produce false positives.
+A file matches when a quoted spec inside a ``mark.platforms(...)`` call
+COVERS the platform, resolved the way the conftest gate resolves it:
+``"posix"`` covers linux and macOS, ``"any"`` covers every lane, and a
+negated spec (``"not macos"``) lists on every lane since it admits all the
+others (and the named one keeps its import, harmlessly). Matching the
+literal word only would drop every ``platforms("posix")`` file from the
+macOS lane. The match is anchored inside the string literal so bare
+identifiers (a variable named ``windows``) don't produce false positives.
Usage:
python scripts/ci/list_os_marked_tests.py macos [tests_root]
@@ -40,12 +44,48 @@ from pathlib import Path
_VALID_PLATFORMS = ("linux", "macos", "windows")
+# Mirrors tests/conftest.py::_PLATFORM_ALIASES, keyed by lane name rather than
+# sys.platform value: this side never runs on the host it is asking about.
+_SPEC_HOSTS = {
+ "linux": frozenset({"linux"}),
+ "macos": frozenset({"macos"}),
+ "windows": frozenset({"windows"}),
+ "posix": frozenset({"linux", "macos"}),
+ "any": frozenset(_VALID_PLATFORMS),
+}
+_PLATFORMS_CALL = re.compile(r"mark\.platforms\(([^)]*)\)")
+_QUOTED = re.compile(r"""["']([^"']*)["']""")
+
+
+def gated_specs(text: str) -> set[str]:
+ """Every quoted spec inside the ``mark.platforms(...)`` calls of a test file.
+
+ Keyword values (``arch="arm64"``) come along; they resolve to no host below,
+ so they can never select a lane.
+ """
+ return {
+ spec.strip().lower()
+ for call in _PLATFORMS_CALL.finditer(text)
+ for spec in _QUOTED.findall(call.group(1))
+ }
+
+
+def spec_hosts(spec: str) -> frozenset[str]:
+ """Lane names a spec admits; ``not X`` admits every lane but X's; unknown → none."""
+ leaf = spec.removeprefix("not ").strip()
+ hosts = _SPEC_HOSTS.get(leaf, frozenset())
+ return _SPEC_HOSTS["any"] - hosts if spec.startswith("not ") else hosts
+
+
+def file_gates_on(text: str, platform: str) -> bool:
+ """True when some spec covers *platform* — or is negated (see module docstring)."""
+ return any(
+ platform in spec_hosts(spec) or spec.startswith("not ") for spec in gated_specs(text)
+ )
+
def find_marked_files(platform: str, root: Path) -> list[Path]:
"""Return every ``test_*.py`` under *root* gating on *platform*."""
- pattern = re.compile(
- rf'platforms\(\s*[^)]*?"[^")]*\b{re.escape(platform)}\b[^")]*"'
- )
hits: list[Path] = []
# os.walk, not Path.rglob: rglob raises FileNotFoundError when a directory
# (a sibling job's __pycache__) vanishes mid-scan; os.walk skips it.
@@ -58,7 +98,7 @@ def find_marked_files(platform: str, root: Path) -> list[Path]:
text = path.read_text(encoding="utf-8-sig", errors="replace")
except OSError:
continue
- if pattern.search(text):
+ if file_gates_on(text, platform):
hits.append(path)
return sorted(hits)
diff --git a/scripts/run_tests_parallel.py b/scripts/run_tests_parallel.py
index 27886f4c850..804700c5198 100644
--- a/scripts/run_tests_parallel.py
+++ b/scripts/run_tests_parallel.py
@@ -58,6 +58,12 @@ from concurrent.futures import ThreadPoolExecutor, Future
from pathlib import Path
from typing import Dict, List, Optional, Tuple
+# The CI lane selector owns the platforms() spec resolver; share it so the
+# "skipped on this host" note and the lanes can never disagree.
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+from scripts.ci.list_os_marked_tests import gated_specs, spec_hosts # noqa: E402
+
+
def _runner_scratch_root() -> str:
"""Per-run temp roots live on DISK, never the system temp dir: a full-suite run writes
gigabytes of tmp_path fixtures and /tmp is RAM-backed tmpfs on many Linux hosts. /var/tmp is
@@ -192,35 +198,35 @@ def _read_files_from(spec: str) -> List[str]:
return [line.strip() for line in text.splitlines() if line.strip()]
-_OS_MARKERS = {
- "linux_only": ("linux", "the main Linux CI lane"),
- "macos_only": ("darwin", "the macOS Python-tests lane"),
- "windows_only": ("win32", "the Windows Python-tests lane"),
+# Lane names keyed the way platforms() specs resolve (scripts/ci/list_os_marked_tests.py
+# shares the resolver with the CI selector so the note and the lanes never disagree).
+_HOST_LANE = {"linux": "linux", "darwin": "macos", "win32": "windows"}
+_LANES = {
+ "linux": "the main Linux CI lane",
+ "macos": "the macOS Python-tests lane",
+ "windows": "the Windows Python-tests lane",
}
def _off_host_marker_files(files: List[Path]) -> dict[str, int]:
- """Count discovered files referencing each marker for an OS we are not on.
+ """Count discovered files carrying a platforms() spec that excludes this host.
- Whole-word text match, same approach as scripts/ci/list_os_marked_tests.py:
+ Text-level scan, same resolver as scripts/ci/list_os_marked_tests.py:
over-counting a prose mention is harmless here (the note is informational);
what matters is never reporting 0 while gated tests exist.
"""
- off_host = {
- marker: re.compile(rf"\b{marker}\b")
- for marker, (host_prefix, _) in _OS_MARKERS.items()
- if not sys.platform.startswith(host_prefix)
- }
- counts = {marker: 0 for marker in off_host}
+ host = _HOST_LANE.get(sys.platform, sys.platform)
+ counts: dict[str, int] = {}
for path in files:
try:
text = path.read_text(encoding="utf-8-sig", errors="replace")
except OSError:
continue
- for marker, pattern in off_host.items():
- if pattern.search(text):
- counts[marker] += 1
- return {marker: n for marker, n in counts.items() if n}
+ for spec in gated_specs(text):
+ hosts = spec_hosts(spec)
+ if hosts and host not in hosts:
+ counts[spec] = counts.get(spec, 0) + 1
+ return counts
def _approximately_count_tests(
@@ -1376,16 +1382,16 @@ def main() -> int:
# Host-OS gating note: tests marked for another OS were skipped by the
# conftest hook, not run. Say so explicitly — a green local run on Linux
- # proves nothing about the macos_only/windows_only tests, and the reader
+ # proves nothing about the platforms("windows") tests, and the reader
# should know where they DO run rather than misreading skips as coverage.
off_host = _off_host_marker_files(files)
if off_host:
print()
- for marker, n in sorted(off_host.items()):
- _, lane = _OS_MARKERS[marker]
+ for spec, n in sorted(off_host.items()):
+ lanes = ", ".join(_LANES[lane] for lane in sorted(spec_hosts(spec)))
print(
- f" note: {marker} tests (in {n} file{'s' if n != 1 else ''}) were "
- f"SKIPPED on this host ({sys.platform}); they run on {lane}."
+ f" note: platforms({spec!r}) tests (in {n} file{'s' if n != 1 else ''}) were "
+ f"SKIPPED on this host ({sys.platform}); they run on {lanes}."
)
# Zero tests collected across the WHOLE run is NOT a pass. Per-file rc=5
diff --git a/tests/ci/test_list_os_marked_tests.py b/tests/ci/test_list_os_marked_tests.py
index 724fbb2ea36..e85de64eae0 100644
--- a/tests/ci/test_list_os_marked_tests.py
+++ b/tests/ci/test_list_os_marked_tests.py
@@ -97,6 +97,25 @@ def test_negated_spec_lists_for_that_lane(tmp_path):
assert any(p.endswith("test_negated.py") for p in listed)
[email protected]("spec,lanes", [
+ ("posix", {"linux", "macos"}), ("any", {"linux", "macos", "windows"}),
+ ("not linux", {"linux", "macos", "windows"}), # admits the others; named lane keeps its import
+ ("macos", {"macos"}),
+])
+def test_specs_resolve_to_every_lane_they_admit(tmp_path, spec, lanes):
+ """The selector resolves specs like the conftest gate: ``platforms("posix")``
+ files must reach the macOS lane, not just files spelling out ``"macos"``."""
+ _write(
+ tmp_path,
+ "test_gated.py",
+ f'import pytest\n\n\[email protected]("{spec}")\ndef test_x():\n pass\n',
+ )
+ for platform in ("linux", "macos", "windows"):
+ result = _run(platform, str(tmp_path))
+ listed = any(p.endswith("test_gated.py") for p in result.stdout.split())
+ assert listed is (platform in lanes), (platform, result.stdout, result.stderr)
+
+
def test_unknown_platform_is_rejected(tmp_path):
result = _run("amiga", str(tmp_path))
assert result.returncode == 2
diff --git a/tests/scripts/test_run_tests_parallel.py b/tests/scripts/test_run_tests_parallel.py
index 1465a4afad4..0a387efd783 100644
--- a/tests/scripts/test_run_tests_parallel.py
+++ b/tests/scripts/test_run_tests_parallel.py
@@ -42,8 +42,11 @@ def isolated_probe_environment(monkeypatch):
def _probe_root(tmp_path):
root = tmp_path / "runner-root"
scripts = root / "scripts"
- scripts.mkdir(parents=True, exist_ok=True)
- shutil.copy2(Path(__file__).resolve().parents[2] / "scripts" / "run_tests_parallel.py", scripts)
+ (scripts / "ci").mkdir(parents=True, exist_ok=True)
+ real = Path(__file__).resolve().parents[2] / "scripts"
+ shutil.copy2(real / "run_tests_parallel.py", scripts)
+ # The runner shares the platforms() spec resolver with the CI lane selector.
+ shutil.copy2(real / "ci" / "list_os_marked_tests.py", scripts / "ci")
return root
@@ -565,3 +568,26 @@ def test_scratch_root_is_per_user(tmp_path: Path, monkeypatch) -> None:
assert mine != theirs
assert mine.is_dir() and theirs.is_dir()
assert mine.parent == tmp_path and theirs.parent == tmp_path
+
+
+def test_off_host_note_names_platforms_specs_that_exclude_this_host(tmp_path: Path) -> None:
+ """A green local run must say which platforms() tests were skipped and where
+ they run; specs are resolved (posix is not off-host on Linux or macOS)."""
+ probe_dir = _make_probe_dir(tmp_path)
+ (probe_dir / "test_gated.py").write_text(
+ "import pytest\n\n"
+ "@pytest.mark.platforms('not linux')\ndef test_elsewhere():\n assert True\n\n"
+ "@pytest.mark.platforms('posix')\ndef test_posix():\n assert True\n\n"
+ "@pytest.mark.platforms('windows')\ndef test_windows():\n assert True\n",
+ encoding="utf-8",
+ )
+ proc = _run_runner(probe_dir)
+ notes = [line for line in proc.stdout.splitlines() if "SKIPPED on this host" in line]
+ host = {"linux": "linux", "darwin": "macos", "win32": "windows"}[sys.platform]
+ off_host = {"windows"} - {host}
+ if host == "linux":
+ off_host.add("not linux")
+ if host == "windows":
+ off_host.add("posix")
+ assert {n.split("platforms(")[1].split(")")[0].strip("'") for n in notes} == off_host, proc.stdout
+ assert all("they run on the" in n for n in notes), proc.stdout
diff --git a/tests/test_windows_subprocess_no_window_flags.py b/tests/test_windows_subprocess_no_window_flags.py
index 96920bedb93..4579735dc7d 100644
--- a/tests/test_windows_subprocess_no_window_flags.py
+++ b/tests/test_windows_subprocess_no_window_flags.py
@@ -346,6 +346,7 @@ def test_env_probe_run_hides_console_window(monkeypatch):
assert kwargs["stdin"] == subprocess.DEVNULL
def test_suppress_platform_ver_console_stubs_syscmd_ver(monkeypatch):
"""``_syscmd_ver`` is replaced by an in-process echo stub so win32_ver()
takes its ValueError fallback instead of shelling out to `cmd /c ver`.