#!/usr/bin/env python3 """Run the native MoonBit tests fast: build once, then every test in its own process, all cores at once. scripts/test-native.py every package scripts/test.sh runs natively scripts/test-native.py touch tests whose file or name contains "touch" (any word given) scripts/test-native.py -p compositor/host touch osk scripts/test-native.py --slowest 20 Each test gets its own config and runtime directory, so tests can't see each other's files. A test that runs past --timeout is killed and fails. Exits non-zero if any test fails. """ import argparse, concurrent.futures as cf, json, os, shutil, signal, subprocess, sys, tempfile, time ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PKGS = ["compositor/" + p for p in "renderer gfx wasm network portal polkit x11 emoji host".split()] BEGIN, END = "----- BEGIN MOON TEST RESULT -----", "----- END MOON TEST RESULT -----" def environment(): env = dict(os.environ, CHANDRA_TEST_CONFIG="1") env["PATH"] = f"{ROOT}/.tools/bin:{os.path.expanduser('~')}/.moon/bin:" + env["PATH"] wasmer = ROOT + "/.tools/wasmer" if os.path.isdir(wasmer + "/lib"): for k, d in (("C_INCLUDE_PATH", "include"), ("LIBRARY_PATH", "lib"), ("LD_LIBRARY_PATH", "lib")): env[k] = f"{wasmer}/{d}" + (":" + env[k] if env.get(k) else "") # Compiled wasm modules, kept per wasmer build. lib = os.stat(max((e.path for e in os.scandir(wasmer + "/lib") if e.is_file()), key=os.path.getsize)) env["CHANDRA_WASM_CACHE"] = f"{ROOT}/_build/wasm-cache/{lib.st_size:x}-{lib.st_mtime_ns:x}" os.makedirs(env["CHANDRA_WASM_CACHE"], mode=0o700, exist_ok=True) return env def run(test, env, timeout): pkg, exe, file, index, name = test tmp = tempfile.mkdtemp(prefix="ct-") # short: socket paths are limited to 108 bytes # Not this machine's installed apps and icon themes: scanning them took most of the time. e = dict(env, HOME=tmp, XDG_CONFIG_HOME=tmp + "/c", XDG_RUNTIME_DIR=tmp + "/r", XDG_DATA_HOME=tmp + "/d", XDG_DATA_DIRS=tmp + "/d") os.mkdir(tmp + "/c") os.makedirs(tmp + "/d/applications") for n in ("One", "Two", "Three", "Four"): # some tests want apps to be installed with open(f"{tmp}/d/applications/test-{n.lower()}.desktop", "w") as f: f.write(f"[Desktop Entry]\nType=Application\nName=Test {n}\nExec=true\nCategories=Utility;\n") os.mkdir(tmp + "/r", 0o700) t = time.monotonic() # Output goes to a file: a pipe would stay open as long as anything the test left running. with open(tmp + "/out", "w+b") as out: p = subprocess.Popen([exe, f"{file}:{index}-{index + 1}"], cwd=ROOT, env=e, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, start_new_session=True) try: code = p.wait(timeout) why = None if code == 0 else f"exit status {code}" except subprocess.TimeoutExpired: why = f"still running after {timeout:g} s" try: os.killpg(p.pid, signal.SIGKILL) except ProcessLookupError: pass p.wait() took = time.monotonic() - t out.seek(0) text = out.read().decode("utf-8", "replace") shutil.rmtree(tmp, ignore_errors=True) got, log = None, [] lines = iter(text.splitlines()) for line in lines: if line.endswith(BEGIN): try: r = json.loads(next(lines, "{}")) except ValueError: r = {} if r.get("type") == "result": got = r.get("message", "") elif not line.startswith(END) and line: log.append(line) if why is None and got is None: why = "no result" if why is None and got: why = got return test, took, why, log def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("words", nargs="*", help="run only tests whose file or name contains one of these") ap.add_argument("-p", "--package", action="append", help="package (repeatable)") ap.add_argument("-j", "--jobs", type=int, default=len(os.sched_getaffinity(0))) ap.add_argument("--timeout", type=float, default=60) ap.add_argument("--slowest", type=int, default=0, metavar="N", help="list the N slowest tests") a = ap.parse_args() env, pkgs, start = environment(), a.package or PKGS, time.monotonic() # Only the build is moon's. It also writes each test binary's list of tests. b = subprocess.run(["moon", "test", "--target", "native", "--warn-list", "-a", "--build-only", *pkgs], cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) if b.returncode: sys.exit(b.stdout) built = time.monotonic() - start tests = [] for pkg in (p.rstrip("/") for p in pkgs): d = f"{ROOT}/_build/native/debug/test/{pkg}" for kind in ("internal", "blackbox", "whitebox"): info, exe = f"{d}/__{kind}_test_info.json", f"{d}/{pkg.split('/')[-1]}.{kind}_test.exe" if not (os.path.exists(info) and os.path.exists(exe)): continue with open(info) as f: meta = json.load(f) for key in ("with_args_tests", "async_tests", "async_tests_with_args", "no_args_tests"): for file, ts in meta.get(key, {}).items(): for x in ts: name = x.get("name") or f"#{x['index']}" label = f"{pkg}/{file} {name}".lower() if not a.words or any(w.lower() in label for w in a.words): tests.append((pkg, exe, file, x["index"], name)) if not tests: sys.exit("no tests match") # The longest first (by the last run's times), so none is left running alone at the end. times_file = f"{ROOT}/_build/test-native-times.json" try: with open(times_file) as f: times = json.load(f) except (OSError, ValueError): times = {} key = lambda t: f"{t[0]}/{t[2]} {t[4]}" tests.sort(key=lambda t: -times.get(key(t), 0)) results, failed = [], [] with cf.ThreadPoolExecutor(a.jobs) as ex: for f in cf.as_completed([ex.submit(run, t, env, a.timeout) for t in tests]): (failed if f.result()[2] else results).append(f.result()) # A few tests measure time (frames recorded a second, ...): on their own they have the machine. # With many failures it is the code, not the load. for r in failed: if len(failed) <= 5: first, r = r, run(r[0], env, a.timeout) results.append(r) (pkg, _, file, _, name), took, why, log = r if why: print(f"FAIL {pkg}/{file} \"{name}\" ({took:.1f} s)\n {why}", flush=True) for line in [x for x in log if "no icon for" not in x][-15:]: print(" | " + line) else: print(f"note: {pkg}/{file} \"{name}\" failed beside the others, passed alone: {first[2].splitlines()[0]}") times.update((key(r[0]), round(r[1], 2)) for r in results) with open(times_file, "w") as f: json.dump(times, f) for (pkg, _, file, _, name), took, _, _ in sorted(results, key=lambda r: -r[1])[: a.slowest]: print(f"{took:6.2f} s {pkg}/{file} \"{name}\"") bad = sum(1 for r in results if r[2]) print(f"{len(results) - bad} passed, {bad} failed: build {built:.1f} s, tests {time.monotonic() - start - built:.1f} s") sys.exit(1 if bad else 0) main()