101 lines
3.7 KiB
Python
101 lines
3.7 KiB
Python
#!/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
|
|
|
|
# Time budget of the whole suite. CI runs it in two shards of ten minutes, so a
|
|
# shard gets its share of the budget and never less than ten minutes, and an
|
|
# unsharded local run gets the whole budget.
|
|
SUITE_TIMEOUT_MINUTES = 20
|
|
SHARD_TIMEOUT_FLOOR_MINUTES = 10
|
|
|
|
|
|
def go_timeout(total):
|
|
share = -(-SUITE_TIMEOUT_MINUTES // total)
|
|
return f"{max(SHARD_TIMEOUT_FLOOR_MINUTES, share)}m"
|
|
|
|
|
|
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=" + go_timeout(total),
|
|
"-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)
|