blob: 9ee23b95bd7db2042b8d39ecb0a11e4ebece2b0a [file] [edit]
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Host test runner detection, case-list parsing, and `--test-filter` translation."""
import abc
from collections.abc import Sequence
import dataclasses
import fnmatch
import mmap
import os
import pathlib
import re
import shlex
import zipfile
import test_list_file
MOBLY_TEST_OUTPUT_TEMPLATE = (
'fx test --e2e {test_name} --test-filter "{test_case}"'
)
DEFAULT_TEST_OUTPUT_TEMPLATE = 'fx test {test_name} --test-filter "{test_case}"'
_MOBLY_CLASS_HEADER_REGEX = re.compile(
r"^==========> (?P<class_name>.*) <==========$"
)
_BAZEL_RUNTIME_DIR_CD_REGEX = re.compile(
r'^cd\s+--\s+"?\$\(dirname\s+"\$\{BASH_SOURCE\[0\]\}"\)/([^"\n]+)"?$'
)
_GO_TEST_CASE_REGEX = re.compile(r"^(?:Test|Benchmark|Example|Fuzz)\S*$")
# Match closed fnmatch [...] character classes (an initial ] after [ or [! is literal,
# so [] and [!] alone are unclosed literals rather than character classes).
_FNMATCH_CHAR_CLASS_REGEX = re.compile(
r"\[(?:!?\][^\]]*|![^\]]+|[^!\]][^\]]*)\]"
)
_UNITTEST_MAIN_CALL_REGEX = re.compile(r"\bunittest\.main\b")
_BAZEL_STAGE2_BOOTSTRAP_REGEX = re.compile(
r'^\s*_?STAGE2_BOOTSTRAP\s*=\s*"([^"\n]+)"', re.MULTILINE
)
_BAZEL_MAIN_PATH_REGEX = re.compile(
r'^\s*MAIN_PATH\s*=\s*"([^"\n]+)"', re.MULTILINE
)
_BAZEL_MAIN_CALLABLE_REGEX = re.compile(
r"_main_callable[^=\n]*=\s*unittest\.main\b"
)
# Keep individual argv entries well below Linux MAX_ARG_STRLEN (131072 bytes).
_MAX_GTEST_FILTER_ARG_LENGTH = 65536
_MAX_WRAPPER_SCRIPT_BYTES = 65536
_ELF_GTEST_MARKER_REGEX = re.compile(
rb"(?P<gunit>gunit_filter|InitGoogleUnit)"
rb"|gtest_filter|InitGoogleTest|MakeAndRegisterTestInfo|_ZN6zxtest6Runner"
)
class NoMatchingCasesError(Exception):
"""Raised when `--test-filter` matches zero enumerated test cases."""
class UnsupportedFilterError(Exception):
"""Raised when a host test runner does not support `--test-filter`."""
def _read_bounded_text(path: pathlib.Path) -> str | None:
"""Read UTF-8 text from a small file, returning None if unreadable or oversized."""
try:
if (
not path.is_file()
or path.stat().st_size > _MAX_WRAPPER_SCRIPT_BYTES
):
return None
return path.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
def _split_shell_line(line: str) -> Sequence[str]:
try:
return tuple(shlex.split(line))
except ValueError:
return tuple(line.split())
def _resolve_wrapper_path(
target: str,
entry_path: pathlib.Path,
out_dir: str,
runtime_dir_rel: str | None,
) -> pathlib.Path:
if os.path.isabs(target):
return pathlib.Path(target)
if runtime_dir_rel is not None:
base_dir = entry_path.parent / runtime_dir_rel
else:
base_dir = pathlib.Path(out_dir)
return base_dir / target
def _extract_bazel_runtime_dir(lines: Sequence[str]) -> str | None:
for line in lines:
if (cd_match := _BAZEL_RUNTIME_DIR_CD_REGEX.match(line)) is not None:
return cd_match.group(1)
return None
def _extract_list_tests_target(lines: Sequence[str]) -> str | None:
for line in lines:
if "--list_tests" not in line:
continue
tokens = _split_shell_line(line)
for idx, tok in enumerate(tokens):
if tok == "--list_tests" and idx + 1 < len(tokens):
return tokens[idx + 1]
if tok.startswith("--list_tests="):
return tok.partition("=")[2]
return None
def _extract_exec_tokens(lines: Sequence[str]) -> Sequence[str]:
exec_tokens: Sequence[str] = ()
for line in lines:
if line.startswith("exec "):
exec_tokens = _split_shell_line(line)
return exec_tokens
def _strip_exec_env_prefix(tokens: Sequence[str]) -> Sequence[str]:
"""Strip leading `exec`, repeated `env` tokens, and `KEY=VALUE` assignments."""
idx = 1
while idx < len(tokens) and tokens[idx] == "env":
idx += 1
while (
idx < len(tokens)
and "=" in tokens[idx]
and not tokens[idx].startswith("-")
):
idx += 1
return tokens[idx:]
def _pyz_uses_unittest_main(pyz_path: pathlib.Path) -> bool:
try:
with zipfile.ZipFile(pyz_path) as zf:
main_py = zf.read("__main__.py").decode("utf-8", errors="replace")
except (OSError, zipfile.BadZipFile, KeyError):
return False
return _UNITTEST_MAIN_CALL_REGEX.search(main_py) is not None
def _bazel_launcher_uses_unittest_main(launcher_path: pathlib.Path) -> bool:
launcher_text = _read_bounded_text(launcher_path)
if launcher_text is None:
return False
if (
stage2_match := _BAZEL_STAGE2_BOOTSTRAP_REGEX.search(launcher_text)
) is not None:
runfiles_dir = pathlib.Path(f"{launcher_path}.runfiles")
stage2_text = _read_bounded_text(runfiles_dir / stage2_match.group(1))
if stage2_text is None:
return False
main_match = _BAZEL_MAIN_PATH_REGEX.search(stage2_text)
if main_match is None:
return False
callable_text = _read_bounded_text(runfiles_dir / main_match.group(1))
if callable_text is None:
return False
return _BAZEL_MAIN_CALLABLE_REGEX.search(callable_text) is not None
if _BAZEL_MAIN_CALLABLE_REGEX.search(launcher_text) is not None:
return True
return (
launcher_path.suffix == ".py"
and _UNITTEST_MAIN_CALL_REGEX.search(launcher_text) is not None
)
def _python_wrapper_uses_unittest_main(
entry_path: pathlib.Path, out_dir: str
) -> bool:
"""Return True if a Python host test wrapper invokes `unittest.main`.
Missing files return True so unbuilt `python_host_test` targets under
`--no-build` still attempt enumeration and fail with `TestCouldNotRun`
rather than being misreported as `TestFilterUnsupported`.
"""
if not entry_path.is_file():
return True
script_text = _read_bounded_text(entry_path)
if script_text is None:
return False
lines = tuple(raw.strip() for raw in script_text.splitlines())
list_tests_target = _extract_list_tests_target(lines)
if not list_tests_target:
return False
target_path = _resolve_wrapper_path(
list_tests_target,
entry_path,
out_dir,
_extract_bazel_runtime_dir(lines),
)
if target_path.suffix == ".pyz":
return _pyz_uses_unittest_main(target_path)
return _bazel_launcher_uses_unittest_main(target_path)
def _pattern_matches_case(pattern: str, case_name: str) -> bool:
"""Match a single filter pattern against a test case name.
Patterns containing glob wildcards (`*`, `?`, `[`) use `fnmatchcase`
against the full case name, and also against the unqualified leaf test name
(after `.` or `::`) when `pattern` does not specify a suite/module separator.
Plain strings match as substrings (which includes exact matches).
"""
if any(ch in pattern for ch in "*?["):
if fnmatch.fnmatchcase(case_name, pattern):
return True
if "." not in pattern and "::" not in pattern and "/" not in pattern:
leaf_name = case_name.rsplit(".", 1)[-1].rsplit("::", 1)[-1]
return fnmatch.fnmatchcase(leaf_name, pattern)
return False
return pattern in case_name
def _filter_test_cases(
all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
"""Filter enumerated test case names using positive and `-` negative patterns."""
includes = tuple(f for f in filters if not f.startswith("-"))
excludes = tuple(f[1:] for f in filters if f.startswith("-") and len(f) > 1)
return tuple(
case
for case in all_cases
if (
not includes
or any(_pattern_matches_case(pat, case) for pat in includes)
)
and not any(_pattern_matches_case(pat, case) for pat in excludes)
)
def _require_matched_cases(
all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
matched_cases = _filter_test_cases(all_cases, filters)
if not matched_cases:
raise NoMatchingCasesError(
f"No test cases matched filters: {list(filters)}"
)
return matched_cases
def _parse_mobly_list_output(stdout: str) -> Sequence[str]:
clean_lines: list[str] = []
current_class: str | None = None
for raw_line in stdout.splitlines():
line = raw_line.strip()
if not line:
continue
if (header := _MOBLY_CLASS_HEADER_REGEX.match(line)) is not None:
current_class = header.group("class_name")
continue
if current_class:
clean_lines.append(line)
return tuple(clean_lines)
def _parse_gtest_list_output(
stdout: str, *, include_disabled: bool
) -> Sequence[str]:
"""Extract `Suite.Case` names from GTest, gunit, or zxtest list stdout."""
cases: list[str] = []
current_suite: str | None = None
for raw_line in stdout.splitlines():
line = raw_line.split("#", 1)[0].rstrip()
if not line:
continue
if not line[0].isspace():
header = line.strip()
current_suite = (
None
if (" " in header or "\t" in header)
else header.rstrip(".")
)
continue
if current_suite is None:
continue
case_part = line.strip().lstrip(".")
if not case_part or " " in case_part or "\t" in case_part:
continue
if not include_disabled and (
current_suite.startswith("DISABLED_")
or "/DISABLED_" in current_suite
or case_part.startswith("DISABLED_")
):
continue
cases.append(f"{current_suite}.{case_part}")
return tuple(cases)
def _glob_segment_to_go_regex(segment: str) -> str:
"""Convert a single `/` segment containing glob wildcards to an anchored RE2 regex."""
parts: list[str] = ["^"]
idx = 0
length = len(segment)
while idx < length:
ch = segment[idx]
if ch == "*":
parts.append(".*")
elif ch == "?":
parts.append(".")
elif ch == "[":
end = idx + 1
if end < length and segment[end] == "!":
end += 1
if end < length and segment[end] == "]":
end += 1
while end < length and segment[end] != "]":
end += 1
if end < length:
body = segment[idx + 1 : end].replace("\\", "\\\\")
if body.startswith("!"):
body = "^" + body[1:]
elif body.startswith("^"):
body = "\\" + body
parts.append(f"[{body}]")
idx = end
else:
parts.append(r"\[")
else:
parts.append(re.escape(ch))
idx += 1
parts.append("$")
return "".join(parts)
def _filter_to_go_regexp(pattern: str) -> str:
"""Translate a `--test-filter` pattern to Go's `-test.run` / `-test.skip` syntax."""
segments = tuple(
_glob_segment_to_go_regex(seg)
if any(ch in seg for ch in "*?[")
else re.escape(seg)
for seg in pattern.split("/")
)
return "/".join(segments)
def _build_go_filter_args(
all_top_level_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
"""Validate Go top-level matches and construct `-test.run` / `-test.skip` flags."""
includes = tuple(f for f in filters if not f.startswith("-"))
excludes = tuple(f[1:] for f in filters if f.startswith("-") and len(f) > 1)
top_includes = tuple(pat.split("/", 1)[0] for pat in includes)
top_excludes = tuple(pat for pat in excludes if "/" not in pat)
matching_top_level = tuple(
case
for case in all_top_level_cases
if (
not top_includes
or any(_pattern_matches_case(pat, case) for pat in top_includes)
)
and not any(_pattern_matches_case(pat, case) for pat in top_excludes)
)
if not matching_top_level:
raise NoMatchingCasesError(
f"No test cases matched filters: {list(filters)}"
)
go_args: list[str] = []
# Go's testing.splitRegexp (src/testing/match.go) gives '|' lower precedence than
# '/' at depth 0, building an alternationMatch of per-level simpleMatch slices.
if includes:
go_args.extend(
("-test.run", "|".join(_filter_to_go_regexp(p) for p in includes))
)
if excludes:
go_args.extend(
("-test.skip", "|".join(_filter_to_go_regexp(p) for p in excludes))
)
return tuple(go_args)
def _expand_gtest_fallback_pattern(
pat: str, *, is_exclude: bool
) -> Sequence[str]:
"""Translate a single filter pattern into GoogleTest/gunit filter globs.
GoogleTest splits filters on `-` and `:` (with no escape syntax), supports
only `*` and `?` wildcards (treating `[...]` literally), and matches against
full `Suite.Case` names from index 0:
- Plain substrings wrap as `*<pat>*` (with `:` and `-` replaced by `?` on
positive includes, and dropped on excludes to avoid over-excluding).
- Unqualified leaf globs expand to both `<pat>` and `*.<pat>`.
- Closed `[...]` character classes and `:`/`-` delimiters are approximated
with `?` for positive includes (`is_exclude=False`, a safe superset),
whereas `is_exclude=True` returns `()` rather than widening exclusions.
"""
if any(ch in pat for ch in "*?["):
if is_exclude:
if (
_FNMATCH_CHAR_CLASS_REGEX.search(pat) is not None
or ":" in pat
or "-" in pat
):
return ()
gtest_glob = pat
else:
gtest_glob = (
_FNMATCH_CHAR_CLASS_REGEX.sub("?", pat)
.replace(":", "?")
.replace("-", "?")
)
if (
"." not in pat
and "::" not in pat
and "/" not in pat
and not gtest_glob.startswith("*")
):
return (gtest_glob, f"*.{gtest_glob}")
return (gtest_glob,)
if is_exclude:
if ":" in pat or "-" in pat:
return ()
return (f"*{pat}*",)
safe_pat = pat.replace(":", "?").replace("-", "?")
return (f"*{safe_pat}*",)
def _build_gtest_negative_fallback(
all_cases: Sequence[str],
matched_set: frozenset[str],
includes: Sequence[str],
pos_expr: str,
exclude_pats: Sequence[str],
) -> str:
if not exclude_pats:
return ""
# `includes` contains GoogleTest globs, which treat `[` literally unlike fnmatch.
fnmatch_includes = tuple(inc.replace("[", "[[]") for inc in includes)
excluded_exact = ":".join(
c
for c in all_cases
if c not in matched_set
and (
not fnmatch_includes
or any(fnmatch.fnmatchcase(c, inc) for inc in fnmatch_includes)
)
and any(_pattern_matches_case(p, c) for p in exclude_pats)
)
if not excluded_exact:
return ""
if (
len(pos_expr or "*") + 1 + len(excluded_exact)
<= _MAX_GTEST_FILTER_ARG_LENGTH
):
return excluded_exact
return ":".join(
expanded
for pat in exclude_pats
for expanded in _expand_gtest_fallback_pattern(pat, is_exclude=True)
)
def _build_gtest_filter_arg(
all_cases: Sequence[str],
matched_cases: Sequence[str],
filters: Sequence[str],
*,
flag_prefix: str,
) -> str:
"""Build a `--gtest_filter=...` or `--gunit_filter=...` arg below MAX_ARG_STRLEN."""
exact_joined = ":".join(matched_cases)
if len(exact_joined) <= _MAX_GTEST_FILTER_ARG_LENGTH:
return f"--{flag_prefix}_filter={exact_joined}"
matched_set = frozenset(matched_cases)
complement_joined = ":".join(c for c in all_cases if c not in matched_set)
if not complement_joined:
return f"--{flag_prefix}_filter=*"
if len(complement_joined) + 2 <= _MAX_GTEST_FILTER_ARG_LENGTH:
return f"--{flag_prefix}_filter=*-{complement_joined}"
includes = tuple(
expanded
for f in filters
if not f.startswith("-")
for expanded in _expand_gtest_fallback_pattern(f, is_exclude=False)
)
pos_expr = ":".join(includes)
exclude_pats = tuple(
f[1:] for f in filters if f.startswith("-") and len(f) > 1
)
neg_expr = _build_gtest_negative_fallback(
all_cases, matched_set, includes, pos_expr, exclude_pats
)
filter_expr = f"{pos_expr}-{neg_expr}" if neg_expr else (pos_expr or "*")
return f"--{flag_prefix}_filter={filter_expr}"
class HostTestRunner(abc.ABC):
"""Strategy encapsulating CLI enumeration and filtering for a host test runner."""
is_mobly: bool = False
def output_template(self) -> str:
return DEFAULT_TEST_OUTPUT_TEMPLATE
def disabled_test_args(self) -> Sequence[str]:
return ()
@abc.abstractmethod
def enumerate_args(self, *, include_disabled: bool) -> Sequence[str]:
"""Return CLI arguments to list test cases for this runner."""
@abc.abstractmethod
def parse_list_output(
self, stdout: str, *, include_disabled: bool
) -> Sequence[str]:
"""Parse raw enumeration stdout into clean case names."""
@abc.abstractmethod
def build_filter_args(
self, all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
"""Translate `--test-filter` patterns into runner-specific CLI arguments."""
@dataclasses.dataclass(frozen=True)
class MoblyRunner(HostTestRunner):
is_mobly: bool = dataclasses.field(default=True, init=False, repr=False)
def output_template(self) -> str:
return MOBLY_TEST_OUTPUT_TEMPLATE
def enumerate_args(self, *, include_disabled: bool) -> Sequence[str]:
return ("--list_mobly_tests",)
def parse_list_output(
self, stdout: str, *, include_disabled: bool
) -> Sequence[str]:
return _parse_mobly_list_output(stdout)
def build_filter_args(
self, all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
return ("--test_cases", *_require_matched_cases(all_cases, filters))
@dataclasses.dataclass(frozen=True)
class PythonUnittestRunner(HostTestRunner):
def enumerate_args(self, *, include_disabled: bool) -> Sequence[str]:
return ("--list_host_python_unittests",)
def parse_list_output(
self, stdout: str, *, include_disabled: bool
) -> Sequence[str]:
return tuple(
stripped
for line in stdout.splitlines()
if (stripped := line.strip())
)
def build_filter_args(
self, all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
if not all_cases:
raise UnsupportedFilterError(
"Test defines no unittest cases and does not support --test-filter; "
"pass runner-specific arguments after '--' instead."
)
return _require_matched_cases(all_cases, filters)
@dataclasses.dataclass(frozen=True)
class RustRunner(HostTestRunner):
def disabled_test_args(self) -> Sequence[str]:
return ("--include-ignored",)
def enumerate_args(self, *, include_disabled: bool) -> Sequence[str]:
return ("--list", "--format=terse")
def parse_list_output(
self, stdout: str, *, include_disabled: bool
) -> Sequence[str]:
return tuple(
stripped.removesuffix(": test")
for line in stdout.splitlines()
if (stripped := line.strip()).endswith(": test")
)
def build_filter_args(
self, all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
return ("--exact", *_require_matched_cases(all_cases, filters))
@dataclasses.dataclass(frozen=True)
class GoRunner(HostTestRunner):
def enumerate_args(self, *, include_disabled: bool) -> Sequence[str]:
return ("-test.list", ".")
def parse_list_output(
self, stdout: str, *, include_disabled: bool
) -> Sequence[str]:
return tuple(
stripped
for line in stdout.splitlines()
if _GO_TEST_CASE_REGEX.match(stripped := line.strip())
)
def build_filter_args(
self, all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
return _build_go_filter_args(all_cases, filters)
@dataclasses.dataclass(frozen=True)
class GTestRunner(HostTestRunner):
flag_prefix: str
def disabled_test_args(self) -> Sequence[str]:
return (f"--{self.flag_prefix}_also_run_disabled_tests",)
def enumerate_args(self, *, include_disabled: bool) -> Sequence[str]:
if include_disabled:
return (
f"--{self.flag_prefix}_list_tests",
f"--{self.flag_prefix}_also_run_disabled_tests",
)
return (f"--{self.flag_prefix}_list_tests",)
def parse_list_output(
self, stdout: str, *, include_disabled: bool
) -> Sequence[str]:
return _parse_gtest_list_output(
stdout, include_disabled=include_disabled
)
def build_filter_args(
self, all_cases: Sequence[str], filters: Sequence[str]
) -> Sequence[str]:
matched_cases = _require_matched_cases(all_cases, filters)
return (
_build_gtest_filter_arg(
all_cases,
matched_cases,
filters,
flag_prefix=self.flag_prefix,
),
)
def _detect_elf_gtest_runner(
binary_path: pathlib.Path,
) -> GTestRunner | None:
"""Inspect an ELF executable via mmap for gunit, GTest, or zxtest symbols."""
try:
with binary_path.open("rb") as f:
if f.read(4) != b"\x7fELF":
return None
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
saw_gtest = False
for match in _ELF_GTEST_MARKER_REGEX.finditer(mm):
if match.group("gunit") is not None:
return GTestRunner("gunit")
saw_gtest = True
if saw_gtest:
return GTestRunner("gtest")
except (OSError, ValueError):
return None
return None
# TODO(https://fxbug.dev/589905525): Emit explicit host test runner metadata in
# `tests.json` for Bazel host tests (directly from non-C++ rules and via a
# transitive C++ framework aspect on `host_test.binary`) and prefer it here.
# ELF/wrapper inspection is also brittle, but remains a cheap on-demand fallback
# for GN host tests where transitive C++ metadata requires per-test
# `generated_file` walks and sidecar files.
def detect_host_test_runner(
test: test_list_file.Test, out_dir: str
) -> HostTestRunner | None:
"""Identify the host/E2E test framework backing a path-based test."""
if test.info.execution is not None or not test.build.test.path:
return None
raw_path = test.build.test.path
entry_path = (
pathlib.Path(raw_path)
if os.path.isabs(raw_path)
else pathlib.Path(out_dir) / raw_path
)
list_cases_arg = test.build.test.list_cases_argument
if list_cases_arg == "list_mobly_tests":
return MoblyRunner()
if list_cases_arg == "list_host_python_unittests":
return (
PythonUnittestRunner()
if _python_wrapper_uses_unittest_main(entry_path, out_dir)
else None
)
if not entry_path.is_file():
return None
try:
with entry_path.open("rb") as f:
prefix = f.read(4)
except OSError:
return None
if prefix == b"\x7fELF":
return _detect_elf_gtest_runner(entry_path)
if not prefix.startswith(b"#!"):
return None
script_text = _read_bounded_text(entry_path)
if script_text is None:
return None
lines = tuple(raw.strip() for raw in script_text.splitlines())
exec_tokens = _extract_exec_tokens(lines)
if len(exec_tokens) < 2:
return None
command_tokens = _strip_exec_env_prefix(exec_tokens)
if not command_tokens:
return None
tool_token = command_tokens[0]
remaining_tokens = command_tokens[1:]
tool_basename = os.path.basename(tool_token)
if tool_basename == "rust_test_parser":
return RustRunner()
if (
tool_basename == "go_test_parser"
or "-test.v" in remaining_tokens
or "-test.timeout" in remaining_tokens
):
return GoRunner()
if tool_basename == "mobly_test_parser":
return MoblyRunner()
candidate_binary = _resolve_wrapper_path(
tool_token,
entry_path,
out_dir,
_extract_bazel_runtime_dir(lines),
)
if candidate_binary.is_file():
return _detect_elf_gtest_runner(candidate_binary)
return None