refactor(backend): standardize errors and simplify configuration and test setup
This commit is contained in:
1 parent
1535c19b8c
commit
138666a7bb
92 files changed
+3994
-210
No files matched your search
@@ -0,0 +1 @@
|
||||
__pycache__/
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Discover and run whole integration tests in deterministic, isolated CI shards."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def shard_settings():
|
||||
index = os.environ.get("TEST_SHARD_INDEX")
|
||||
total = os.environ.get("TEST_SHARD_TOTAL")
|
||||
if index is None and total is None:
|
||||
return 1, 1
|
||||
if not all(value and re.fullmatch(r"[1-9][0-9]*", value) for value in (index, total)):
|
||||
raise ValueError("TEST_SHARD_INDEX and TEST_SHARD_TOTAL must both be positive integers")
|
||||
index, total = int(index), int(total)
|
||||
if index > total:
|
||||
raise ValueError("TEST_SHARD_INDEX must not exceed TEST_SHARD_TOTAL")
|
||||
return index, total
|
||||
|
||||
|
||||
def capture(command):
|
||||
result = subprocess.run(command, text=True, stdout=subprocess.PIPE, check=False)
|
||||
if result.returncode:
|
||||
print(result.stdout, file=sys.stderr, end="")
|
||||
raise subprocess.CalledProcessError(result.returncode, command)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def discover(go):
|
||||
packages = capture([*go, "list", "-tags=integration", "./integration_test/..."])
|
||||
tests = set()
|
||||
for package in sorted({line.strip() for line in packages.splitlines() if line.strip()}):
|
||||
output = capture([
|
||||
*go, "test", "-tags=integration", "-count=1", "-json", "-list=^Test", package,
|
||||
])
|
||||
for line in output.splitlines():
|
||||
event = json.loads(line)
|
||||
name = event.get("Output", "").strip()
|
||||
if event.get("Action") == "output" and re.fullmatch(r"Test\w*", name):
|
||||
tests.add((package, name))
|
||||
if not tests:
|
||||
raise ValueError("no top-level integration tests were discovered")
|
||||
return sorted(tests)
|
||||
|
||||
|
||||
def run():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--go", default=os.environ.get("GO", "go"))
|
||||
parser.add_argument("--list", action="store_true", help="list the selected tests without running them")
|
||||
args = parser.parse_args()
|
||||
go = shlex.split(args.go)
|
||||
if not go:
|
||||
raise ValueError("Go command must not be empty")
|
||||
index, total = shard_settings()
|
||||
tests = discover(go)
|
||||
if total > len(tests):
|
||||
raise ValueError(f"{total} shards would leave empty shards for {len(tests)} tests")
|
||||
selected = tests[index - 1::total]
|
||||
print(f"Integration shard {index}/{total}: {len(selected)} of {len(tests)} tests", flush=True)
|
||||
packages = defaultdict(list)
|
||||
for package, name in selected:
|
||||
print(f" {package}: {name}", flush=True)
|
||||
packages[package].append(name)
|
||||
if args.list:
|
||||
return
|
||||
for package, names in packages.items():
|
||||
# Go splits -run at slashes. Anchoring only the parent keeps all its subtests.
|
||||
pattern = "^(" + "|".join(re.escape(name) for name in names) + ")$"
|
||||
subprocess.run([
|
||||
*go, "test", "-tags=integration", "-count=1", "-timeout=10m",
|
||||
"-run=" + pattern, package,
|
||||
], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
run()
|
||||
except subprocess.CalledProcessError as error:
|
||||
print(f"Integration runner - command failed with status {error.returncode}", file=sys.stderr)
|
||||
sys.exit(error.returncode if error.returncode > 0 else 1)
|
||||
except (ValueError, OSError) as error:
|
||||
print(f"Integration runner - {error}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Exercise discovery, shard selection, and failures through the Go boundary."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
RUNNER = Path(__file__).with_name("run-integration-suite.py")
|
||||
FIXTURE = {
|
||||
"example/integration_test": ["TestZulu", "TestAlpha", "TestAlphaLong"],
|
||||
"example/integration_test/nested": ["TestSecond", "TestFirst"],
|
||||
"example/integration_test/helpers": [],
|
||||
}
|
||||
FAKE_GO = r'''
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
with Path(os.environ["RUN_LOG"]).open("a") as log:
|
||||
log.write(json.dumps(args) + "\n")
|
||||
tests = json.loads(os.environ["TEST_FIXTURE"])
|
||||
stage = "packages" if args[0] == "list" else "discovery" if "-list=^Test" in args else "tests"
|
||||
if os.environ.get("FAIL_STAGE") == stage:
|
||||
print("deliberate " + stage + " failure")
|
||||
sys.exit(23)
|
||||
if stage == "packages":
|
||||
print("\n".join(reversed(tests)))
|
||||
elif stage == "discovery":
|
||||
for name in tests[args[-1]]:
|
||||
print(json.dumps({"Action": "output", "Output": name + "\n"}))
|
||||
print(json.dumps({"Action": "output", "Output": "ok " + args[-1] + "\n"}))
|
||||
'''
|
||||
|
||||
|
||||
class IntegrationSuiteTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory(prefix="integration-runner-")
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.directory = Path(directory.name)
|
||||
self.fake_go = self.directory / "go.py"
|
||||
self.fake_go.write_text(FAKE_GO)
|
||||
self.log = self.directory / "runs.jsonl"
|
||||
|
||||
def run_suite(self, settings=None, fixture=None, list_only=False):
|
||||
environment = {
|
||||
key: value for key, value in os.environ.items()
|
||||
if key not in ("TEST_SHARD_INDEX", "TEST_SHARD_TOTAL", "FAIL_STAGE")
|
||||
}
|
||||
environment.update({
|
||||
"RUN_LOG": str(self.log),
|
||||
"TEST_FIXTURE": json.dumps(FIXTURE if fixture is None else fixture),
|
||||
})
|
||||
environment.update(settings or {})
|
||||
self.log.write_text("")
|
||||
command = [sys.executable, str(RUNNER), "--go", shlex.join([sys.executable, str(self.fake_go)])]
|
||||
if list_only:
|
||||
command.append("--list")
|
||||
result = subprocess.run(command, env=environment, text=True, capture_output=True, check=False)
|
||||
calls = [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
return result, calls
|
||||
|
||||
def selected(self, calls):
|
||||
selected = []
|
||||
for args in calls:
|
||||
patterns = [arg.removeprefix("-run=") for arg in args if arg.startswith("-run=")]
|
||||
if not patterns:
|
||||
continue
|
||||
pattern = patterns[0]
|
||||
self.assertTrue(pattern.startswith("^(") and pattern.endswith(")$"))
|
||||
self.assertNotIn("/", pattern, "subtests must remain with their parent test")
|
||||
for name in FIXTURE[args[-1]]:
|
||||
if re.search(pattern, name):
|
||||
selected.append((args[-1], name))
|
||||
self.assertFalse(re.search(pattern, "TestAlphaLonger"))
|
||||
self.assertIn("-count=1", args)
|
||||
return selected
|
||||
|
||||
def test_shards_are_disjoint_and_cover_every_package(self):
|
||||
selected = []
|
||||
for index in (1, 2, 3):
|
||||
result, calls = self.run_suite({"TEST_SHARD_INDEX": str(index), "TEST_SHARD_TOTAL": "3"})
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
shard = self.selected(calls)
|
||||
self.assertTrue(shard)
|
||||
selected.extend(shard)
|
||||
expected = [(package, name) for package, names in FIXTURE.items() for name in names]
|
||||
self.assertCountEqual(selected, expected)
|
||||
|
||||
def test_default_runs_full_suite(self):
|
||||
result, calls = self.run_suite()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(len(self.selected(calls)), 5)
|
||||
|
||||
def test_discovery_order_does_not_change_selection(self):
|
||||
settings = {"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": "2"}
|
||||
result, calls = self.run_suite(settings)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
expected = self.selected(calls)
|
||||
fixture = {package: list(reversed(names)) for package, names in reversed(FIXTURE.items())}
|
||||
result, calls = self.run_suite(settings, fixture)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.selected(calls), expected)
|
||||
|
||||
def test_list_only_never_runs_tests(self):
|
||||
result, calls = self.run_suite(list_only=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("5 of 5 tests", result.stdout)
|
||||
self.assertEqual(self.selected(calls), [])
|
||||
|
||||
def test_invalid_shard_settings_fail_before_discovery(self):
|
||||
settings = [
|
||||
{"TEST_SHARD_INDEX": "1"}, {"TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "0", "TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "3", "TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "one", "TEST_SHARD_TOTAL": "2"},
|
||||
{"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": "-2"},
|
||||
{"TEST_SHARD_INDEX": "", "TEST_SHARD_TOTAL": ""},
|
||||
]
|
||||
for setting in settings:
|
||||
with self.subTest(setting=setting):
|
||||
result, calls = self.run_suite(setting)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(calls, [])
|
||||
|
||||
def test_empty_suite_and_empty_shards_fail(self):
|
||||
for fixture in ({}, {"example/integration_test": []}):
|
||||
with self.subTest(fixture=fixture):
|
||||
result, calls = self.run_suite(fixture=fixture)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("no top-level integration tests", result.stderr)
|
||||
self.assertEqual(self.selected(calls), [])
|
||||
result, calls = self.run_suite({"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": "6"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("empty shards", result.stderr)
|
||||
self.assertEqual(self.selected(calls), [])
|
||||
|
||||
def test_discovery_and_test_failures_are_propagated(self):
|
||||
for stage in ("packages", "discovery", "tests"):
|
||||
with self.subTest(stage=stage):
|
||||
result, _ = self.run_suite({"FAIL_STAGE": stage})
|
||||
self.assertEqual(result.returncode, 23)
|
||||
self.assertIn("deliberate " + stage + " failure", result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user