Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,19 +86,14 @@ jobs:
- name: Tests (standard library only, no game data)
shell: bash
run: |
# Run every file, then fail: stopping at the first failure would hide the files after it.
failed=()
# Keep the pytest selection predicate, but run the selected files two at a time.
# The runner reports every failure instead of stopping at the first one.
while IFS= read -r t; do
if grep -Eq "$PYTEST_FILE_MARKERS" "$t" || ! grep -q '__main__' "$t"; then
continue
fi
echo "== $t"
python -I "$t" || failed+=("$t")
done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) # pytest-based files run in the translator-tests job
if (( ${#failed[@]} )); then
for t in "${failed[@]}"; do echo "::error file=$t::$t failed"; done
exit 1
fi
printf '%s\n' "$t"
done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) | python -I scripts/run_standalone_tests.py -j 2
- name: Build rpf9dump
run: dotnet build tools/rpf9dump/rpf9dump.csproj -c Release
- name: Test TTPF export retry
Expand Down
70 changes: 70 additions & 0 deletions scripts/run_standalone_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Run selected standalone Python test files, one subprocess per file.
Read a newline-delimited list of paths from stdin and run each with python -I
from the caller's working directory. Selection stays with the CI workflow, so
pytest and standalone tests use the same predicate. Bounded parallelism keeps
each file's output together and still reports every failure at the end.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import subprocess
import sys


def positive_int(value):
jobs = int(value)
if jobs < 1:
raise argparse.ArgumentTypeError("jobs must be positive")
return jobs


def run_file(path):
try:
# A test (or one of its children) must not read the stream of selected paths.
result = subprocess.run([sys.executable, "-I", path], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, errors="replace")
except OSError as exc:
return 1, f"Could not start test: {exc}\n"
return result.returncode, result.stdout


def run_tests(paths, jobs):
if not paths:
print("No standalone test files selected", file=sys.stderr)
return 1

failed = []
with ThreadPoolExecutor(max_workers=jobs) as pool:
pending = {pool.submit(run_file, path): path for path in paths}
for future in as_completed(pending):
path = pending.pop(future)
code, output = future.result()
print(f"== {path}", flush=True)
if output:
print(output, end="" if output.endswith("\n") else "\n", flush=True)
if code:
failed.append(path)

# Match the Windows check job's file annotations, regardless of completion order.
for path in sorted(failed):
print(f"::error file={path}::{path} failed")
print(f"{len(paths)} files, {len(failed)} files failed", flush=True)
return int(bool(failed))


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("-j", "--jobs", type=positive_int, default=1, help="files at a time (default: 1)")
args = parser.parse_args(argv)
return run_tests([path for path in sys.stdin.read().splitlines() if path], args.jobs)


if __name__ == "__main__":
if sys.stdout.isatty():
sys.stdout.reconfigure(errors="replace")
else:
# GitHub Actions reads annotations as UTF-8, including on Windows.
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
# Git Bash writes its find/printf paths as UTF-8, even on Windows.
sys.stdin.reconfigure(encoding="utf-8")
sys.exit(main())
12 changes: 10 additions & 2 deletions tests/test_ci_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,9 +645,16 @@ def test_loop_runs_past_a_failure_and_names_every_failed_file(self):
markers = ci_rules(ROOT)[0]
failing = "import sys\nif __name__ == \"__main__\":\n sys.exit(1)\n"
passing = "import sys\nif __name__ == \"__main__\":\n sys.exit(0)\n"
# In the old shell loop a child could consume the find stream from stdin,
# silently preventing subsequent test files from running.
reading_stdin = "import sys\nif __name__ == \"__main__\":\n assert sys.stdin.read() == ''\n"
with tempfile.TemporaryDirectory() as tmp:
os.makedirs(os.path.join(tmp, "tests", "semantic"))
os.makedirs(os.path.join(tmp, "scripts"))
shutil.copyfile(os.path.join(ROOT, "scripts", "run_standalone_tests.py"),
os.path.join(tmp, "scripts", "run_standalone_tests.py"))
files = {
"tests/test_0_reads_stdin.py": reading_stdin,
"tests/test_a_fails.py": failing,
"tests/test_b_passes.py": passing,
"tests/test_c_fails.py": failing,
Expand All @@ -673,13 +680,14 @@ def test_loop_runs_past_a_failure_and_names_every_failed_file(self):
out = result.stdout + result.stderr
self.assertNotEqual(result.returncode, 0, out)
ran = re.findall(r"^== (\S+)$", out, re.M)
self.assertEqual(ran, ["tests/test_a_fails.py", "tests/test_b_passes.py", "tests/test_c_fails.py"], out)
self.assertCountEqual(ran, ["tests/test_0_reads_stdin.py", "tests/test_a_fails.py",
"tests/test_b_passes.py", "tests/test_c_fails.py"], out)
errors = re.findall(r"^::error file=(\S+)::", out, re.M)
self.assertEqual(errors, ["tests/test_a_fails.py", "tests/test_c_fails.py"], out)

def test_step_script_reads_the_check_loop(self):
script = step_script(ROOT, STDLIB_STEP)
self.assertIn('python -I "$t"', script)
self.assertIn('python -I scripts/run_standalone_tests.py -j 2', script)
self.assertIn("-name 'test_*.py'", script)


Expand Down
108 changes: 108 additions & 0 deletions tests/test_run_standalone_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""CPU-only tests of the CI standalone-file runner."""
import contextlib
import io
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import unittest
from unittest import mock

ROOT = Path(__file__).resolve().parent.parent
RUNNER = ROOT / "scripts" / "run_standalone_tests.py"
sys.path.insert(0, str(RUNNER.parent))
import run_standalone_tests as runner # noqa: E402


class StandaloneRunnerTest(unittest.TestCase):
def run_cli(self, cwd, paths, jobs):
return subprocess.run([sys.executable, "-I", str(RUNNER), "-j", str(jobs)],
cwd=cwd, input="\n".join(paths) + "\n", text=True,
capture_output=True, timeout=30)

def test_subprocesses_are_isolated_and_all_files_reported(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
paths = ["test a.py", "test_b.py", "test_c.py"]
for i, path in enumerate(paths):
(root / path).write_text(
"import os, sys\n"
"assert sys.flags.isolated\n"
"assert os.path.isfile('test a.py')\n"
"assert sys.stdin.read() == ''\n"
f"print('stdout-{i}', flush=True)\n"
f"print('stderr-{i}', file=sys.stderr, flush=True)\n"
f"sys.exit({int(i != 1)})\n",
encoding="utf-8", newline="\n")
for jobs in (1, 2):
with self.subTest(jobs=jobs):
result = self.run_cli(tmp, paths, jobs)
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
for i, path in enumerate(paths):
self.assertIn(f"== {path}\nstdout-{i}\nstderr-{i}\n", result.stdout)
annotations = [line for line in result.stdout.splitlines() if line.startswith("::error")]
self.assertEqual(annotations, [f"::error file={p}::{p} failed" for p in (paths[0], paths[2])])
self.assertIn("3 files, 2 files failed", result.stdout)

result = self.run_cli(tmp, [paths[1]], 2)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("1 files, 0 files failed", result.stdout)

def test_redirected_annotations_preserve_utf8_paths(self):
# Model redirected Windows stdout even when this test runs on a UTF-8 host.
start = ("import runpy, sys; sys.stdout.reconfigure(encoding='cp1252'); "
"sys.argv = sys.argv[1:]; runpy.run_path(sys.argv[0], run_name='__main__')")
name = "test_λ.py"
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / name).write_bytes(b"raise SystemExit(1)\n")
result = subprocess.run([sys.executable, "-I", "-c", start, str(RUNNER), "-j", "2"],
cwd=tmp, input=(name + "\n").encode(), capture_output=True, timeout=30)
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn(f"== {name}".encode(), result.stdout.splitlines())
self.assertIn(f"::error file={name}::{name} failed".encode(), result.stdout.splitlines())

def test_bounds_concurrency_without_timing_assumptions(self):
lock = threading.Lock()
rendezvous = threading.Barrier(2)
active = peak = 0
seen = []

def worker(path):
nonlocal active, peak
with lock:
active += 1
peak = max(peak, active)
seen.append(path)
rendezvous.wait(timeout=10)
with lock:
active -= 1
return 0, ""

paths = [f"test_{i}.py" for i in range(4)]
with mock.patch.object(runner, "run_file", side_effect=worker), contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(runner.run_tests(paths, 2), 0)
self.assertEqual(peak, 2)
self.assertCountEqual(seen, paths)

def test_empty_selection_and_invalid_job_counts_fail(self):
with tempfile.TemporaryDirectory() as tmp:
result = self.run_cli(tmp, [], 2)
self.assertEqual(result.returncode, 1)
self.assertIn("No standalone test files selected", result.stderr)
for jobs in (0, -1, "nope"):
with self.subTest(jobs=jobs):
result = self.run_cli(tmp, [], jobs)
self.assertEqual(result.returncode, 2)

def test_launch_failure_does_not_hide_other_tests(self):
with mock.patch.object(runner.subprocess, "run", side_effect=OSError("unavailable")):
with contextlib.redirect_stdout(io.StringIO()) as out:
self.assertEqual(runner.run_tests(["test_a.py", "test_b.py"], 2), 1)
for path in ("test_a.py", "test_b.py"):
self.assertIn(f"== {path}\nCould not start test: unavailable", out.getvalue())
self.assertIn(f"::error file={path}::{path} failed", out.getvalue())


if __name__ == "__main__":
unittest.main()
Loading