From 5ca7242615e94a9cc087cba217bbb04f4dc49ed2 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sun, 29 Nov 2026 23:45:29 -0800 Subject: [PATCH] Tests: the native suite in seconds, every test on its own, all cores - scripts/test-native.py (just t WORD): builds once, runs each test in its own process in parallel, longest first, with a timeout; CI and just test use it. - Tests no longer search this machine's apps and icon themes. - Compiled wasm modules are cached between test processes (CHANDRA_WASM_CACHE). - draw_circle fills its middle with spans (same pixels); encode_png writes into one buffer, with a CRC table. - The ffprobe helper always waited out its 20 s: its done file was empty. - The fake polkit helper no longer depends on which shell sh is. Co-Authored-By: Claude Opus 5.5 --- compositor/host/screenshot_test.mbt | 2 +- compositor/polkit/polkit_test.mbt | 2 +- compositor/renderer/fill_wbtest.mbt | 38 ++++++ compositor/renderer/renderer.mbt | 201 +++++++++++++++++++--------- compositor/shell/default_apps.mbt | 3 +- compositor/shell/icons.mbt | 13 +- compositor/wasm/wasm_stub.c | 48 ++++++- docs/TOOLCHAIN.md | 4 + docs/desktop-modules.md | 3 +- justfile | 8 +- scripts/test-native.py | 152 +++++++++++++++++++++ scripts/test.sh | 4 +- 12 files changed, 397 insertions(+), 81 deletions(-) create mode 100755 scripts/test-native.py diff --git a/compositor/host/screenshot_test.mbt b/compositor/host/screenshot_test.mbt index cb28f92..4788e30 100644 --- a/compositor/host/screenshot_test.mbt +++ b/compositor/host/screenshot_test.mbt @@ -170,7 +170,7 @@ fn need_ffmpeg() -> Unit raise { fn run_capture(cmd : String, tag : String) -> String { let out = "/tmp/chandra-rec-" + tag + "-" + @sys.getpid().to_string() + ".txt" let done = out + ".done" - ignore(@sys.spawn("(" + cmd + ") > '" + out + "' 2>&1; touch '" + done + "'", "")) + ignore(@sys.spawn("(" + cmd + ") > '" + out + "' 2>&1; echo > '" + done + "'", "")) let t0 = @sys.monotonic_ms() while @sys.read_file_bytes(done).length() == 0 && @sys.monotonic_ms() - t0 < 20000UL { @sys.sleep_ms(20) diff --git a/compositor/polkit/polkit_test.mbt b/compositor/polkit/polkit_test.mbt index c480eca..c83546b 100644 --- a/compositor/polkit/polkit_test.mbt +++ b/compositor/polkit/polkit_test.mbt @@ -534,7 +534,7 @@ test "the setuid route: the helper runs on a socket pair and speaks the protocol @sys.write_file_bytes( script, @utf8.encode( - "#!/bin/sh\nread cookie\n[ \"$1\" = nandi ] && [ \"$cookie\" = c-1 ] || { echo FAILURE; exit 1; }\necho 'PAM_TEXT_INFO hello\\\\tthere'\necho 'PAM_PROMPT_ECHO_OFF Password: '\nread pw\nif [ \"$pw\" = 'pässword' ]; then echo SUCCESS; else echo FAILURE; fi\n", + "#!/bin/sh\nread cookie\n[ \"$1\" = nandi ] && [ \"$cookie\" = c-1 ] || { echo FAILURE; exit 1; }\nprintf '%s\\n' 'PAM_TEXT_INFO hello\\tthere'\necho 'PAM_PROMPT_ECHO_OFF Password: '\nread pw\nif [ \"$pw\" = 'pässword' ]; then echo SUCCESS; else echo FAILURE; fi\n", ), ), ) diff --git a/compositor/renderer/fill_wbtest.mbt b/compositor/renderer/fill_wbtest.mbt index cb03c60..87b4faf 100644 --- a/compositor/renderer/fill_wbtest.mbt +++ b/compositor/renderer/fill_wbtest.mbt @@ -138,3 +138,41 @@ test "span-based strokes match the per-pixel reference" { } } } + +///| +/// What draw_circle must look like: the coverage of every pixel on its own, no spans. +fn plain_circle(dst : Pixmap, cx : Int, cy : Int, radius : Int, c : @scene.Rgba, filled : Bool, clip : @scene.Rect?) -> Unit { + for dy = -radius - 1; dy <= radius + 1; dy = dy + 1 { + for dx = -radius - 1; dx <= radius + 1; dx = dx + 1 { + let d = (dx * dx + dy * dy).to_double().sqrt() + let mut cov = (radius.to_double() + 0.5 - d).min(1.0) + if !filled { + cov = cov.min((d - (radius.to_double() - 1.5)).min(1.0)) + } + if cov > 0.02 { + let a = (c.a.to_int().to_double() * cov).round().to_int() + blend_pixel(dst, cx + dx, cy + dy, c.r.to_int(), c.g.to_int(), c.b.to_int(), a, clip) + } + } + } +} + +///| +test "draw_circle's spans give the same pixels as one at a time" { + for radius in [1, 2, 3, 7, 20, 33] { + for at in [(20, 15), (-3, 4), (38, 29)] { + for alpha in [b'\xff', b'\x50'] { + for filled in [true, false] { + for clip in [None, Some(@scene.Rect::new(5, 6, 20, 13))] { + let c : @scene.Rgba = { r: b'\xd0', g: b'\x40', b: b'\x11', a: alpha } + let one = Pixmap::new(40, 30) + let two = Pixmap::new(40, 30) + draw_circle(one, at.0, at.1, radius, c, filled, clip) + plain_circle(two, at.0, at.1, radius, c, filled, clip) + assert_true(one.data == two.data) + } + } + } + } + } +} diff --git a/compositor/renderer/renderer.mbt b/compositor/renderer/renderer.mbt index 6116027..e610f36 100644 --- a/compositor/renderer/renderer.mbt +++ b/compositor/renderer/renderer.mbt @@ -346,10 +346,42 @@ fn draw_circle( let cg = color.g.to_int() let cb = color.b.to_int() let ca = color.a.to_int() + // What can show: the pixmap, intersected with the clip, as offsets from the centre. + let mut x0 = 0 + let mut y0 = 0 + let mut x1 = dst.width + let mut y1 = dst.height + match clip { + Some(c) => { + x0 = x0.max(c.x) + y0 = y0.max(c.y) + x1 = x1.min(c.x + c.w) + y1 = y1.min(c.y + c.h) + } + None => () + } + let dx0 = (x0 - cx).max(-radius - 1) + let dx1 = (x1 - 1 - cx).min(radius + 1) + let dy0 = (y0 - cy).max(-radius - 1) + let dy1 = (y1 - 1 - cy).min(radius + 1) // Antialiased: per-pixel coverage from the distance to the edge (1px wide ring when unfilled). let rad = radius.to_double() - for dy = -radius - 1; dy <= radius + 1; dy = dy + 1 { - for dx = -radius - 1; dx <= radius + 1; dx = dx + 1 { + let alpha = ca.to_double() + // Within this distance every pixel is alike: fully covered, or the empty middle of a ring. + let even = if filled { rad - 0.5 } else { rad - 1.5 } + for dy = dy0; dy <= dy1; dy = dy + 1 { + let rest = even * even - (dy * dy).to_double() + let half = if even > 0.0 && rest > 0.0 { rest.sqrt().to_int() - 1 } else { -1 } + let mut dx = dx0 + while dx <= dx1 { + if half >= 0 && dx >= -half && dx <= half { + let last = half.min(dx1) + if filled { + blend_span(dst, cy + dy, cx + dx, cx + last + 1, cr, cg, cb, ca) + } + dx = last + 1 + continue + } let d = (dx * dx + dy * dy).to_double().sqrt() let outer = rad + 0.5 - d let mut cov = if outer > 1.0 { 1.0 } else { outer } @@ -361,8 +393,9 @@ fn draw_circle( } } if cov > 0.02 { - blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, (ca.to_double() * cov).round().to_int(), clip) + blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, (alpha * cov + 0.5).to_int(), clip) } + dx = dx + 1 } } } @@ -955,18 +988,20 @@ fn push_u32_be(out : Array[Byte], v : UInt) -> Unit { out.push((v & 0xFFU).to_byte()) } +///| +let crc_table : FixedArray[UInt] = FixedArray::makei(256, n => { + let mut c = n.reinterpret_as_uint() + for _b = 0; _b < 8; _b = _b + 1 { + c = if (c & 1U) != 0U { (c >> 1) ^ 0xEDB8_8320U } else { c >> 1 } + } + c +}) + ///| fn crc32(bytes : Array[Byte], start : Int, len : Int) -> UInt { let mut c = 0xFFFF_FFFFU - for i = 0; i < len; i = i + 1 { - c = c ^ bytes[start + i].to_uint() - for _b = 0; _b < 8; _b = _b + 1 { - if (c & 1U) != 0U { - c = (c >> 1) ^ 0xEDB8_8320U - } else { - c = c >> 1 - } - } + for i = start; i < start + len; i = i + 1 { + c = (c >> 8) ^ crc_table[((c ^ bytes[i].to_uint()) & 0xFFU).reinterpret_as_int()] } c ^ 0xFFFF_FFFFU } @@ -985,65 +1020,101 @@ fn push_png_chunk(out : Array[Byte], tag : String, payload : Array[Byte]) -> Uni push_u32_be(out, crc) } -///| Encode Pixmap as a valid uncompressed RGBA PNG in pure MoonBit. +///| Encode Pixmap as a valid uncompressed RGBA PNG in pure MoonBit. Written straight into a buffer +/// of the final size: the tests save many of these, unoptimised. pub fn encode_png(p : Pixmap) -> Bytes { - let out : Array[Byte] = [ - b'\x89', b'\x50', b'\x4e', b'\x47', b'\x0d', b'\x0a', b'\x1a', b'\x0a', - ] + let row = 1 + p.width * 4 // the filter byte (0), then the pixels + let total = row * p.height + let blocks = (total + 65534) / 65535 // stored deflate blocks + let idat = 2 + total + 5 * blocks + 4 + let out : FixedArray[Byte] = FixedArray::make(8 + 25 + 12 + idat + 12, b'\x00') + let mut at = 0 + fn byte(v : Int) { + out[at] = v.to_byte() + at = at + 1 + } - // IHDR - let ihdr : Array[Byte] = [] - push_u32_be(ihdr, p.width.reinterpret_as_uint()) - push_u32_be(ihdr, p.height.reinterpret_as_uint()) - ihdr.push(b'\x08') // bit depth = 8 - ihdr.push(b'\x06') // color type = RGBA - ihdr.push(b'\x00') // compression = 0 - ihdr.push(b'\x00') // filter = 0 - ihdr.push(b'\x00') // interlace = 0 - push_png_chunk(out, "IHDR", ihdr) + fn u32(v : UInt) { + byte(((v >> 24) & 0xFFU).reinterpret_as_int()) + byte(((v >> 16) & 0xFFU).reinterpret_as_int()) + byte(((v >> 8) & 0xFFU).reinterpret_as_int()) + byte((v & 0xFFU).reinterpret_as_int()) + } - // Raw scanlines: 1 filter byte (0) + width * 4 bytes per row - let row_bytes = 1 + p.width * 4 - let raw : Array[Byte] = Array(capacity=row_bytes * p.height) + fn tag(s : String) { + for ch in s { + byte(ch.to_int()) + } + } + + fn crc(start : Int) { + let mut c = 0xFFFF_FFFFU + let table = crc_table + for i = start; i < at; i = i + 1 { + c = (c >> 8) ^ table[((c ^ out[i].to_uint()) & 0xFFU).reinterpret_as_int()] + } + u32(c ^ 0xFFFF_FFFFU) + } + + for b in [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] { + byte(b) + } + u32(13U) + let start = at + tag("IHDR") + u32(p.width.reinterpret_as_uint()) + u32(p.height.reinterpret_as_uint()) + for b in [8, 6, 0, 0, 0] { // 8 bits, RGBA, deflate, filter method 0, not interlaced + byte(b) + } + crc(start) + u32(idat.reinterpret_as_uint()) + let start = at + tag("IDAT") + byte(0x78) + byte(0x01) let mut s1 = 1U let mut s2 = 0U - for y = 0; y < p.height; y = y + 1 { - raw.push(b'\x00') - s1 = (s1 + 0U) % 65521U - s2 = (s2 + s1) % 65521U - let row_off = y * p.width * 4 - for i = 0; i < p.width * 4; i = i + 1 { - let b = p.data[row_off + i] - raw.push(b) - s1 = (s1 + b.to_uint()) % 65521U - s2 = (s2 + s1) % 65521U - } - } - - // Zlib stream with stored (uncompressed) deflate blocks (max 65535 bytes each) - let idat : Array[Byte] = [b'\x78', b'\x01'] - let mut pos = 0 - let total = raw.length() + let mut left = 0 // in this block + let mut pos = 0 // in the scanlines + let mut col = 0 // in the row + let mut src = 0 + let mut due = 5552 // bytes until the Adler sums could overflow + let data = p.data while pos < total { - let rem = total - pos - let blk = if rem > 65535 { 65535 } else { rem } - let is_last = pos + blk >= total - idat.push(if is_last { b'\x01' } else { b'\x00' }) - idat.push((blk & 0xFF).to_byte()) - idat.push(((blk >> 8) & 0xFF).to_byte()) - let nlen = blk ^ 0xFFFF - idat.push((nlen & 0xFF).to_byte()) - idat.push(((nlen >> 8) & 0xFF).to_byte()) - for i = 0; i < blk; i = i + 1 { - idat.push(raw[pos + i]) + if left == 0 { + left = (total - pos).min(65535) + byte(if pos + left == total { 1 } else { 0 }) + byte(left & 0xFF) + byte(left >> 8) + byte((left ^ 0xFFFF) & 0xFF) + byte((left ^ 0xFFFF) >> 8) } - pos = pos + blk + let b = if col == 0 { + b'\x00' + } else { + src = src + 1 + data[src - 1] + } + out[at] = b + at = at + 1 + s1 = s1 + b.to_uint() + s2 = s2 + s1 + due = due - 1 + if due == 0 { + s1 = s1 % 65521U + s2 = s2 % 65521U + due = 5552 + } + col = if col + 1 == row { 0 } else { col + 1 } + pos = pos + 1 + left = left - 1 } - let adler = (s2 << 16) | s1 - push_u32_be(idat, adler) - push_png_chunk(out, "IDAT", idat) - - // IEND - push_png_chunk(out, "IEND", []) - Bytes::from_array(out) + u32((s2 % 65521U << 16) | (s1 % 65521U)) + crc(start) + u32(0U) + let start = at + tag("IEND") + crc(start) + Bytes::from_fixedarray(out) } diff --git a/compositor/shell/default_apps.mbt b/compositor/shell/default_apps.mbt index 2e2c529..4365138 100644 --- a/compositor/shell/default_apps.mbt +++ b/compositor/shell/default_apps.mbt @@ -201,7 +201,8 @@ pub fn XdgDirs::from_env() -> XdgDirs { } // Flatpak's exports (flatpak usually puts them in XDG_DATA_DIRS). let data_dirs = parts(or("XDG_DATA_DIRS", "/usr/local/share:/usr/share")) - for d in [home + "/.local/share/flatpak/exports/share", "/var/lib/flatpak/exports/share"] { + let flatpak = home + "/.local/share/flatpak/exports/share" + for d in if test_run() { [flatpak] } else { [flatpak, "/var/lib/flatpak/exports/share"] } { if !data_dirs.contains(d) { data_dirs.push(d) } diff --git a/compositor/shell/icons.mbt b/compositor/shell/icons.mbt index 08ce95f..a9fb88e 100644 --- a/compositor/shell/icons.mbt +++ b/compositor/shell/icons.mbt @@ -2,6 +2,12 @@ /// .desktop file (`resolve_app_id`), whose Icon= key is looked up in the freedesktop icon themes /// (a simplified icon theme spec lookup), and the file is loaded for `Image` draw ops. +///| Under the tests: only what XDG_DATA_HOME / XDG_DATA_DIRS name, not this machine's own apps and +/// icons, which are slow to search and differ between machines. +fn test_run() -> Bool { + @sys.getenv("CHANDRA_TEST_CONFIG") == "1" +} + ///| Base directories icon themes live in, highest priority first. fn icon_base_dirs() -> Array[String] { let home = @sys.getenv("HOME") @@ -18,7 +24,9 @@ fn icon_base_dirs() -> Array[String] { } } dirs.push(home + "/.local/share/flatpak/exports/share/icons") - dirs.push("/var/lib/flatpak/exports/share/icons") + if !test_run() { + dirs.push("/var/lib/flatpak/exports/share/icons") + } dirs } @@ -398,7 +406,8 @@ fn IconSearch::from_env() -> IconSearch { ///| The icon file for Icon= value `name`, or None when no theme has it. fn IconSearch::find(self : IconSearch, name : String, svg_ok : Bool) -> String? { - for path in icon_candidates(name, svg_ok, self.themes, self.bases, ["/usr/share/pixmaps"]) { + let pixmaps = if test_run() { [] } else { ["/usr/share/pixmaps"] } + for path in icon_candidates(name, svg_ok, self.themes, self.bases, pixmaps) { if @sys.read_file_bytes(path).length() > 0 { return Some(path) } diff --git a/compositor/wasm/wasm_stub.c b/compositor/wasm/wasm_stub.c index 5b9eb91..e9483ac 100644 --- a/compositor/wasm/wasm_stub.c +++ b/compositor/wasm/wasm_stub.c @@ -744,11 +744,51 @@ static void note_import(Inst *in, const wasm_name_t *m) { in->imports[have + strlen(iface) + 1] = 0; } } +/* Compile a core module. With CHANDRA_WASM_CACHE=DIR (scripts/test-native.py, whose every test is + * a new process) the compiled code is kept there. Compiled code is loaded unchecked: the directory + * has to be ours alone and belong to one wasmer build, so a normal session doesn't use it. */ +static wasm_module_t *compile_module(const uint8_t *bytes, size_t len) { + wasm_byte_vec_t v; + wasm_module_t *mod = NULL; + const char *dir = getenv("CHANDRA_WASM_CACHE"); + char path[1024], tmp[1100]; + int cache = 0; + if (dir && *dir) { + uint64_t h = 14695981039346656037ull; + for (size_t i = 0; i < len; i++) h = (h ^ bytes[i]) * 1099511628211ull; + int n = snprintf(path, sizeof path, "%s/%016llx-%zu", dir, (unsigned long long)h, len); + cache = n > 0 && (size_t)n < sizeof path; + } + FILE *f = cache ? fopen(path, "rb") : NULL; + if (f) { + fseek(f, 0, SEEK_END); + long n = ftell(f); + rewind(f); + if (n > 0) { + wasm_byte_vec_new_uninitialized(&v, (size_t)n); + if (fread(v.data, 1, (size_t)n, f) == (size_t)n) mod = wasm_module_deserialize(store, &v); + wasm_byte_vec_delete(&v); + } + fclose(f); + if (mod) return mod; + } + wasm_byte_vec_new(&v, len, (const wasm_byte_t *)bytes); + mod = wasm_module_new(store, &v); + wasm_byte_vec_delete(&v); + if (!mod || !cache) return mod; + wasm_module_serialize(mod, &v); + snprintf(tmp, sizeof tmp, "%s.%d", path, (int)getpid()); + f = v.size ? fopen(tmp, "wb") : NULL; + if (f) { + int ok = fwrite(v.data, 1, v.size, f) == v.size; + if (fclose(f) != 0 || !ok || rename(tmp, path) != 0) unlink(tmp); + } + wasm_byte_vec_delete(&v); + return mod; +} + static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len) { - wasm_byte_vec_t bin; - wasm_byte_vec_new(&bin, len, (const wasm_byte_t *)bytes); - wasm_module_t *mod = wasm_module_new(store, &bin); - wasm_byte_vec_delete(&bin); + wasm_module_t *mod = compile_module(bytes, len); if (!mod) return 0; wasm_exporttype_vec_t ets; diff --git a/docs/TOOLCHAIN.md b/docs/TOOLCHAIN.md index 8188bf3..9edaeff 100644 --- a/docs/TOOLCHAIN.md +++ b/docs/TOOLCHAIN.md @@ -95,6 +95,10 @@ scripts/build.sh # or: scripts/build.sh clock-binary (one component scripts/test.sh ``` +While working, `scripts/test-native.py WORD` (or `just t WORD`) runs the native tests whose file or +name contains WORD, in seconds: each test in its own process, on all cores. Without a word it runs +them all. + Pinned versions: moon 0.1.20261119 (moonc `738607b`), wasm-tools 1.263.0, wit-bindgen 0.63.0, wasmtime 51.0.0, jco 1.42.0, Node 20/24. diff --git a/docs/desktop-modules.md b/docs/desktop-modules.md index d60a749..a73845e 100644 --- a/docs/desktop-modules.md +++ b/docs/desktop-modules.md @@ -110,8 +110,7 @@ win, drags stay with the module), the right-click menu, resize, idle and animati reload, and screenshots (`_build/desktop_*.png`). Run with: ``` -XDG_CONFIG_HOME=$(mktemp -d) CHANDRA_TEST_CONFIG=1 \ - moon test --target native --warn-list -a -p chandra/desktop/compositor/host --filter "*desktop*" +scripts/test-native.py -p compositor/host desktop ``` Also checked headless on `build/wasmhost` (`--gfx-out`) with `:desktop` set in diff --git a/justfile b/justfile index 0cb499f..dbf4c26 100644 --- a/justfile +++ b/justfile @@ -155,12 +155,16 @@ remote-build *targets: # Compositor + wasm component + lib tests. test: modules emoji-font - XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 moon test --target native --warn-list -a compositor/renderer compositor/wasm compositor/emoji compositor/host + scripts/test-native.py moon test --target wasm --warn-list -a lib/shell lib/panel lib/clock lib/launcher lib/wm lib/taskbar lib/layoutpick lib/modmgr +# Native tests whose file or name contains one of WORDS (all without any), in parallel: `just t touch`. +t *words: + scripts/test-native.py {{words}} + # Render one composed frame to _build/e2e_frame.png (via the e2e test). frame: modules - moon test --target native --warn-list -a compositor/host + scripts/test-native.py -p compositor/host e2e_test @echo "wrote _build/e2e_frame.png" # Everything CI runs. diff --git a/scripts/test-native.py b/scripts/test-native.py new file mode 100755 index 0000000..c375258 --- /dev/null +++ b/scripts/test-native.py @@ -0,0 +1,152 @@ +#!/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() diff --git a/scripts/test.sh b/scripts/test.sh index 4461612..7e8c6c6 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -52,8 +52,6 @@ if [ -d "$WASMER/lib" ]; then fi # The emoji picker's font (Noto Color Emoji, bitmap edition): compositor/emoji's tests read it. scripts/fetch-emoji-font.sh -XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 \ - moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/wasm \ - compositor/network compositor/portal compositor/polkit compositor/x11 compositor/emoji compositor/host +scripts/test-native.py --timeout 240 --slowest 10 scripts/test-private-bus.sh moon build --target native --warn-list -a compositor/bin