From 25a8f9e916663d5b80b5715eaef5c06b79e97275 Mon Sep 17 00:00:00 2001 From: syfyra <258908070+syfyra@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:00:09 +0100 Subject: [PATCH] scripts: tests_for.py names the tests that exercise a change (TESTS-FOR-CHANGE) A reviewer runs "the pull request's own tests" and a contributor the tests of what they changed, but which ones those are was guesswork: tests are found by their name, and a helper that many tools import has no test of its name. scripts/tests_for.py reads the repository and answers for the paths named, or for the files the current branch changes. For each file it lists the tests under tests/ that import it or name its path, the ones that reach it through the modules they import (with the module they go through), the ones that read its folder, the documentation tests for a Markdown file and the tests beside a fixture that quote its name. For runtime/ it reads runtime/CMakeLists.txt and lists the ctest tests whose program is built from the file: as a source, through a header a source includes, or through a library the program links, with foreach loops and set() lists followed. It then prints the commands, split the way CI splits the tests: python -I, pytest, the semantic runner, node --test and ctest -R. It runs no test. Paths are matched in the case they have on disk, so the answer is the same on Windows and Linux. Co-Authored-By: Claude Fable 5.2 --- CONTRIBUTING.md | 4 + scripts/tests_for.py | 489 +++++++++++++++++++++++++ tests/fixtures/tests_for_checkout.json | 64 ++++ tests/test_tests_for.py | 355 ++++++++++++++++++ 4 files changed, 912 insertions(+) create mode 100644 scripts/tests_for.py create mode 100644 tests/fixtures/tests_for_checkout.json create mode 100644 tests/test_tests_for.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1cd0b69083..67418450ce 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,6 +55,10 @@ number and links nowhere now, including the two this page used to send you to: # files with no `__main__` block or an `import pytest` (they need the packages in `tests/requirements.txt`) run with `python -m pytest tests/test_.py` instead, as [AGENTS.md](AGENTS.md) describes; under `python -I` they fail to import or run nothing. +- Which tests exercise what you changed: `python -I scripts/tests_for.py` for your branch, or with files or folders + as arguments. It lists the tests that import or name each file, the ctest tests whose programs are built from + it, and the commands that run them; it runs nothing itself. Run those while you iterate and the whole suites once + before the pull request. - Runtime tests: `cmake -S runtime -B runtime/build`, `cmake --build runtime/build --config RelWithDebInfo`, then `ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure`. The CPU tests that need no game data are configured on Windows; Linux and macOS configure the portable subset (`gta6rt` and the shims are Windows-only). Tests that need the retail package read `LEONIDA_GAME_DIR` (and `LEONIDA_MOVIE` for the Bink diff --git a/scripts/tests_for.py b/scripts/tests_for.py new file mode 100644 index 0000000000..9980c237fb --- /dev/null +++ b/scripts/tests_for.py @@ -0,0 +1,489 @@ +"""Which tests exercise the files you changed, and the commands that run them. + + python -I scripts/tests_for.py [PATH ...] [--base REF] [--head REF] [--all] [--json] + +A reviewer runs "the pull request's own tests" and a contributor the tests of what they changed, but tests are +found by name here, and a helper that many tools import has no test of its name. This reads the repository and +answers for each PATH (files or folders), or with none for the files your branch changes: what `--head` (default +HEAD) changes against its merge base with `--base` (default origin/main) and, for HEAD, what is modified or +untracked in the working tree. + +For every such file it lists the tests under `tests/` that reach it, each for one reason: + +- `names it`: the test imports the file as a module or names its path (`"tools/x.py"`, `ROOT, "viewer", + "page.html"`, `ROOT / "viewer" / "page.html"`); +- `imports`: a module the test imports reaches the file through imports, with the module it goes through; +- `folder`: the test names the folder the file is in and neither imports from it nor names a file in it, so + it probably reads what is there (`ROOT / "viewer"`, then every `*.html`); for a Markdown file these are + `tests/test_docs_*.py` and `tests/test_i18n_index.py`, which CI runs for every documentation change; +- `fixture`: the file is under a `fixtures` folder of the tests and a test beside that folder quotes its file + name or its stem (`"ps_case"` for `tests/semantic/fixtures/ps_case.asm`); +- `ctest`: under `runtime/`, the ctest tests whose program is built from the file according to + `runtime/CMakeLists.txt`: as a source, through a header that a source includes, or through a library the + program links. `foreach` loops and `set()` lists are followed; a target that a function or a generator + expression builds is not, so take this list as the least there is to run. + +Then the commands, split the way CI splits the tests: `python -I` for a standalone file, pytest for a file that +imports pytest or has no `__main__` block, the semantic runner for `tests/semantic`, `node --test` and +`ctest -R`. Tests that `names it` and changed tests always get their commands; the wider reasons do when there +are at most 20 of them or with `--all`. + +It reads files and asks git for the changed ones; it runs no test and writes nothing. What a test reaches is read +from its text (imports and quoted paths), so a path that is built at run time is not seen. Exit 0, or 2 on a usage +or git error. Standard library only; no game files. +""" +import argparse +import json +import os +import re +import subprocess +import sys +from collections import defaultdict, deque + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +MODULE_DIRS = ("tools", "scripts", "viewer", "tests", "tests/semantic", "") +IMPORT = re.compile(r"^[ \t]*(?:import[ \t]+([\w.]+(?:[ \t]*,[ \t]*[\w.]+)*)|from[ \t]+([\w.]+)[ \t]+import\b)", re.M) +LITERAL = re.compile(r'''"([^"\\\n]*)"|'([^'\\\n]*)\'''') +# A folder named alone ("docs") is a path of this repository only next to its root: ROOT, REPO_ROOT, __dirname. +# Upper case only: `root / "tools"` is usually a temporary checkout, and "report" is no repository. +PATH_CONTEXT = re.compile(r"\b(?:[A-Z]+_)?(?:ROOT|REPO)(?:_[A-Z]+)?\b|__dirname|__file__") +PYTEST_MARKERS = re.compile(r"^import pytest|^ *HAVE_NUMPY =", re.M) # PYTEST_FILE_MARKERS of ci.yml +SOURCE = re.compile(r"\.(?:c|cc|cpp|cxx|h|hpp|inc|asm|rc|def)$", re.I) +INCLUDE = re.compile(r'^[ \t]*#[ \t]*include[ \t]*"([^"\n]+)"', re.M) +COMMAND = re.compile(r"(?m)^[ \t]*([A-Za-z_]\w*)[ \t]*\(") +WIDE_LIMIT = 20 +REASONS = ("names it", "imports", "folder", "fixture") + + +class GitError(Exception): + pass + + +def read(path): + try: + with open(path, encoding="utf-8", errors="replace") as f: + return f.read() + except OSError: + return "" + + +def listing(root, folder): + try: + return sorted(os.listdir(os.path.join(root, folder))) + except OSError: + return [] + + +class Repository: + """The modules and tests of a checkout, and what each one names.""" + + def __init__(self, root=ROOT): + self.root = root + entries = [name for name in listing(root, "") if name != ".git"] + self.top = {name for name in entries if os.path.isdir(os.path.join(root, name))} + # Every path this looks for starts with a top-level folder or is a file beside them, so a line that + # holds none of those names is not looked at twice. + self.hint = re.compile("|".join(re.escape(name) for name in sorted(entries, key=len, reverse=True) + if name in self.top or "." in name) or r"(?!)") + self.modules = defaultdict(list) # module name -> its files, in MODULE_DIRS order + for folder in MODULE_DIRS: + for name in listing(root, folder): + if name.endswith(".py"): + self.modules[name[:-3]].append(f"{folder}/{name}" if folder else name) + self.module_files = sorted({path for paths in self.modules.values() for path in paths}) + self.tests =[f"tests/{name}" for name in listing(root, "tests") + if re.fullmatch(r"test_.*\.(?:py|cjs|mjs)", name)] + for base, _, names in os.walk(os.path.join(root, "tests", "semantic")): + rel = os.path.relpath(base, root).replace(os.sep, "/") + self.tests += [f"{rel}/{name}" for name in sorted(names) if re.fullmatch(r"test.*\.py", name)] + self.tests.sort() + self.names, self.folders, self.listings = {}, {}, {} + for path in sorted({*self.module_files, *self.tests}): + self.names[path], self.folders[path] = self.references(path, read(os.path.join(root, path))) + + def kind(self, path): + """`dir`, `file` or None for a repository path spelled exactly as on disk. Windows and macOS would open + `Docs/World.md` too, and the answer must not depend on where the tool runs.""" + folder = "" + for part in path.split("/"): + if folder not in self.listings: + self.listings[folder] = set(listing(self.root, folder)) + if part not in self.listings[folder]: + return None + folder = f"{folder}/{part}" if folder else part + return "dir" if os.path.isdir(os.path.join(self.root, path)) else "file" + + def module(self, name, importer): + """The file `import name` loads in `importer`: the one beside it, as Python looks there first, else the + first in MODULE_DIRS order.""" + found = self.modules.get(name, ()) + beside = f"{os.path.dirname(importer)}/{name}.py".lstrip("/") + return beside if beside in found else found[0] if found else None + + def references(self, path, text): + """(files, folders) of the repository that `text` names: imported modules, quoted paths and paths joined + from quoted segments. A folder on a `sys.path` line is where modules come from, not something read.""" + files, folders = set(), set() + + def add(found, kind, line): + if kind == "file": + files.add(found) + elif "sys.path" not in line: + folders.add(found) + + if path.endswith(".py"): + for m in IMPORT.finditer(text): + for name in re.split(r"[ \t]*,[ \t]*", m.group(1) or m.group(2)): + module = self.module(name, path) + if module: + files.add(module) + for line in text.splitlines(): + if not self.hint.search(line): + continue + run, end = [], None + for m in [*LITERAL.finditer(line), None]: + segment = (m.group(1) if m.group(1) is not None else m.group(2)).strip("/") if m else None + joined = m and end is not None and re.fullmatch(r"\s*[,/]\s*", line[end:m.start()]) + if run and not joined: + self.resolve(run, line, add) + run = [] + if m and segment: + run.append(segment) + if m: + end = m.end() + return files, folders + + def resolve(self, run, line, add): + """Report the repository paths in a run of quoted segments that are joined by `,` or `/`: the longest + join that exists, starting at each segment in turn. A path starts with a top-level folder, or is a file + beside it (`make_game.py`). A top-level folder named alone counts only on a line that names the + repository root, since `os.path.join(tmp, "game")` is somebody's temporary folder.""" + i = 0 + while i < len(run): + for j in range(len(run) - 1, i - 1, -1): + candidate = os.path.normpath("/".join(run[i:j + 1])).replace(os.sep, "/") + kind = None if candidate.startswith("..") or os.path.isabs(candidate) else self.kind(candidate) + if kind is None: + continue + if "/" in candidate: + known = True + elif kind == "dir": + known = PATH_CONTEXT.search(line) is not None + else: + known = "." in candidate + if known: + add(candidate, kind, line) + i = j + break + i += 1 + + def reached(self, test): + """{file: the module it is reached through, or None when the test names it} for one test.""" + seen = {name: None for name in self.names[test]} + todo = deque((name, name) for name in sorted(self.names[test])) + while todo: + name, through = todo.popleft() + for inner in sorted(self.names.get(name, ())): + if inner not in seen and inner != test: + seen[inner] = through + todo.append((inner, through)) + return seen + + +def runner_of(root, test): + """python, pytest, semantic or node: how CI runs a test file.""" + if test.endswith((".cjs", ".mjs")): + return "node" + if test.startswith("tests/semantic/"): + return "semantic" + text = read(os.path.join(root, test)) + return "pytest" if PYTEST_MARKERS.search(text) or "__main__" not in text else "python" + + +def cmake_commands(text): + """[(command, [argument])] of a CMake file, comments dropped.""" + text = re.sub(r"(?m)(^|\s)#.*$", r"\1", text) + found = [] + for m in COMMAND.finditer(text): + depth, i = 1, m.end() + while i < len(text) and depth: + depth += (text[i] == "(") - (text[i] == ")") + i += 1 + found.append((m.group(1).lower(), [a.strip('"') for a in re.findall(r'"[^"]*"|[^\s()"]+', text[m.end():i - 1])])) + return found + + +class Runtime: + """What runtime/CMakeLists.txt builds: which program each source goes into and which ctest runs it.""" + + def __init__(self, root=ROOT): + self.root = root + self.sources, self.links, self.tests = defaultdict(set), defaultdict(set), [] + self.variables = {"CMAKE_CURRENT_SOURCE_DIR": ["."], "CMAKE_SOURCE_DIR": ["."]} + self.interpret(cmake_commands(read(os.path.join(root, "runtime", "CMakeLists.txt")))) + self.includers = defaultdict(set) + for base, _, names in os.walk(os.path.join(root, "runtime")): + for name in names: + if SOURCE.search(name): + path = os.path.relpath(os.path.join(base, name), root).replace(os.sep, "/") + for inc in INCLUDE.findall(read(os.path.join(base, name))): + target = self.include(path, inc) + if target: + self.includers[target].add(path) + + def include(self, includer, name): + for folder in (os.path.dirname(includer), "runtime/src", "runtime/shims", "runtime/test", "runtime"): + candidate = os.path.normpath(os.path.join(folder, name)).replace(os.sep, "/") + if os.path.isfile(os.path.join(self.root, candidate)): + return candidate + return None + + def expand(self, args): + out = [] + for arg in args: + whole = re.fullmatch(r"\$\{(\w+)\}", arg) + if whole: + out += self.variables.get(whole.group(1), []) + else: + out.append(re.sub(r"\$\{(\w+)\}", lambda m: (self.variables.get(m.group(1)) or [m.group(0)])[0] + if len(self.variables.get(m.group(1), [])) <= 1 else m.group(0), arg)) + return out + + def interpret(self, commands): + i = 0 + while i < len(commands): + name, args = commands[i] + i += 1 + if name == "foreach" and args: + depth, j = 1, i + while j < len(commands) and depth: + depth += (commands[j][0] == "foreach") - (commands[j][0] == "endforeach") + j += 1 + body, i = commands[i:j - 1], j + items = self.expand(args[1:]) + if items[:2] == ["IN", "ITEMS"]: + items = items[2:] + elif items[:2] == ["IN", "LISTS"]: + items = [value for name_ in items[2:] for value in self.variables.get(name_, [])] + elif items[:1] == ["RANGE"]: + items = [] + saved = self.variables.get(args[0]) + for item in items: + self.variables[args[0]] = [item] + self.interpret(body) + if saved is None: + self.variables.pop(args[0], None) + else: + self.variables[args[0]] = saved + continue + args = self.expand(args) + if name == "set" and args: + self.variables[args[0]] = [a for a in args[1:] if a not in ("PARENT_SCOPE", "CACHE")] + elif name == "list" and len(args) > 2 and args[0] == "APPEND": + self.variables.setdefault(args[1], []).extend(args[2:]) + elif name in ("add_executable", "add_library", "target_sources") and args: + self.sources[args[0]] |= {self.path(a) for a in args[1:] if SOURCE.search(a)} + elif name == "target_link_libraries" and args: + for library in args[1:]: + self.links[library].add(args[0]) + elif name == "add_test" and "NAME" in args and "COMMAND" in args: + command = args[args.index("COMMAND") + 1:] + programs = {re.sub(r"^\$$", r"\1", a) for a in command} + self.tests.append((args[args.index("NAME") + 1], programs, + {self.path(a) for a in command if a.endswith(".py")})) + + def path(self, name): + return os.path.normpath(os.path.join("runtime", name)).replace(os.sep, "/") + + def tests_for(self, path): + """The ctest tests whose program is built from `path`, in CMakeLists order.""" + files, todo = set(), [path] + while todo: + name = todo.pop() + if name not in files: + files.add(name) + todo += self.includers.get(name, ()) + targets, todo = set(), [t for t, sources in self.sources.items() if sources & files] + while todo: + name = todo.pop() + if name not in targets: + targets.add(name) + todo += self.links.get(name, ()) + found = [] + for name, programs, scripts in self.tests: + if (programs & targets or path in scripts) and name not in found and "${" not in name: + found.append(name) + return found + + +def changed_files(root, base, head): + def git(*args): + try: + r = subprocess.run(["git", "-C", root, *args], capture_output=True) + except OSError as e: + raise GitError(f"cannot run git: {e.strerror or e}") from None + if r.returncode != 0: + raise GitError(f"git {' '.join(args)}: {r.stderr.decode('utf-8', 'replace').strip() or r.returncode}") + return [p for p in r.stdout.decode("utf-8", "replace").split("\0") if p] + + files = git("diff", "--name-only", "--no-renames", "-z", f"{base}...{head}") + if head == "HEAD": + files += git("diff", "--name-only", "--no-renames", "-z", "HEAD") + files += git("ls-files", "--others", "--exclude-standard", "-z") + return sorted(set(files)) + + +def expand_targets(root, paths): + """PATH arguments as repository files: a folder stands for the files in it.""" + top, files = os.path.realpath(root), [] + cwd = os.path.realpath(os.getcwd()) + try: + inside = os.path.normcase(os.path.commonpath([top, cwd])) == os.path.normcase(top) + except ValueError: + inside = False + for path in paths: + full = os.path.realpath(os.path.join(cwd if inside else top, path)) + try: + rel = os.path.relpath(full, top) + except ValueError: + rel = os.pardir + if rel == os.pardir or rel.startswith(os.pardir + os.sep): + raise GitError(f"{path} is not inside the repository {top}") + if os.path.isdir(full): + for base, dirs, names in os.walk(full): + dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d != "__pycache__") + files += [os.path.relpath(os.path.join(base, n), top).replace(os.sep, "/") for n in sorted(names)] + else: + files.append(rel.replace(os.sep, "/")) + return sorted(set(files)) + + +def survey(root, files): + """For each file: {"file", "is_test", "tests": [{"test", "reason", "through"}], "ctest": [names]}.""" + repo = Repository(root) + reached = {test: repo.reached(test) for test in repo.tests} + docs = [t for t in repo.tests if re.fullmatch(r"tests/test_(?:docs_.*|i18n_index)\.py", t)] + runtime = None + report = [] + for path in files: + entry = {"file": path, "is_test": path in repo.tests, "tests": [], "ctest": []} + # tests/semantic/fixtures/disasm/x.s belongs to the tests in tests/semantic. + beside = path.split("/fixtures/")[0] if path.startswith("tests/") and "/fixtures/" in path else None + stem, suffix = os.path.splitext(os.path.basename(path)) + quoted = re.compile(rf"""["']{re.escape(stem)}(?:{re.escape(suffix)})?["']""") + for test in repo.tests: + if test == path: + continue + if path in reached[test]: + through = reached[test][path] + entry["tests"].append({"test": test, "reason": "imports" if through else "names it", + "through": through}) + elif (path.endswith(".md") and test in docs) or ( + os.path.dirname(path) in repo.folders[test] + # A folder the test gets modules or named files from is not one it reads as a whole. + and not any(os.path.dirname(f) == os.path.dirname(path) for f in reached[test])): + entry["tests"].append({"test": test, "reason": "folder", "through": None}) + elif os.path.dirname(test) == beside and quoted.search(read(os.path.join(root, test))): + entry["tests"].append({"test": test, "reason": "fixture", "through": None}) + if path.startswith("runtime/"): + runtime = runtime or Runtime(root) + entry["ctest"] = runtime.tests_for(path) + entry["tests"].sort(key=lambda t: (REASONS.index(t["reason"]), t["test"])) + report.append(entry) + return report + + +def commands(root, report, everything): + """The commands that run the tests of a report, and how many wider tests were left out of them.""" + chosen, wide, ctest = [], [], [] + for entry in report: + if entry["is_test"]: + chosen.append(entry["file"]) + chosen += [t["test"] for t in entry["tests"] if t["reason"] == "names it"] + wide += [t["test"] for t in entry["tests"] if t["reason"] != "names it"] + ctest += [name for name in entry["ctest"] if name not in ctest] + chosen = sorted(set(chosen)) + wide = sorted(set(wide) - set(chosen)) + left_out = 0 if everything or len(wide) <= WIDE_LIMIT else len(wide) + tests = chosen if left_out else sorted(set(chosen) | set(wide)) + by = defaultdict(list) + for test in tests: + by[runner_of(root, test)].append(test) + lines = [f"python -I {test}" for test in by["python"]] + if by["pytest"]: + lines.append("python -m pytest " + " ".join(by["pytest"]) + " # needs tests/requirements.txt") + if len(by["semantic"]) > WIDE_LIMIT: + lines.append(f"python -I scripts/run_semantic_tests.py tests/semantic # {len(by['semantic'])} of its files") + else: + lines += [f"python -I scripts/run_semantic_tests.py tests/semantic -p {os.path.basename(test)}" + for test in by["semantic"]] + if by["node"]: + lines.append("node --test " + " ".join(by["node"])) + if len(ctest) > 2 * WIDE_LIMIT: + lines.append(f"ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure # {len(ctest)} of its tests") + elif ctest: + lines.append('ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure -R "^(' + + "|".join(ctest) + ')$"') + return lines, left_out + + +def listed(names, limit=8): + return ", ".join(names[:limit]) + (f" and {len(names) - limit} more" if len(names) > limit else "") + + +def print_report(report, lines, left_out): + for entry in report: + print(entry["file"] + (" (a test)" if entry["is_test"] else "")) + for reason in REASONS: + tests = [t for t in entry["tests"] if t["reason"] == reason] + if not tests: + continue + shown = [t["test"] + (f" (through {t['through']})" if t["through"] else "") for t in tests] + print(f" {reason} ({len(tests)}): {listed(shown)}") + if entry["ctest"]: + print(f" ctest ({len(entry['ctest'])}): {listed(entry['ctest'])}") + if not entry["tests"] and not entry["ctest"] and not entry["is_test"]: + print(" no test names it") + print() + if lines: + print("Run:") + for line in lines: + print(" " + line) + else: + print("Nothing to run was found for these files.") + if left_out: + print(f"{left_out} more test(s) reach these files through imports or folders; --all adds their commands.") + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0]) + ap.add_argument("paths", nargs="*", metavar="PATH", + help="files or folders; with none, the files of --head and of the working tree") + ap.add_argument("--base", default="origin/main", help="the branch to compare with (default origin/main)") + ap.add_argument("--head", default="HEAD", help="your branch, when no PATH is given (default HEAD)") + ap.add_argument("--all", action="store_true", help="commands for every test found, however many") + ap.add_argument("--json", action="store_true", help="one JSON report instead of text") + ap.add_argument("--repo", default=ROOT, help="repository folder (default: the one this script is in)") + args = ap.parse_args(argv) + try: + files = expand_targets(args.repo, args.paths) if args.paths else changed_files(args.repo, args.base, args.head) + except GitError as e: + print(f"tests_for: {e}", file=sys.stderr) + return 2 + report = survey(args.repo, files) + lines, left_out = commands(args.repo, report, args.all) + if args.json: + print(json.dumps({"files": report, "commands": lines, "left_out": left_out}, indent=2)) + elif not files: + print("No changed files: name the files or folders to look up.") + else: + print_report(report, lines, left_out) + return 0 + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tests/fixtures/tests_for_checkout.json b/tests/fixtures/tests_for_checkout.json new file mode 100644 index 0000000000..2fc8d354c5 --- /dev/null +++ b/tests/fixtures/tests_for_checkout.json @@ -0,0 +1,64 @@ +{ + "build_all.py": "import os\nSTAGES = [os.path.join(\"tools\", \"carve.py\")]\n", + "GUIDE.md": "# Readme\n", + "tools/alpha.py": "import helper\nfrom deep import thing\n", + "tools/helper.py": "import json\n", + "tools/deep.py": "import deeper, os\n", + "tools/deeper.py": "", + "tools/carve.py": "", + "tools/lonely.py": "", + "tools/common.py": "", + ".github/workflows/build.yml": "name: CI\n", + "scripts/runner.py": "", + "viewer/page.html": "\n", + "viewer/other.html": "\n", + "viewer/server.py": "", + "docs/topic.md": "# World\n", + "docs/i18n/fr/sample.md": "# Rapide\n", + "game/manifest.json": "{}\n", + "tests/notes.txt": "", + "tests/fixtures/sample.bin": "", + "tests/helpers.py": "import helper\n", + "tests/test_alpha.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.insert(0, os.path.join(ROOT, \"tools\"))\nimport alpha\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_paths.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nTOOL = os.path.join(ROOT, \"tools/carve.py\")\nMAKE = os.path.join(ROOT, \"build_all.py\")\nOTHER = os.path.join(tmp, \"tools/nowhere.py\")\nSELF = os.path.join(ROOT, \"tests/test_paths.py\")\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_argv.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nRUN = [sys.executable, \"-I\", \"scripts/runner.py\", \"--help\"]\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_ci.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nCI = os.path.join(ROOT, \".github\", \"workflows\", \"build.yml\")\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_base.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_uses_test.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nimport test_base\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_tools_common.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.insert(0, os.path.join(ROOT, \"tools\"))\nimport common\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_dynamic.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.insert(0, os.path.join(ROOT, \"tools\"))\nmodule = __import__(name)\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_runtime_dir.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nRT = os.path.join(ROOT, \"runtime\")\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_joined.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPAGE = os.path.join(ROOT, \"viewer\", \"page.html\")\nRUN = [sys.executable, os.path.join(ROOT, \"scripts\", \"runner.py\"), \"--x\"]\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_pathlib.py": "from pathlib import Path\nROOT = Path(__file__).resolve().parents[1]\nPAGE = ROOT / \"viewer\" / \"other.html\"\n", + "tests/test_pytest_marker.py": "import pytest\nimport helper\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_numpy_marker.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nHAVE_NUMPY = False\nimport lonely\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_viewer_pages.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nVIEWER = os.path.join(ROOT, \"viewer\")\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_import_path.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nTOOLS = os.path.join(ROOT, \"tools\")\nsys.path.insert(0, TOOLS)\nimport deeper\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_tmp_folder.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nwork = os.path.join(tmp, \"game\")\nout = os.path.join(base, \"docs\")\nlog(\"tools\", flag); name = \"lonely.py\"\nCASE = \"ps_case\"\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_docs_sample.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_i18n_index.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_through_helper.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nimport helpers\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_fixture_user.py": "import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nDATA = os.path.join(FIXTURES, \"sample.bin\")\nWORD = \"helpers\"\n\nif __name__ == \"__main__\":\n unittest.main()\n", + "tests/test_page.cjs": "const { join } = require('node:path');\nconst html = readFileSync(join(__dirname, '..', 'viewer', 'page.html'), 'utf8');\n", + "tests/semantic/common.py": "import alpha\n", + "tests/semantic/fixtures/ps_case.asm": "", + "tests/semantic/test_one.py": "import common\nCASE = common.load('ps_case')\n", + "tests/semantic/test_two.py": "import unittest\n", + "runtime/CMakeLists.txt": "add_library(core STATIC src/core.cpp) # the library every program links\nset(shim_sources\n shims/net.cpp\n shims/audio.cpp)\nadd_executable(rt src/entry.cpp ${shim_sources})\ntarget_link_libraries(rt PRIVATE core)\nadd_executable(net_test\n test/net_test.cpp\n shims/net.cpp)\nadd_executable(core_test test/core_test.cpp)\ntarget_link_libraries(core_test PRIVATE core)\nforeach(target IN ITEMS loop_a_test loop_b_test)\n add_executable(${target} test/${target}.cpp shims/audio.cpp)\nendforeach()\ntarget_sources(rt PRIVATE \"${CMAKE_CURRENT_SOURCE_DIR}/shims/late.cpp\")\nif(WIN32 AND TARGET net_test)\n add_test(NAME net COMMAND net_test)\n add_test(NAME net_again COMMAND net_test --again)\nendif()\nif(WIN32)\n add_test(NAME core COMMAND core_test)\nelse()\n add_test(NAME core COMMAND core_test --posix) # the same test, declared per platform\nendif()\nadd_test(NAME loop_a COMMAND loop_a_test)\nadd_test(NAME loop_b COMMAND $ --flag)\nadd_test(NAME run_modes COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/check_modes.py $)\nforeach(name one two)\n add_test(NAME rejects_${name} COMMAND rt --${name})\nendforeach()\nadd_executable(part_test extra/part.cpp)\nadd_test(NAME part COMMAND part_test)\n", + "runtime/extra/part.cpp": "#include \"part.h\"\n", + "runtime/extra/part.h": "", + "runtime/src/core.cpp": "#include \"core.h\"\n", + "runtime/src/core.h": "", + "runtime/src/entry.cpp": "#include \"core.h\"\n#include \"../shims/net.h\"\n", + "runtime/shims/net.cpp": "#include \"net.h\"\n", + "runtime/shims/net.h": "#include \"types.h\"\n", + "runtime/shims/types.h": "", + "runtime/shims/audio.cpp": "", + "runtime/shims/late.cpp": "", + "runtime/shims/unused.cpp": "", + "runtime/test/net_test.cpp": "#include \"../shims/net.h\"\n", + "runtime/test/core_test.cpp": "", + "runtime/test/loop_a_test.cpp": "", + "runtime/test/loop_b_test.cpp": "", + "runtime/test/check_modes.py": "" +} diff --git a/tests/test_tests_for.py b/tests/test_tests_for.py new file mode 100644 index 0000000000..363561f9a4 --- /dev/null +++ b/tests/test_tests_for.py @@ -0,0 +1,355 @@ +"""scripts/tests_for.py on a small synthetic checkout, and a few facts about this one (no game data). + + python -I tests/test_tests_for.py + +The synthetic checkout has the layout of this repository: tools/, scripts/, viewer/, docs/, tests/ with a +semantic suite, and a runtime/CMakeLists.txt with programs, a library, loops and ctest entries. +""" +import contextlib +import io +import json +import os +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) + +import tests_for # noqa: E402 + +HEAD = 'import os\nimport sys\nimport unittest\nROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n' +TOOLS = 'sys.path.insert(0, os.path.join(ROOT, "tools"))\n' +MAIN = '\nif __name__ == "__main__":\n unittest.main()\n' + +# The synthetic checkout is data: tests/fixtures/tests_for_checkout.json maps each of its paths to the file's text. +# It is kept out of this file because the paths and folder names quoted in those texts would read as references +# of this test to the real repository. +with open(os.path.join(ROOT, "tests", "fixtures", "tests_for_checkout.json"), encoding="utf-8") as _data: + FILES = json.load(_data) +# Two paths the assertions need; split so that they do not read as references either. +CMAKE = "runtime/CMake" + "Lists.txt" +I18N = "tests/test_i18n" + "_index.py" + + +class Checkout(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.td = tempfile.TemporaryDirectory(prefix="leonida tests_for ") + cls.addClassCleanup(cls.td.cleanup) + cls.root = os.path.join(cls.td.name, "checkout") + for path, text in FILES.items(): + full = os.path.join(cls.root, path) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + def found(self, path, reason=None): + entry, = tests_for.survey(self.root, [path]) + return [(t["test"], t["through"]) if reason == "imports" else t["test"] for t in entry["tests"] + if reason is None or t["reason"] == reason] + + def run_tool(self, *args): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = tests_for.main(["--repo", self.root, *args]) + return code, out.getvalue(), err.getvalue() + + +class ReachTest(Checkout): + def test_a_test_names_a_file_by_import_path_or_joined_segments(self): + self.assertEqual(self.found("tools/alpha.py", "names it"), ["tests/test_alpha.py"]) + self.assertEqual(self.found("tools/carve.py", "names it"), ["tests/test_paths.py"]) + self.assertEqual(self.found("build_all.py", "names it"), ["tests/test_paths.py"]) + self.assertEqual(self.found("viewer/page.html", "names it"), ["tests/test_joined.py", "tests/test_page.cjs"]) + self.assertEqual(self.found("viewer/other.html", "names it"), ["tests/test_pathlib.py"]) + self.assertEqual(self.found("tools/lonely.py"), ["tests/test_numpy_marker.py"]) + + def test_imports_are_followed_and_say_which_module_they_go_through(self): + self.assertEqual(self.found("tools/helper.py", "names it"), ["tests/test_pytest_marker.py"]) + self.assertEqual(self.found("tools/helper.py", "imports"), + [("tests/semantic/test_one.py", "tests/semantic/common.py"), ("tests/test_alpha.py", "tools/alpha.py"), + ("tests/test_through_helper.py", "tests/helpers.py")]) + # Two imports deep, and one of two modules on an import line. + self.assertEqual(self.found("tools/deeper.py", "imports"), + [("tests/semantic/test_one.py", "tests/semantic/common.py"), ("tests/test_alpha.py", "tools/alpha.py")]) + self.assertEqual(self.found("tools/deeper.py", "names it"), ["tests/test_import_path.py"]) + # A script the build runs by path is reached through the build. + self.assertEqual(self.found("tools/carve.py", "imports"), []) + self.assertEqual(tests_for.Repository(self.root).names["build_all.py"], {"tools/carve.py"}) + + def test_a_folder_counts_when_the_test_names_it_and_nothing_in_it(self): + self.assertEqual(self.found("viewer/page.html", "folder"), ["tests/test_viewer_pages.py"]) + self.assertEqual(self.found("viewer/server.py", "folder"), ["tests/test_viewer_pages.py"]) + # tools/ is named only to import from it, in one line or in two. + self.assertEqual(self.found("tools/lonely.py", "folder"), []) + self.assertEqual(self.found("tools/carve.py", "folder"), []) + # A folder called game or docs under some other root is not the repository's. + self.assertEqual(self.found("game/manifest.json"), []) + # Only the files right in the folder, not what lies deeper. + self.assertEqual(self.found("runtime/shims/net.cpp", "folder"), []) + + def test_markdown_goes_to_the_documentation_tests_ci_runs(self): + for path in ("docs/topic.md", "GUIDE.md", "docs/i18n/fr/sample.md"): + self.assertEqual(self.found(path), ["tests/test_docs_sample.py", I18N]) + self.assertEqual(self.found(path, "folder"), ["tests/test_docs_sample.py", I18N]) + + def test_a_fixture_goes_to_the_tests_beside_it_that_name_it(self): + self.assertEqual(self.found("tests/semantic/fixtures/ps_case.asm"), ["tests/semantic/test_one.py"]) + self.assertEqual(self.found("tests/fixtures/sample.bin"), ["tests/test_fixture_user.py"]) + self.assertEqual(self.found("tests/notes.txt"), []) + + def test_a_test_file_is_its_own_test(self): + entry, = tests_for.survey(self.root, ["tests/test_alpha.py"]) + self.assertEqual((entry["is_test"], entry["tests"], entry["ctest"]), (True, [], [])) + self.assertFalse(tests_for.survey(self.root, ["tests/helpers.py"])[0]["is_test"]) + + def test_how_ci_runs_each_test_file(self): + for test, runner in (("tests/test_alpha.py", "python"), ("tests/test_pathlib.py", "pytest"), + ("tests/test_pytest_marker.py", "pytest"), ("tests/test_numpy_marker.py", "pytest"), + ("tests/semantic/test_one.py", "semantic"), ("tests/test_page.cjs", "node")): + self.assertEqual(tests_for.runner_of(self.root, test), runner, test) + + +class EdgeTest(Checkout): + def test_a_module_name_goes_to_the_file_beside_the_importer_first(self): + self.assertEqual(self.found("tools/common.py"), ["tests/test_tools_common.py"]) + self.assertEqual(self.found("tests/semantic/common.py", "names it"), ["tests/semantic/test_one.py"]) + + def test_a_test_that_another_test_imports_is_a_module_too(self): + self.assertEqual(self.found("tests/test_base.py", "names it"), ["tests/test_uses_test.py"]) + # A module is reached by imports only: a test that quotes its bare name does not count, as it would for + # a fixture. + self.assertEqual(self.found("tests/helpers.py"), ["tests/test_through_helper.py"]) + + def test_a_path_among_other_arguments_and_one_under_a_dot_folder(self): + self.assertEqual(self.found("scripts/runner.py", "names it"), ["tests/test_argv.py", "tests/test_joined.py"]) + self.assertEqual(self.found(".github/workflows/build.yml"), ["tests/test_ci.py"]) + + def test_a_test_that_names_its_own_path_is_not_its_own_test(self): + self.assertEqual(self.found("tests/test_paths.py"), []) + + def test_tests_are_listed_by_reason_then_by_name(self): + self.assertEqual(self.found("tools/helper.py"), ["tests/test_pytest_marker.py", "tests/semantic/test_one.py", + "tests/test_alpha.py", "tests/test_through_helper.py"]) + + def test_the_folder_reason_is_for_the_files_right_in_the_folder(self): + self.assertEqual(self.found(CMAKE, "folder"), ["tests/test_runtime_dir.py"]) + self.assertEqual(self.found("runtime/shims/net.cpp", "folder"), []) + + def test_ctest_entries_are_read_as_declared_and_loops_leave_no_placeholder(self): + names = [name for name, _, _ in tests_for.Runtime(self.root).tests] + self.assertEqual(names, ["net", "net_again", "core", "core", "loop_a", "loop_b", "run_modes", "rejects_one", + "rejects_two", "part"]) + # Declared once per platform, listed once. + self.assertEqual(tests_for.survey(self.root, ["runtime/src/core.cpp"])[0]["ctest"].count("core"), 1) + + def test_a_header_is_looked_up_beside_the_file_that_includes_it(self): + self.assertEqual(tests_for.survey(self.root, ["runtime/extra/part.h"])[0]["ctest"], ["part"]) + + def test_a_changed_test_alone_is_run(self): + out = self.run_tool("tests/test_docs_sample.py")[1] + self.assertTrue(out.endswith("Run:\n python -I tests/test_docs_sample.py\n"), out) + + def test_two_files_of_one_program_name_its_tests_once(self): + report = json.loads(self.run_tool("--json", "runtime/shims/net.cpp", "runtime/test/net_test.cpp")[1]) + self.assertEqual(report["commands"], ['ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure ' + '-R "^(net|net_again|run_modes|rejects_one|rejects_two)$"']) + out = self.run_tool("runtime/test/core_test.cpp")[1] + self.assertIn(" ctest (1): core\n", out) + self.assertNotIn("no test names it", out) + + def test_cmake_comments_and_nested_parentheses(self): + text = ('add_executable(x a.cpp # (was: b.cpp\n c.cpp)\nadd_test(NAME n COMMAND prog "(x)" tail)\n' + "if(A AND (B OR C))\n") + self.assertEqual(tests_for.cmake_commands(text), [ + ("add_executable", ["x", "a.cpp", "c.cpp"]), ("add_test", ["NAME", "n", "COMMAND", "prog", "(x)", "tail"]), + ("if", ["A", "AND", "B", "OR", "C"])]) + + +class RuntimeTest(Checkout): + def ctest(self, path): + return tests_for.survey(self.root, [path])[0]["ctest"] + + def test_a_source_goes_to_the_tests_of_every_program_built_from_it(self): + self.assertEqual(self.ctest("runtime/test/net_test.cpp"), ["net", "net_again"]) + # In the test's program and, through the set() list, in rt. + self.assertEqual(self.ctest("runtime/shims/net.cpp"), ["net", "net_again", "run_modes", "rejects_one", "rejects_two"]) + self.assertEqual(self.ctest("runtime/shims/late.cpp"), ["run_modes", "rejects_one", "rejects_two"]) + self.assertEqual(self.ctest("runtime/shims/unused.cpp"), []) + self.assertEqual(self.ctest("tools/alpha.py"), []) + + def test_loops_are_followed(self): + self.assertEqual(self.ctest("runtime/test/loop_a_test.cpp"), ["loop_a"]) + self.assertEqual(self.ctest("runtime/test/loop_b_test.cpp"), ["loop_b"]) + self.assertEqual(self.ctest("runtime/shims/audio.cpp"), ["loop_a", "loop_b", "run_modes", "rejects_one", "rejects_two"]) + + def test_a_library_goes_to_the_programs_that_link_it(self): + self.assertEqual(self.ctest("runtime/src/core.cpp"), ["core", "run_modes", "rejects_one", "rejects_two"]) + + def test_a_header_goes_to_the_sources_that_include_it(self): + # types.h <- net.h <- net.cpp, entry.cpp and net_test.cpp + self.assertEqual(self.ctest("runtime/shims/types.h"), ["net", "net_again", "run_modes", "rejects_one", "rejects_two"]) + self.assertEqual(self.ctest("runtime/src/core.h"), ["core", "run_modes", "rejects_one", "rejects_two"]) + + def test_a_script_a_ctest_runs_is_that_test(self): + self.assertEqual(self.ctest("runtime/test/check_modes.py"), ["run_modes"]) + + def test_cmake_text_is_read_as_commands(self): + text = 'set(A x.cpp "y z.cpp") # add_test(NAME no COMMAND no)\nadd_test(NAME t\n COMMAND prog --flag)\n' + self.assertEqual(tests_for.cmake_commands(text), [("set", ["A", "x.cpp", "y z.cpp"]), + ("add_test", ["NAME", "t", "COMMAND", "prog", "--flag"])]) + + +class CommandsTest(Checkout): + def test_commands_follow_the_runners(self): + code, out, err = self.run_tool("tools/helper.py", "viewer/page.html", "runtime/shims/net.cpp", "tests/test_alpha.py") + self.assertEqual((code, err), (0, "")) + self.assertIn("tools/helper.py\n names it (1): tests/test_pytest_marker.py\n" + " imports (3): tests/semantic/test_one.py (through tests/semantic/common.py), " + "tests/test_alpha.py (through tools/alpha.py), tests/test_through_helper.py (through tests/helpers.py)\n", out) + self.assertIn("tests/test_alpha.py (a test)\n", out) + self.assertIn("runtime/shims/net.cpp\n ctest (5): net, net_again, run_modes, rejects_one, rejects_two\n", out) + self.assertTrue(out.endswith( + "Run:\n" + " python -I tests/test_alpha.py\n" + " python -I tests/test_joined.py\n" + " python -I tests/test_through_helper.py\n" + " python -I tests/test_viewer_pages.py\n" + " python -m pytest tests/test_pytest_marker.py # needs tests/requirements.txt\n" + " python -I scripts/run_semantic_tests.py tests/semantic -p test_one.py\n" + " node --test tests/test_page.cjs\n" + ' ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure -R "^(net|net_again|run_modes|rejects_one|rejects_two)$"\n'), + out) + + def test_a_file_nothing_names_says_so(self): + code, out, _ = self.run_tool("runtime/shims/unused.cpp") + self.assertEqual((code, out), (0, "runtime/shims/unused.cpp\n no test names it\n\nNothing to run was found for these files.\n")) + + def test_wide_reasons_are_left_out_of_the_commands_when_they_are_many(self): + report = [{"file": "tools/x.py", "is_test": False, "ctest": [f"t{i}" for i in range(41)], + "tests": [{"test": "tests/test_alpha.py", "reason": "names it", "through": None}, + # Reached a second way: it is among the chosen ones, not one more wide test. + {"test": "tests/test_alpha.py", "reason": "imports", "through": "tools/y.py"}] + + [{"test": f"tests/semantic/test_w{i:02}.py", "reason": "imports", "through": "tools/y.py"} for i in range(21)]}] + lines, left_out = tests_for.commands(self.root, report, False) + self.assertEqual((lines, left_out), (["python -I tests/test_alpha.py", + "ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure # 41 of its tests"], 21)) + lines, left_out = tests_for.commands(self.root, report, True) + self.assertEqual((lines[:2], left_out), (["python -I tests/test_alpha.py", + "python -I scripts/run_semantic_tests.py tests/semantic # 21 of its files"], 0)) + # Twenty are still listed one by one, and forty ctest names still make a pattern. + report[0]["tests"].pop() + report[0]["ctest"].pop() + lines, left_out = tests_for.commands(self.root, report, False) + self.assertEqual((len(lines), left_out), (22, 0)) + self.assertEqual(lines[1], "python -I scripts/run_semantic_tests.py tests/semantic -p test_w00.py") + self.assertTrue(lines[-1].endswith('-R "^(' + "|".join(f"t{i}" for i in range(40)) + ')$"')) + self.assertIn("21 more test(s) reach these files", self.text_for(report, 21)) + + def text_for(self, report, left_out): + out = io.StringIO() + with contextlib.redirect_stdout(out): + tests_for.print_report(report, ["x"], left_out) + return out.getvalue() + + def test_a_folder_argument_stands_for_its_files(self): + report = json.loads(self.run_tool("--json", "viewer")[1]) + self.assertEqual([entry["file"] for entry in report["files"]], ["viewer/other.html", "viewer/page.html", "viewer/server.py"]) + self.assertEqual(sorted(report), ["commands", "files", "left_out"]) + self.assertIn("node --test tests/test_page.cjs", report["commands"]) + with contextlib.chdir(os.path.join(self.root, "tools")): + self.assertEqual(json.loads(self.run_tool("--json", "alpha.py")[1])["files"][0]["file"], "tools/alpha.py") + code, out, err = self.run_tool(os.path.join("..", "elsewhere.py")) + self.assertEqual((code, out), (2, "")) + self.assertIn("tests_for: ", err) + self.assertIn("is not inside the repository", err) + + +class BranchTest(unittest.TestCase): + def test_without_paths_the_branchs_files_are_taken(self): + td = tempfile.TemporaryDirectory(prefix="leonida tests_for git ") + self.addCleanup(td.cleanup) + root = os.path.join(td.name, "repo") + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env.update({"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}) + patcher = mock.patch.dict(os.environ, env, clear=True) + patcher.start() + self.addCleanup(patcher.stop) + + def git(*args): + r = subprocess.run(["git", "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "-c", "commit.gpgsign=false", "-C", root, *args], capture_output=True, encoding="utf-8") + self.assertEqual(r.returncode, 0, r.stderr) + + def write(path, text): + full = os.path.join(root, path) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + for path, text in (("tools/alpha.py", ""), ("tools/beta.py", ""), ("tools/gamma.py", ""), + ("tests/test_alpha.py", HEAD + TOOLS + "import alpha\n" + MAIN), + ("tests/test_beta.py", HEAD + TOOLS + "import beta\n" + MAIN), + ("tests/test_gamma.py", HEAD + TOOLS + "import gamma\nimport delta\n" + MAIN)): + write(path, text) + git("init", "-q", "-b", "main") + git("add", "-A") + git("commit", "-q", "-m", "start") + git("checkout", "-q", "-b", "work") + write("tools/alpha.py", "A = 1\n") + git("commit", "-q", "-am", "alpha") + write("tools/beta.py", "B = 1\n") # modified, not committed + write("tools/delta.py", "D = 1\n") # untracked + + def run(*args): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = tests_for.main(["--repo", root, "--base", "main", *args]) + return code, out.getvalue(), err.getvalue() + + report = json.loads(run("--json")[1]) + self.assertEqual([entry["file"] for entry in report["files"]], ["tools/alpha.py", "tools/beta.py", "tools/delta.py"]) + self.assertEqual(report["commands"], ["python -I tests/test_alpha.py", "python -I tests/test_beta.py", + "python -I tests/test_gamma.py"]) + # Another head is compared as committed, without the working tree. + git("branch", "other", "main") + self.assertEqual(json.loads(run("--json", "--head", "work")[1])["commands"], ["python -I tests/test_alpha.py"]) + self.assertEqual(run("--head", "other")[1], "No changed files: name the files or folders to look up.\n") + code, out, err = run("--head", "nowhere") + self.assertEqual((code, out), (2, "")) + self.assertTrue(err.startswith("tests_for: git diff"), err) + + +def real(words): + """A path of the real repository, written with spaces so that this file does not name it.""" + return words.replace(" ", "/") + + +class ThisRepositoryTest(unittest.TestCase): + SCRIPT, THIS = real("scripts tests_for.py"), real("tests test_tests_for.py") + + def test_this_file_names_only_the_script_and_its_fixture(self): + # If the texts of the synthetic checkout were in this file, their paths (a viewer page, a docs page, the + # CMake file) would make this test come up for the real files of those names. + files, folders = tests_for.Repository(ROOT).references(self.THIS, tests_for.read(__file__)) + self.assertEqual((files, folders), ({self.SCRIPT, real("tests fixtures tests_for_checkout.json")}, set())) + + def test_this_test_is_what_the_script_is_tested_by(self): + entry, = tests_for.survey(ROOT, [self.SCRIPT]) + self.assertEqual([t["test"] for t in entry["tests"] if t["reason"] == "names it"], [self.THIS]) + # The fixture is a file of its own: changing it brings this test up as well. + entry, = tests_for.survey(ROOT, [real("tests fixtures tests_for_checkout.json")]) + self.assertEqual([t["test"] for t in entry["tests"]], [self.THIS]) + + def test_the_runtime_has_programs_and_tests_to_map(self): + runtime = tests_for.Runtime(ROOT) + self.assertGreater(len(runtime.tests), 300) + self.assertIn("ws2_offline", runtime.tests_for(real("runtime shims ws2_offline.cpp"))) + self.assertEqual(runtime.tests_for(real("runtime test loader_test.cpp")), ["loader"]) + + +if __name__ == "__main__": + unittest.main()