Crafter.Build/implementations/Crafter.Build-Test.cpp
Jorijn van der Graaf dc8e9e6f9e
feat(test): give a test that sets Test::wayland a compositor of its own
A test that opens a window opened it on the display of whoever ran the
suite: every `crafter-build test` of Crafter.Graphics put the windows
of its window tests on the desktop, and its other GPU tests connect to
the session's compositor too, since Device::Initialize calls
wl_display_connect whether a window follows or not.

A test that sets the new Test::wayland (TestBuilder::Wayland) now runs
with a headless compositor started for it alone. RunSingleTest starts
the compositor through sh, with XDG_RUNTIME_DIR naming a directory made
for it and without WAYLAND_DISPLAY, WAYLAND_SOCKET or DISPLAY, waits up
to 30 s for a wayland-<n> socket in that directory, runs the test with
WAYLAND_DISPLAY set to the socket's path and with DISPLAY and
WAYLAND_SOCKET unset, then stops the compositor's process group and
removes the directory. The test's command is env with those changes,
and env's command is sh, which execs the test's words: env takes every
word with an '=' in it ahead of its command for an assignment, a
binary's path among them. The compositor runs under timeout(1) as long
as the test may, the wait and 30 s more, and with no limit for a test
that has none, a timeout of 0. It is weston on its headless backend
with its GL renderer, unless CRAFTER_BUILD_COMPOSITOR or the new
--compositor= names another command; `host` gives the tests the
session's own display instead, to watch them. A compositor that ends
before it listens, sh not finding it included, or does not listen in
time fails the test with what it printed. A test that may run where its
compositor is missing declares it in requires_ (tool:weston for the
default), the check RunTests makes before the build, so no skip of its
own is added, and no probe of the command: the command is any sh
command, whose first word need not be the compositor. A test that
fails, crashes or times out keeps what its compositor printed
(TestResult::compositorLog), which RunTests writes to
build/test-logs/<name>.compositor.log, and says when the compositor
ended while it ran.

One compositor per test rather than one per run: no two tests share
one, so tests that run at once cannot cover each other's windows or
take each other's focus, for weston's start-up on every test. weston's
GL renderer, because it imports the dmabufs that a GPU's Vulkan driver
presents, as Mesa's and NVIDIA's do, and the headless backend's default
renderer and pixman import none: against pixman, the NVIDIA driver
reports no format for a window's surface, and Crafter.Graphics's
FrameLoopSync stops at its formatCount > 0 assertion. weston cannot
run the test itself, as `weston -- <test>` exits 0 whatever the test
returned, so crafter-build runs the compositor beside it.

:Platform gains BackgroundCommand, the compositor's process, and
PrivateDirectory, its directory. The process is forked with
PR_SET_PDEATHSIG and runs under `timeout`, which passes the SIGTERM it
gets when crafter-build dies on to the compositor's group, so a
crafter-build killed by Ctrl-C leaves no compositor running. The
directory is made in $XDG_RUNTIME_DIR, or in /tmp where that is not a
directory, rather than in the temp directory, since a socket's path
holds 107 bytes, and is flocked while in use; one that a killed
crafter-build left is removed when the next is made beside it, once it
has not changed for a minute.

New members and a parameter with a default, nothing removed: a minor
release.
2026-11-28 11:05:51 +01:00

890 lines
40 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
export module Crafter.Build:Test_impl;
import std;
import :Test;
import :Clang;
import :Platform;
import :Progress;
namespace fs = std::filesystem;
using namespace Crafter;
namespace {
bool TargetIsWindows(std::string_view target) {
return target.find("windows") != std::string_view::npos || target.find("mingw") != std::string_view::npos;
}
// MatchGlob/MatchAny live in :Platform — shared with the lint verb.
std::string JoinAndQuoteArgs(std::span<const std::string> args) {
std::string out;
for (const auto& a : args) {
if (!out.empty()) out.push_back(' ');
out += ShellQuote(a);
}
return out;
}
std::string Substitute(std::string_view tmpl, const std::map<std::string, std::string>& ph) {
std::string out;
out.reserve(tmpl.size());
std::size_t i = 0;
while (i < tmpl.size()) {
if (tmpl[i] == '{') {
std::size_t end = tmpl.find('}', i + 1);
if (end != std::string_view::npos) {
std::string key(tmpl.substr(i, end - i + 1));
if (auto it = ph.find(key); it != ph.end()) {
out += it->second;
i = end + 1;
continue;
}
}
}
out.push_back(tmpl[i++]);
}
return out;
}
std::string SignalName(std::int32_t sig) {
switch (sig) {
case 1: return "SIGHUP";
case 2: return "SIGINT";
case 4: return "SIGILL";
case 6: return "SIGABRT";
case 8: return "SIGFPE";
case 9: return "SIGKILL";
case 11: return "SIGSEGV";
case 13: return "SIGPIPE";
case 14: return "SIGALRM";
case 15: return "SIGTERM";
default: return std::format("signal {}", sig);
}
}
// Writes build/test-logs/<name>.log and returns its path, or nothing
// when the directory cannot be made.
std::optional<fs::path> WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) {
fs::path logDir = projectPath / "build" / "test-logs";
std::error_code ec;
fs::create_directories(logDir, ec);
if (ec) return std::nullopt;
const fs::path log = logDir / std::format("{}.log", name);
std::ofstream(log) << output;
return log;
}
// weston on its headless backend: the compositor a test that sets
// Test::wayland runs with unless --compositor= or CRAFTER_BUILD_COMPOSITOR
// names another. Its GL renderer takes the dmabufs that hardware Vulkan
// and EGL drivers present, which the headless backend's default, a
// renderer that draws nothing, and pixman do not. --no-config keeps the
// user's weston.ini out of the test, and --idle-time=0 keeps the output
// from going idle after the default 300 s, which would stop frame
// callbacks.
constexpr std::string_view DefaultCompositor = "weston --backend=headless --renderer=gl --no-config --idle-time=0";
// The compositor named for none of the test's own: the test gets the
// environment crafter-build has, display included, to watch its windows.
constexpr std::string_view HostDisplay = "host";
// How long a compositor may take to listen. weston needs a fraction of a
// second; this is for a machine running a test on every hardware thread.
constexpr std::chrono::seconds CompositorStartup{30};
std::string CompositorCommand(const std::optional<std::string>& compositorOverride) {
if (compositorOverride && !compositorOverride->empty()) return *compositorOverride;
const char* named = std::getenv("CRAFTER_BUILD_COMPOSITOR");
if (named != nullptr && *named != '\0') return named;
return std::string(DefaultCompositor);
}
// The wayland-<n> socket a compositor made in `directory`. Any number:
// libwayland's wl_display_add_socket_auto starts at 0 and weston at 1.
std::optional<fs::path> WaylandSocket(const fs::path& directory) {
constexpr std::string_view prefix = "wayland-";
std::error_code ec;
for (const fs::directory_entry& entry : fs::directory_iterator(directory, ec)) {
const std::string name = entry.path().filename().string();
if (!name.starts_with(prefix) || name.size() == prefix.size()) continue;
if (!std::ranges::all_of(name.substr(prefix.size()), [](char c) { return c >= '0' && c <= '9'; })) continue;
std::error_code statError;
if (fs::is_socket(entry.symlink_status(statError))) return entry.path();
}
return std::nullopt;
}
// Where the directory one test's compositor gets as its XDG_RUNTIME_DIR
// is made: in $XDG_RUNTIME_DIR, where a session's sockets live, when
// that is a directory, else in /tmp. A socket's path holds at most 107
// bytes, so the directory needs a short path, which a project's, a
// scratch directory's or the temp directory TMPDIR names need not be.
fs::path CompositorParent() {
const char* runtime = std::getenv("XDG_RUNTIME_DIR");
std::error_code ec;
if (runtime != nullptr && *runtime != '\0' && fs::is_directory(runtime, ec)) return runtime;
return "/tmp";
}
// That directory, which also holds the compositor's log.
struct CompositorDirectory : PrivateDirectory {
CompositorDirectory() : PrivateDirectory(CompositorParent(), "crafter-build-wayland-") {}
fs::path Log() const { return path / "compositor.log"; }
};
std::string ReadWhole(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
void PrintResult(const TestResult& r, std::string_view runnerName) {
Progress::Clear();
auto ms = r.duration.count();
std::string runnerSuffix = (runnerName.empty() || runnerName == "local")
? std::string()
: std::format(" ({})", runnerName);
switch (r.outcome) {
case TestOutcome::Pass:
std::println("✅ {}{} ({}ms)", r.name, runnerSuffix, ms);
break;
case TestOutcome::Fail:
std::println("❌ {}{} ({}ms) exit {}", r.name, runnerSuffix, ms, r.exitCode);
if (!r.output.empty()) {
for (auto line : std::views::split(r.output, '\n')) {
std::string_view sv(line.begin(), line.end());
if (!sv.empty()) std::println(" {}", sv);
}
}
break;
case TestOutcome::Crash:
std::println("\U0001F4A5 {}{} ({}ms) crashed: {}", r.name, runnerSuffix, ms, SignalName(r.signal));
if (!r.output.empty()) {
for (auto line : std::views::split(r.output, '\n')) {
std::string_view sv(line.begin(), line.end());
if (!sv.empty()) std::println(" {}", sv);
}
}
break;
case TestOutcome::Timeout:
std::println("⏱ {}{} ({}ms) timeout", r.name, runnerSuffix, ms);
break;
case TestOutcome::Skipped:
std::println("⏭ {}{} skipped: {}", r.name, runnerSuffix, r.output.empty() ? std::string("(no reason)") : r.output);
break;
}
}
}
namespace {
std::mutex ParentProjectsMutex;
std::vector<Configuration*> ParentProjects;
Configuration* FindLibInTree(Configuration* root, std::string_view name, std::unordered_set<Configuration*>& seen) {
if (!seen.insert(root).second) return nullptr;
if (root->name == name) return root;
for (Configuration* dep : root->dependencies) {
if (auto found = FindLibInTree(dep, name, seen)) return found;
}
return nullptr;
}
}
void Crafter::SetParentProject(Configuration* parent) {
SetParentProject(parent ? std::span<Configuration* const>(&parent, 1) : std::span<Configuration* const>());
}
void Crafter::SetParentProject(std::span<Configuration* const> parents) {
const std::lock_guard lock(ParentProjectsMutex);
ParentProjects.assign(parents.begin(), parents.end());
}
Configuration* Crafter::ParentLib(std::string_view name) {
std::vector<Configuration*> roots;
{
const std::lock_guard lock(ParentProjectsMutex);
roots = ParentProjects;
}
if (roots.empty()) {
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): no parent project set", name));
}
std::unordered_set<Configuration*> seen;
std::string names;
for (Configuration* root : roots) {
if (auto found = FindLibInTree(root, name, seen)) return found;
if (!names.empty()) names += ", ";
names += root->name;
}
throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, names));
}
TestRunner TestRunner::Local() {
TestRunner r;
r.name = "local";
return r;
}
TestRunner TestRunner::Cmd(std::string command) {
TestRunner r;
r.name = std::format("cmd:{}", command);
r.exec = std::format("{} {{bin}} {{args}}", command);
r.probe = std::format("which {}", command);
return r;
}
TestRunner TestRunner::Wine() {
TestRunner r;
r.name = "wine";
r.exec = "wine {bin} {args}";
r.probe = "which wine";
return r;
}
TestRunner TestRunner::ForTarget(const Configuration& cfg) {
const std::string& target = cfg.target;
// Same triple as the host → run the binary directly. Covers the common
// case (cfg.target defaulted to HostTarget()) without any wrapper.
if (SameTarget(target, HostTarget())) return Local();
// Windows targets run under Wine; there is no Windows host.
if (TargetIsWindows(target)) return Wine();
// WASI: a .wasm file isn't directly executable; wasmtime is the canonical
// runtime. wasi-cli also works but the upstream Bytecode Alliance name is
// wasmtime, so we standardize on that.
if (target.starts_with("wasm32-wasi") || target.starts_with("wasm64-wasi")) {
return Cmd("wasmtime");
}
// Non-host Linux triple: extract the architecture and route through
// qemu-user. Triple is <arch>-<vendor>-<os>-<env> (or sometimes 3 parts);
// qemu-user's binary names mostly follow the arch field, with two known
// mismatches handled below. cfg.sysroot, when set, becomes QEMU_LD_PREFIX
// so the target's dynamic linker / shared libs are reachable — without
// it qemu-user crashes on dynamic ELFs with "could not open /lib/ld...".
if (target.find("-linux-") != std::string::npos) {
auto dash = target.find('-');
std::string arch = target.substr(0, dash);
// i686-linux-gnu → qemu-i386; arm-* already matches qemu-arm; aarch64,
// riscv64, ppc64le, mips, mips64, s390x all match their qemu names.
if (arch == "i686") arch = "i386";
TestRunner r = Cmd(std::format("qemu-{}", arch));
if (!cfg.sysroot.empty()) {
// Use `env VAR=value cmd` rather than the shell's `VAR=value cmd`
// prefix syntax: RunCommandWithTimeout pipes through GNU `timeout`,
// which execvp's its argument list directly without going through a
// shell. A bare VAR=value would be exec'd as a command path and
// fail with "No such file or directory".
// QEMU_LD_PREFIX only redirects the ELF interpreter lookup; the
// emulated loader then searches ITS default paths against the
// host filesystem, picking up host-arch libraries from /lib —
// LD_LIBRARY_PATH steers it back into the sysroot.
r.exec = std::format("env QEMU_LD_PREFIX={0} LD_LIBRARY_PATH={0}/lib:{0}/usr/lib {1}", cfg.sysroot, r.exec);
}
return r;
}
// Unknown / bare-metal / freestanding targets: fall back to Local. The
// caller's runner-availability probe (or absence of the binary) surfaces
// the problem rather than us inventing a wrong wrapper here.
return Local();
}
namespace {
std::string NormalizeTriple(std::string_view target) {
std::string out(target);
for (char& c : out) {
if (c == '-' || c == '.') c = '_';
}
return out;
}
// Spec grammar: "local" | "cmd:<binary>". Used by CRAFTER_BUILD_RUNNER_*
// env vars and --runner=. The set used to include ssh/sshwin/wsl variants;
// those were removed when transport-style runners were dropped (issue #8).
std::optional<TestRunner> ParseRunnerSpec(std::string_view spec) {
if (spec.empty()) return std::nullopt;
if (spec == "local") return TestRunner::Local();
if (spec.starts_with("cmd:") && spec.size() > 4) {
return TestRunner::Cmd(std::string(spec.substr(4)));
}
throw std::runtime_error(std::format("TestRunner::FromSpec: unrecognized runner spec '{}' " "(expected 'local' or 'cmd:<binary>')", spec));
}
}
std::optional<TestRunner> TestRunner::FromSpec(std::string_view spec) {
return ParseRunnerSpec(spec);
}
TestRunner TestRunner::FromEnv(std::string_view target, TestRunner fallback) {
std::string envName = std::format("CRAFTER_BUILD_RUNNER_{}", NormalizeTriple(target));
const char* v = std::getenv(envName.c_str());
if (!v || !*v) return fallback;
if (auto r = ParseRunnerSpec(v)) return std::move(*r);
return fallback;
}
TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout, const std::optional<std::string>& compositorOverride) {
TestResult result;
result.name = test.config.name;
std::map<std::string, std::string> ph;
ph["{args}"] = JoinAndQuoteArgs(test.args);
std::string cmd;
if (test.runner.exec.empty()) {
// Local runner: spawn the binary directly through the host shell.
cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]);
} else {
// Prefix runner (qemu-user, wasmtime, wine, ...): templated exec
// wraps the local binary.
ph["{bin}"] = binary.string();
cmd = Substitute(test.runner.exec, ph);
}
// The test's own compositor, which no other test shares, so that no
// two tests cover each other's windows or take each other's focus. Its
// directory goes after it: declared first, it is destroyed last.
const std::string compositor = test.wayland ? CompositorCommand(compositorOverride) : std::string();
std::optional<CompositorDirectory> directory;
std::optional<BackgroundCommand> process;
if (test.wayland && compositor != HostDisplay) {
directory.emplace();
// Without a WAYLAND_DISPLAY, which the compositor would take for a
// session to open a window in (wlroots does), or a DISPLAY.
const std::array<EnvironmentChange, 4> environment = {{
{"XDG_RUNTIME_DIR", directory->path.string()},
{"WAYLAND_DISPLAY", std::nullopt},
{"WAYLAND_SOCKET", std::nullopt},
{"DISPLAY", std::nullopt},
}};
// As long as the test may run, the wait for its socket and 30 s
// more; none for a test with none, a timeout of 0, which timeout(1)
// takes for no limit, the test's as the compositor's.
const std::chrono::seconds lifetime = timeout.count() > 0 ? timeout + CompositorStartup + std::chrono::seconds(30) : std::chrono::seconds(0);
process.emplace(compositor, environment, directory->Log(), lifetime);
// weston makes its socket once its backend and renderer are up, so a
// socket means a compositor that takes clients.
const auto deadline = std::chrono::steady_clock::now() + CompositorStartup;
std::optional<fs::path> socket = WaylandSocket(directory->path);
std::optional<std::int32_t> ended;
while (!socket && !(ended = process->Exited()) && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
socket = WaylandSocket(directory->path);
}
if (!socket) {
process->Stop(std::chrono::seconds(5));
std::string printed = ReadWhole(directory->Log());
if (!printed.empty() && !printed.ends_with('\n')) printed.push_back('\n');
// A compositor that is missing fails the test as any other that
// does not start does. The one skip is the test's own requires_,
// tool:weston for the default, which RunTests checks before the
// build; a probe of the command here would not do, since it is any
// sh command, whose first word need not be the compositor.
result.outcome = TestOutcome::Fail;
result.exitCode = -1;
result.output = ended
? std::format("the headless compositor ({}) ended with status {} before it listened for clients; it printed:\n{}", compositor, *ended, printed)
: std::format("the headless compositor ({}) made no wayland-<n> socket in {} within {} s; it printed:\n{}", compositor, directory->path.string(), CompositorStartup.count(), printed);
// sh's status for a command it cannot find.
if (ended == 127) result.output += "install weston, name another compositor with CRAFTER_BUILD_COMPOSITOR or --compositor=, or skip a test that may run without it with requires_, tool:weston for weston\n";
return result;
}
// env's command is sh, which execs the test's words as they are: env
// takes every word with an '=' in it ahead of its command for an
// assignment, the binary's path among them where it has one (a test
// named a=b), and that test never ran.
cmd = std::format("env -u DISPLAY -u WAYLAND_SOCKET WAYLAND_DISPLAY={} sh -c 'exec \"$@\"' sh {}", ShellQuote(socket->string()), cmd);
}
auto start = std::chrono::steady_clock::now();
CommandResult r = RunCommandWithTimeout(cmd, timeout);
auto end = std::chrono::steady_clock::now();
result.duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
result.output = std::move(r.output);
result.exitCode = r.exitCode;
result.signal = r.signal;
if (r.timedOut) result.outcome = TestOutcome::Timeout;
else if (r.crashed) result.outcome = TestOutcome::Crash;
else if (r.exitCode == 77) result.outcome = TestOutcome::Skipped;
else if (r.exitCode != 0) result.outcome = TestOutcome::Fail;
else result.outcome = TestOutcome::Pass;
if (process) {
// Asked before Stop() ends it, which would make every compositor one
// that ended.
const std::optional<std::int32_t> ended = process->Exited();
process->Stop(std::chrono::seconds(5));
if (result.outcome != TestOutcome::Pass && result.outcome != TestOutcome::Skipped) {
if (ended) {
if (!result.output.empty() && !result.output.ends_with('\n')) result.output.push_back('\n');
result.output += std::format("the headless compositor ({}) ended with status {} while the test ran\n", compositor, *ended);
}
result.compositorLog = ReadWhole(directory->Log());
}
}
return result;
}
namespace {
bool ToolOnPath(std::string_view name) {
std::string cmd = std::format("which {} > /dev/null 2>&1", name);
return std::system(cmd.c_str()) == 0;
}
struct RequireResult {
bool ok;
std::string reason; // human-readable when !ok
};
// Evaluate each `<kind>:<arg>` precondition. Returns the first failure
// (short-circuit; reporting one missing dep at a time is enough to act on
// and keeps the test log uncluttered).
RequireResult EvaluateRequires(std::span<const std::string> reqs) {
for (const auto& r : reqs) {
auto sep = r.find(':');
if (sep == std::string::npos || sep == 0 || sep == r.size() - 1) {
return {false, std::format("malformed require '{}' (expected kind:arg)", r)};
}
std::string_view kind(r.data(), sep);
std::string_view arg(r.data() + sep + 1, r.size() - sep - 1);
if (kind == "tool") {
if (!ToolOnPath(arg)) {
return {false, std::format("tool '{}' not on PATH", arg)};
}
} else if (kind == "file") {
if (!fs::exists(std::string(arg))) {
return {false, std::format("file '{}' missing", arg)};
}
} else if (kind == "env") {
const char* v = std::getenv(std::string(arg).c_str());
if (!v || !*v) {
return {false, std::format("env '{}' unset", arg)};
}
} else {
return {false, std::format("unknown require kind '{}' (expected tool/file/env)", kind)};
}
}
return {true, ""};
}
// Match a runner's tool dependency against the test's declared
// requirements. Used to decide between Skip (declared, may legitimately
// be missing) and Fail (runner unavailable but test didn't declare it —
// a silent skip would mask broken cross-arch CI configuration).
bool RequiresMentionsTool(std::span<const std::string> reqs, std::string_view tool) {
std::string needle = std::format("tool:{}", tool);
return std::ranges::any_of(reqs, [&](const std::string& s) { return s == needle; });
}
// Best-effort extraction of the runner-tool name from a TestRunner so the
// hard-fail-unless-declared check can match it against `requires`. For
// Cmd("foo"), the name is "cmd:foo"; for Wine, it's "wine". Anything else
// (Local, transport runners) returns empty — those don't trigger the
// declared/undeclared gate.
std::string RunnerToolName(const TestRunner& runner) {
if (runner.name == "wine") return "wine";
if (runner.name.starts_with("cmd:")) {
std::string tool = runner.name.substr(4);
// QEMU_LD_PREFIX prefix may be glued onto exec but the runner's
// `name` field already isolates the command, so no extra parsing.
return tool;
}
return "";
}
}
TestBuilder Configuration::AddTest(std::string_view name) {
// Empty-interfaces trampoline. The span we hand to the (name, interfaces)
// overload wraps a stack array; it's only consulted inside that call, so
// its lifetime is fine for the duration.
std::array<fs::path, 0> noIfaces = {};
return AddTest(name, noIfaces);
}
TestBuilder Configuration::AddTest(std::string_view name, std::span<fs::path> interfaces) {
Test t;
// Default to "./" so tests/<name>/main.cpp resolves at the project root
// (where crafter-build sets cwd from project.cpp's location). Projects
// whose lib lives in a subdir (e.g. cfg.path = "./mylib/") get this
// right by default; if the test layout is unusual, override via .Path().
t.config.path = "./";
t.config.name = std::string(name);
t.config.outputName = std::string(name);
t.config.target = this->target;
t.config.march = this->march;
t.config.mtune = this->mtune;
t.config.sysroot = this->sysroot;
t.config.debug = this->debug;
t.config.cudaArch = this->cudaArch;
// Inherited so a project flag that changes what the library contains also
// moves the test's own outputs, rather than letting two flag settings share
// one test bin dir.
t.config.projectArgs = this->projectArgs;
t.config.type = ConfigurationType::Executable;
// Default source layout: tests/<name>/main.cpp resolved against the
// parent Configuration's path. cfg.path is typically "./" (project
// root), which puts the test sources at <repo>/tests/<name>/main.cpp.
fs::path mainSource = fs::path("tests") / std::string(name) / "main";
std::array<fs::path, 1> impls = { mainSource };
t.config.GetInterfacesAndImplementations(interfaces, impls);
tests.push_back(std::move(t));
return TestBuilder{this, tests.size() - 1};
}
void Configuration::AddMarchVariants(std::string_view name, std::span<fs::path> interfaces, std::span<const MarchTier> tiers) {
for (const auto& tier : tiers) {
Test t;
t.config.path = "./";
t.config.name = std::format("{}-{}", name, tier.march);
t.config.outputName = t.config.name;
t.config.target = this->target;
t.config.march = tier.march;
t.config.mtune = tier.mtune;
t.config.sysroot = this->sysroot;
t.config.debug = this->debug;
t.config.cudaArch = this->cudaArch;
t.config.projectArgs = this->projectArgs;
t.config.type = ConfigurationType::Executable;
fs::path mainSource = fs::path("tests") / std::string(name) / "main";
std::array<fs::path, 1> impls = { mainSource };
// Interfaces stamped directly into each variant's Configuration —
// NOT via cfg.dependencies. The dependency machinery caches PCMs by
// dep->VariantId(), which would compile the parent's interfaces
// once with the parent's march; for SIMD-sensitive code each
// variant needs its own compile. Listing the interfaces as the
// test's own forces per-variant recompilation.
t.config.GetInterfacesAndImplementations(interfaces, impls);
tests.push_back(std::move(t));
}
}
TestBuilder& TestBuilder::Path(fs::path p) { Ref().config.path = std::move(p); return *this; }
TestBuilder& TestBuilder::Target(std::string t) { Ref().config.target = std::move(t); return *this; }
TestBuilder& TestBuilder::March(std::string m) { Ref().config.march = std::move(m); return *this; }
TestBuilder& TestBuilder::Mtune(std::string m) { Ref().config.mtune = std::move(m); return *this; }
TestBuilder& TestBuilder::Sysroot(fs::path s) { Ref().config.sysroot = s.string(); return *this; }
TestBuilder& TestBuilder::Debug(bool d) { Ref().config.debug = d; return *this; }
TestBuilder& TestBuilder::Define(std::string n, std::string v) {
Ref().config.defines.push_back({std::move(n), std::move(v)});
return *this;
}
TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; }
TestBuilder& TestBuilder::Args(std::vector<std::string> a) { Ref().args = std::move(a); return *this; }
TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; }
TestBuilder& TestBuilder::Dependencies(std::vector<Configuration*> d) { Ref().config.dependencies = std::move(d); return *this; }
TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; }
TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; }
TestBuilder& TestBuilder::Wayland(bool w) { Ref().wayland = w; return *this; }
void Crafter::UnpackageTests(Configuration& cfg) {
for (Test& test : cfg.tests) test.config.packaging = Packaging::None;
}
TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
std::array<Configuration*, 1> one = { &projectCfg };
return RunTests(std::span<Configuration* const>(one), opts, projectArgs);
}
TestSummary Crafter::RunTests(std::span<Configuration* const> configurations, const RunTestsOptions& opts, std::span<const std::string_view> projectArgs) {
// Each of them once, however often the list names it: named twice, a
// configuration would have each of its tests built twice at once.
std::vector<Configuration*> distinct;
for (Configuration* cfg : configurations) {
if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg);
}
if (distinct.size() != configurations.size()) return RunTests(distinct, opts, projectArgs);
for (Configuration* cfg : configurations) UnpackageTests(*cfg);
// Multi-target sweep: when no --target= was given, the run covers every
// distinct target declared across the tests plus the host target.
// Lets a bare `crafter-build test` exercise cross-arch tests without the
// user having to know which targets exist. An explicit --target=X
// bypasses the sweep and runs that target only.
if (opts.targetFilter.empty()) {
// Keyed by the normalized triple so x86_64-pc-linux-gnu and
// x86_64-unknown-linux-gnu make one pass; the first spelling seen is
// the one shown and filtered on.
std::map<std::string, std::string> sweep;
sweep.emplace(NormalizeTarget(HostTarget()), HostTarget());
for (const Configuration* cfg : configurations) {
for (const Test& t : cfg->tests) {
if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target);
}
}
TestSummary aggregate;
for (const auto& [normalized, target] : sweep) {
RunTestsOptions perTarget = opts;
perTarget.targetFilter = target;
if (sweep.size() > 1) {
Progress::Clear();
std::println("\n=== target: {} ===", target);
}
TestSummary s = RunTests(configurations, perTarget, projectArgs);
aggregate.passed += s.passed;
aggregate.failed += s.failed;
aggregate.crashed += s.crashed;
aggregate.timedOut += s.timedOut;
aggregate.skipped += s.skipped;
for (auto& r : s.results) aggregate.results.push_back(std::move(r));
}
return aggregate;
}
TestSummary summary;
// Filter by target + glob, derive each Test's runner just-in-time. The
// runner is recomputed each sweep iteration (rather than once at AddTest
// time) because runnerOverride and FromEnv resolution depend on the
// run's options, which the project.cpp doesn't know about.
std::vector<Test*> filtered;
// The configuration that declares each of them, whose path its log is
// written under.
std::vector<const Configuration*> owners;
for (Configuration* cfg : configurations) {
for (auto& test : cfg->tests) {
if (!SameTarget(test.config.target, opts.targetFilter)) continue;
if (!MatchAny(opts.globs, test.config.name)) continue;
test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config));
if (opts.runnerOverride) {
if (auto r = TestRunner::FromSpec(*opts.runnerOverride)) {
test.runner = std::move(*r);
}
}
filtered.push_back(&test);
owners.push_back(cfg);
}
}
if (opts.listOnly) {
for (auto* t : filtered) {
std::println("{}", t->config.name);
}
return summary;
}
if (filtered.empty()) {
std::println("No tests matched.");
return summary;
}
// A test is built in a directory named after the test and what it is
// compiled as, not after the configuration that declares it, and its
// sources are tests/<name> whichever one does. Two configurations that
// each declare a test of one name, compiled alike, would have the two
// built in that one directory, at once when the run has the jobs for
// it, each with the dependencies and link flags of its own declaration.
// Neither is built: both fail, and say which configurations declare
// them. Only tests of different configurations are looked at: a test
// one configuration declares twice is as it was.
std::vector<std::string> clashes(filtered.size());
{
std::unordered_map<fs::path, std::vector<std::size_t>> builtInto;
for (std::size_t i = 0; i < filtered.size(); ++i) {
builtInto[fs::absolute(filtered[i]->config.PcmDir()).lexically_normal()].push_back(i);
}
for (const auto& [directory, sharing] : builtInto) {
std::vector<const Configuration*> declaring;
for (const std::size_t i : sharing) {
if (!std::ranges::contains(declaring, owners[i])) declaring.push_back(owners[i]);
}
if (declaring.size() < 2) continue;
std::string names;
for (const Configuration* cfg : declaring) {
if (!names.empty()) names += ", ";
names += cfg->name;
}
for (const std::size_t i : sharing) {
clashes[i] = std::format("{} each declare a test named {}, which would be built for each of them in {}: give each test a name of its own", names, filtered[i]->config.name, directory.string());
}
}
}
std::int32_t jobs = opts.jobs > 0
? opts.jobs
: std::max(1u, std::thread::hardware_concurrency());
jobs = std::min(jobs, static_cast<std::int32_t>(filtered.size()));
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
std::mutex printMutex;
std::mutex probeMutex;
std::unordered_map<std::string, bool> probeCache;
std::atomic<std::size_t> next{0};
std::vector<TestResult> results(filtered.size());
auto runnerAvailable = [&](const TestRunner& runner) -> bool {
if (runner.probe.empty()) return true;
std::lock_guard lk(probeMutex);
if (auto it = probeCache.find(runner.name); it != probeCache.end()) {
return it->second;
}
// RunCommandChecked captures and discards output internally, so probe
// specs don't need `> /dev/null 2>&1` (which doesn't translate to cmd).
bool ok = (RunCommandChecked(runner.probe).exitCode == 0);
probeCache[runner.name] = ok;
return ok;
};
auto worker = [&]() {
while (true) {
std::size_t i = next.fetch_add(1);
if (i >= filtered.size()) break;
Test& t = *filtered[i];
TestResult r;
r.name = t.config.name;
if (!clashes[i].empty()) {
r.outcome = TestOutcome::Fail;
r.output = clashes[i];
r.exitCode = -1;
{
std::lock_guard lk(printMutex);
PrintResult(r, t.runner.name);
}
results[i] = std::move(r);
continue;
}
// Declarative preconditions set via TestBuilder::Requires. Evaluated
// before the build so a missing tool/file/env turns into a Skip without
// paying the compile cost. Reports the first failure only — once one
// precondition is unmet the test couldn't run anyway, and a wall of
// "also missing X, also missing Y" buries the actionable root cause.
if (auto req = EvaluateRequires(t.requires_); !req.ok) {
r.outcome = TestOutcome::Skipped;
r.output = req.reason;
{
std::lock_guard lk(printMutex);
PrintResult(r, t.runner.name);
}
results[i] = std::move(r);
continue;
}
if (!runnerAvailable(t.runner)) {
// Hard-fail-unless-declared: if the runner depends on a tool
// (qemu-aarch64, wasmtime, wine, ...) and the test didn't say
// "tool:<that>" in requires, the missing runner is a Fail. The
// intent is to surface broken cross-arch CI configuration
// instead of letting it masquerade as a Skip; tests that
// legitimately may run without their runner have to opt in.
std::string tool = RunnerToolName(t.runner);
if (!tool.empty() && !RequiresMentionsTool(t.requires_, tool)) {
r.outcome = TestOutcome::Fail;
r.exitCode = -1;
r.output = std::format("runner '{}' unavailable and not declared in requires " "(add .Requires(\"tool:{}\") to permit skipping)", t.runner.name, tool);
} else {
r.outcome = TestOutcome::Skipped;
r.output = std::format("runner '{}' not available", t.runner.name);
}
{
std::lock_guard lk(printMutex);
PrintResult(r, t.runner.name);
}
results[i] = std::move(r);
continue;
}
BuildResult br;
try {
br = Build(t.config, depResults, depMutex);
} catch (const std::exception& e) {
r.outcome = TestOutcome::Fail;
r.output = std::format("build threw: {}", e.what());
r.exitCode = -1;
{
std::lock_guard lk(printMutex);
PrintResult(r, t.runner.name);
}
results[i] = std::move(r);
continue;
}
if (!br.result.empty()) {
r.outcome = TestOutcome::Fail;
r.output = std::format("build failed: {}", br.result);
r.exitCode = -1;
{
std::lock_guard lk(printMutex);
PrintResult(r, t.runner.name);
}
results[i] = std::move(r);
continue;
}
std::chrono::seconds timeout = opts.timeoutOverride.value_or(t.timeout);
// The file the link wrote, by the rule the staleness checks and -r
// use, which for a wasm32 executable is the <name>.wasm the link
// writes. A rule of its own here once added .exe for any Windows
// triple and nothing for wasm, so every wasm test was handed to
// wasmtime without the .wasm it was linked as.
fs::path binary = ExpectedOutput(t.config);
try {
r = RunSingleTest(t, binary, timeout, opts.compositorOverride);
} catch (const std::exception& e) {
r.outcome = TestOutcome::Fail;
r.output = std::format("runner threw: {}", e.what());
r.exitCode = -1;
}
// Beside the test's own log rather than in it: weston prints some
// 70 lines starting up, which would bury what the test said.
if (!r.compositorLog.empty()) {
if (const std::optional<fs::path> log = WriteLog(owners[i]->path, std::format("{}.compositor", r.name), r.compositorLog)) {
if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n');
r.output += std::format("the headless compositor's output is in {}\n", log->string());
}
}
if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) {
WriteLog(owners[i]->path, r.name, r.output);
}
{
std::lock_guard lk(printMutex);
PrintResult(r, t.runner.name);
}
results[i] = std::move(r);
}
};
std::vector<std::jthread> threads;
threads.reserve(jobs);
for (std::int32_t j = 0; j < jobs; ++j) {
threads.emplace_back(worker);
}
threads.clear(); // joins all jthreads
for (auto& r : results) {
switch (r.outcome) {
case TestOutcome::Pass: summary.passed++; break;
case TestOutcome::Fail: summary.failed++; break;
case TestOutcome::Crash: summary.crashed++; break;
case TestOutcome::Timeout: summary.timedOut++; break;
case TestOutcome::Skipped: summary.skipped++; break;
}
}
summary.results = std::move(results);
Progress::Clear();
std::print("\n");
std::vector<std::string> parts;
if (summary.passed) parts.push_back(std::format("{} passed", summary.passed));
if (summary.failed) parts.push_back(std::format("{} failed", summary.failed));
if (summary.crashed) parts.push_back(std::format("{} crashed", summary.crashed));
if (summary.timedOut) parts.push_back(std::format("{} timed out", summary.timedOut));
if (summary.skipped) parts.push_back(std::format("{} skipped", summary.skipped));
std::string joined;
for (std::size_t i = 0; i < parts.size(); ++i) {
if (i) joined += ", ";
joined += parts[i];
}
std::println("{}", joined);
return summary;
}