diff --git a/project.cpp b/project.cpp index be6f693..eb8f9ab 100644 --- a/project.cpp +++ b/project.cpp @@ -315,6 +315,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("WasmSysrootKey").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("RunSingleTestExit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("HeadlessCompositor").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("TestTemporaryDirectory").Dependencies({ CrafterBuildLib.get() }); // Loading a project file dlopens the project.so compiled from it, // which references Crafter:: symbols (HostTarget, Configuration // ctors) that have to be visible from the test exe — same wiring diff --git a/tests/HeadlessCompositor/main.cpp b/tests/HeadlessCompositor/main.cpp index 807df30..e14ae12 100644 --- a/tests/HeadlessCompositor/main.cpp +++ b/tests/HeadlessCompositor/main.cpp @@ -29,7 +29,8 @@ using namespace std::chrono_literals; // leaves goes the next time one is made. A test that does not set it, or a // run that names `host`, keeps the session's display. A test with no time // limit gives its compositor none, and one whose binary's path holds an '=' -// runs as any other. +// runs as any other. One that is given a TMPDIR as well, as RunTests gives +// every test one, runs with both. // // This binary plays every part. Without arguments it is the driver; the // harness starts it again as the compositor, which listens on a wayland-7 @@ -63,8 +64,8 @@ namespace { return value != nullptr ? std::string(value) : std::string(Unset); } - // The variables of a Wayland session. - constexpr std::array SessionVariables = { "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "DISPLAY", "XDG_RUNTIME_DIR" }; + // The variables of a Wayland session, and the TMPDIR a test is given. + constexpr std::array SessionVariables = { "WAYLAND_DISPLAY", "WAYLAND_SOCKET", "DISPLAY", "XDG_RUNTIME_DIR", "TMPDIR" }; void WriteFile(const fs::path& file, std::string_view content) { std::ofstream(file, std::ios::binary) << content; @@ -360,6 +361,31 @@ int main(int argc, char* argv[]) { Check(!directory.empty() && !fs::exists(directory), "which is removed afterwards"); } + // A test that sets wayland and is given a TMPDIR: the env prefix takes + // the TMPDIR beside what it unsets and sets for the display. + { + const fs::path state = stateDir("tmpdir"); + const fs::path given = stateDir("tmpdir-given"); + const TestResult r = RunSingleTest(MakeTest(true, "--client", state), self, 10s, FakeCompositorCommand(self, state), given); + Check(r.outcome == TestOutcome::Pass, std::format("a test that sets wayland and is given a TMPDIR passes: {}", r.output)); + std::map client = ReadEnvironment(state / "client.env"); + Check(client["TMPDIR"] == given.string(), std::format("and runs with that TMPDIR: {}", client["TMPDIR"])); + Check(client["WAYLAND_DISPLAY"] == ReadFile(state / "compositor.listening") && client["DISPLAY"] == Unset && client["WAYLAND_SOCKET"] == Unset, + std::format("and with its compositor's display alone: {}", client["WAYLAND_DISPLAY"])); + } + + // Under `host`, a test given a TMPDIR runs with it, beside the + // session's display. + { + const fs::path state = stateDir("host-tmpdir"); + const fs::path given = stateDir("host-tmpdir-given"); + const TestResult r = RunSingleTest(MakeTest(true, "--env", state), self, 10s, "host", given); + std::map client = ReadEnvironment(state / "client.env"); + Check(r.outcome == TestOutcome::Pass && client["TMPDIR"] == given.string(), std::format("under `host` a test given a TMPDIR runs with it: {}", client["TMPDIR"])); + Check(client["WAYLAND_DISPLAY"] == "crafter-build-session-display" && client["DISPLAY"] == ":4242" && client["WAYLAND_SOCKET"] == "4243", + "and with the session's display"); + } + { const fs::path state = stateDir("without"); const TestResult r = RunSingleTest(MakeTest(false, "--env", state), self, 10s, FakeCompositorCommand(self, state)); diff --git a/tests/RunSingleTestExit/main.cpp b/tests/RunSingleTestExit/main.cpp index 34f429f..970fde8 100644 --- a/tests/RunSingleTestExit/main.cpp +++ b/tests/RunSingleTestExit/main.cpp @@ -34,6 +34,8 @@ namespace { // 0 -> Pass // 77 -> Skipped (autoconf convention) // anything else -> Fail +// and that a binary whose path has an '=' in it runs, with a TMPDIR as +// RunTests gives it. int main() { fs::path dir = fs::temp_directory_path() / "crafter-build-run-single-test"; std::error_code ec; @@ -76,6 +78,23 @@ int main() { Check(r.outcome == TestOutcome::Pass, "Cmd-prefixed exit 0 -> Pass"); } + // A test whose binary's path has an '=' in it, given a TMPDIR, as + // RunTests gives every test one: env, which sets the TMPDIR, took that + // path for an assignment and, with no command left, exited 0, a pass + // for a test that never ran. + { + const fs::path equals = dir / "a=b"; + fs::create_directories(equals); + fs::create_directories(dir / "tmpdir"); + const fs::path marker = dir / "a=b-ran"; + const fs::path script = equals / "marker.sh"; + std::ofstream(script) << std::format("#!/bin/sh\necho ran > '{}'\nexit 3\n", marker.string()); + fs::permissions(script, fs::perms::owner_all, fs::perm_options::replace); + TestResult r = RunSingleTest(t, script, std::chrono::seconds(5), std::nullopt, dir / "tmpdir"); + Check(fs::exists(marker), "a test whose binary's path has an '=' in it runs"); + Check(r.outcome == TestOutcome::Fail && r.exitCode == 3, std::format("and its exit decides the outcome, got {}", r.exitCode)); + } + fs::remove_all(dir, ec); if (Failures > 0) { diff --git a/tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp b/tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp new file mode 100644 index 0000000..bc591ae --- /dev/null +++ b/tests/TestTemporaryDirectory/fixture/tests/probe/main.cpp @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +namespace fs = std::filesystem; + +// Writes the TMPDIR it was given and the directory fs::temp_directory_path() +// names to the file its first argument names, leaves a file in that +// directory, and exits with the status its second argument gives. With a +// third, `ran-long`, it first dates the run's directory, which holds its own, +// and every other crafter-build-tests-* directory beside that one two minutes +// back, as a test that ran that long leaves them; only when its own is in a +// run's directory. +int main(int argc, char* argv[]) { + if (argc != 3 && argc != 4) return 2; + const bool ranLong = argc == 4; + if (ranLong && std::string_view(argv[3]) != "ran-long") return 2; + const char* given = std::getenv("TMPDIR"); + const fs::path temporary = fs::temp_directory_path(); + std::ofstream(fs::path(argv[1])) << std::format("{}\n{}\n", given != nullptr ? given : "", temporary.string()); + std::ofstream(temporary / "left-behind") << "staged\n"; + if (ranLong && temporary.parent_path().filename().string().starts_with("crafter-build-tests-")) { + const auto then = fs::file_time_type::clock::now() - std::chrono::minutes(2); + std::error_code ec; + for (const fs::directory_entry& entry : fs::directory_iterator(temporary.parent_path().parent_path(), ec)) { + if (entry.path().filename().string().starts_with("crafter-build-tests-")) fs::last_write_time(entry.path(), then, ec); + } + } + return std::stoi(argv[2]); +} diff --git a/tests/TestTemporaryDirectory/main.cpp b/tests/TestTemporaryDirectory/main.cpp new file mode 100644 index 0000000..d58c395 --- /dev/null +++ b/tests/TestTemporaryDirectory/main.cpp @@ -0,0 +1,247 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +#include +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +// Each test runs with TMPDIR naming a directory of its own, /, in +// a directory RunTests makes for the run in the temp directory. Tests stage +// their fixtures under fixed names in fs::temp_directory_path(), and two runs +// at once used to share them, as every run does the machine's /tmp, and in +// crafter-build's Flatpak every sandbox the app's: one run's staged copy was +// written over or removed by the other's, and its test failed. The second +// test of one name in a run, from another configuration, gets -2. What +// a passing test leaves is removed when it ends, and so is the run's +// directory once every test passed; what a failing test leaves is kept, its +// output says where, and the run's directory with it, which a later run +// removes once a minute has passed since the run ended, and one that comes +// sooner leaves alone. That holds when the failing test ran for minutes, so +// that the run's directory had last changed long before the run ended: +// going by that change alone, the next run removed it at once. And one +// directory serves the run, every pass of its sweep over targets: a pass +// that made one of its own made it once the passes before had let go of +// theirs, and making it removed any of those that had not changed for a +// minute, a kept one after a pass that long among them. It is kept the +// moment a test keeps something in it, so that a later pass that throws, as +// one for a target whose runner is given wrong does, does not take it with +// it. Two failing tests of one name each have a log of their own, named as +// their TMPDIRs are, which says where what each left is kept. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // The two lines the probe recorded: the TMPDIR it was given, and the + // directory fs::temp_directory_path() named in it. + std::pair Recorded(const fs::path& file) { + std::ifstream in(file); + std::pair lines; + std::getline(in, lines.first); + std::getline(in, lines.second); + return lines; + } + + // A test of tests/probe/main.cpp, by the name given, with the arguments + // given, which that file describes. + Test& AddProbe(Configuration& owner, std::string_view name, std::vector args, bool second = false) { + Test test; + Configuration& c = test.config; + c.path = "./"; + c.name = name; + c.outputName = name; + c.target = HostTarget(); + c.type = ConfigurationType::Executable; + // Compiled otherwise than the first configuration's test of the same + // name, so that the two are not built into one directory, which the + // run refuses. + if (second) c.defines.push_back({"SECOND_PROBE", ""}); + std::array ifaces = {}; + std::array impls = { "tests/probe/main" }; + c.GetInterfacesAndImplementations(ifaces, impls); + test.args = std::move(args); + owner.tests.push_back(std::move(test)); + return owner.tests.back(); + } + + const TestResult* Find(const TestSummary& summary, std::string_view name) { + for (const TestResult& result : summary.results) { + if (result.name == name) return &result; + } + return nullptr; + } +} + +int main() { + // The runs below make their directories in a temp directory of this + // test's own, which TMPDIR names from here on, set while this is the + // only thread. What the test dates and removes is then in a directory it + // made, even where RunTests gives a probe no TMPDIR and the probe + // reports this test's own. + const fs::path staged = fs::temp_directory_path() / "crafter-build-test-temporary-directory"; + std::error_code ec; + fs::remove_all(staged, ec); + const fs::path records = staged / "records"; + const fs::path temp = staged / "runs"; + fs::create_directories(records); + fs::create_directories(temp); + setenv("TMPDIR", temp.c_str(), 1); + + // As a directory a run let go of looks, made a moment ago, so that the + // run's first look at the temp directory leaves it, and dated two + // minutes back by the failing probe during the first pass: one more pass + // that made a directory of its own would remove it, as it would a kept + // one after a pass of a minute. + const fs::path planted = temp / "crafter-build-tests-planted"; + fs::create_directories(planted); + + // AddProbe resolves tests/probe/main.cpp against the working directory, + // and the tests' outputs land in the fixture's own bin/ and build/. + fs::current_path(fs::current_path() / "tests" / "TestTemporaryDirectory" / "fixture"); + fs::remove_all("bin", ec); + fs::remove_all("build", ec); + + // One test at a time, in the order declared, so that the failing test + // is the last of the host's pass to make or remove anything in the run's + // directory: its own directory there, just before it starts. It then + // dates the run's directory two minutes back before it fails, as a test + // that ran that long leaves it. A test for another target makes a second + // pass, after the host's: the host's own triple, without its vendor, + // with x32 after it, x86_64-linux-gnux32 on an x86_64 glibc host, which + // is never the host's and sorts right after it. It is skipped before it + // is built. + const std::string otherTarget = std::format("{}x32", NormalizeTarget(HostTarget())); + Configuration first; + first.path = "./"; + first.name = "first"; + first.outputName = "first"; + first.target = HostTarget(); + AddProbe(first, "probe", { (records / "first-probe").string(), "0" }); + Configuration second; + second.path = "./"; + second.name = "second"; + second.outputName = "second"; + second.target = HostTarget(); + AddProbe(second, "probe", { (records / "second-probe").string(), "0" }, true); + AddProbe(second, "failing", { (records / "failing").string(), "1", "ran-long" }); + Test& elsewhere = AddProbe(second, "elsewhere", { (records / "elsewhere").string(), "0" }); + elsewhere.config.target = otherTarget; + elsewhere.requires_ = { "tool:crafter-build-no-such-tool" }; + std::array both = { &first, &second }; + RunTestsOptions serial; + serial.jobs = 1; + + const TestSummary run = RunTests(both, serial); + Check(run.passed == 2 && run.failed == 1 && run.skipped == 1, std::format("the run has two passes, one failure and one skip, got {}, {} and {}", run.passed, run.failed, run.skipped)); + Check(fs::is_directory(planted, ec), "the pass for the other target makes no directory of its own, which would have removed what the first pass left a minute old"); + + const auto [firstGiven, firstSeen] = Recorded(records / "first-probe"); + const auto [secondGiven, secondSeen] = Recorded(records / "second-probe"); + const auto [failingGiven, failingSeen] = Recorded(records / "failing"); + const fs::path directory = fs::path(firstGiven).parent_path(); + Check(firstGiven == firstSeen && secondGiven == secondSeen && failingGiven == failingSeen, + std::format("each test's fs::temp_directory_path() is the TMPDIR it was given: {} {} {}", firstSeen, secondSeen, failingSeen)); + const bool madeForRun = fs::equivalent(directory.parent_path(), temp, ec) && directory.filename().string().starts_with("crafter-build-tests-"); + Check(madeForRun, std::format("the run's directory is one made for it in the temp directory: {}", directory.string())); + Check(fs::path(firstGiven) == directory / "probe", std::format("a test's TMPDIR is named after it: {}", firstGiven)); + Check(fs::path(secondGiven) == directory / "probe-2", std::format("the second test of that name gets probe-2: {}", secondGiven)); + Check(fs::path(failingGiven) == directory / "failing", std::format("and every test of the run gets one in the same run directory: {}", failingGiven)); + + Check(!fs::exists(directory / "probe") && !fs::exists(directory / "probe-2"), "what a passing test left is removed"); + Check(fs::exists(directory / "failing" / "left-behind"), "what a failing test left is kept"); + const TestResult* failed = Find(run, "failing"); + Check(failed != nullptr && failed->output.contains((directory / "failing").string()), "and the failing test's output says where"); + const std::string log = [] { + std::ifstream in(fs::path("build") / "test-logs" / "failing.log"); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + }(); + Check(log.contains((directory / "failing").string()), "and so does its log"); + + // A run straight after leaves the failed run's directory alone, though + // the failing test dated it two minutes back; one that comes when it has + // not changed for a minute removes it. + RunTestsOptions passing; + passing.globs = { "probe" }; + std::array justFirst = { &first }; + const TestSummary again = RunTests(justFirst, passing); + Check(again.passed == 1 && again.failed == 0, std::format("the probe passes again, got {} passed, {} failed", again.passed, again.failed)); + const fs::path againDirectory = fs::path(Recorded(records / "first-probe").first).parent_path(); + Check(againDirectory != directory && fs::equivalent(againDirectory.parent_path(), temp, ec), std::format("a second run gets a directory of its own: {}", againDirectory.string())); + Check(!fs::exists(againDirectory), "and removes it when every test passed"); + Check(fs::exists(directory / "failing" / "left-behind"), "the failed run's directory outlives a run that comes at once, though its last test ran long"); + + // Only the failed run's directory is dated, and not a directory a probe + // reported that is not one: that check has failed already. + if (madeForRun) { + fs::last_write_time(directory, fs::file_time_type::clock::now() - std::chrono::minutes(2), ec); + const TestSummary later = RunTests(justFirst, passing); + Check(later.passed == 1, "the probe passes a third time"); + Check(!fs::exists(directory), "a later run removes the failed run's directory once it has not changed for a minute"); + } + + // A run whose later pass throws, as one does where + // CRAFTER_BUILD_RUNNER_ gives the other target's runner wrong, + // keeps what its first pass kept all the same: the failing test's output + // has said where it is. Set while this is the only thread, under the + // name FromEnv reads, '-' and '.' made '_'. + std::string runnerVariable = std::format("CRAFTER_BUILD_RUNNER_{}", otherTarget); + std::ranges::replace(runnerVariable, '-', '_'); + std::ranges::replace(runnerVariable, '.', '_'); + setenv(runnerVariable.c_str(), "no-such-runner", 1); + bool threw = false; + try { + RunTests(both, serial); + } catch (const std::exception&) { + threw = true; + } + unsetenv(runnerVariable.c_str()); + Check(threw, "a run whose runner for the other target is given wrong throws"); + const fs::path thrownDirectory = fs::path(Recorded(records / "failing").first).parent_path(); + Check(thrownDirectory != directory && fs::exists(thrownDirectory / "failing" / "left-behind"), + std::format("and keeps what its first pass kept: {}", thrownDirectory.string())); + + // Two failing tests of one name in a run, as two configurations may + // each declare one: each one's log is its own, named as its TMPDIR is, + // twin-2 for the second, and says where what it left is kept. With one + // log for both, the second's was written over the first's. Each check + // reads to the end of the line: twin's path is the start of twin-2's. + Configuration one; + one.path = "./"; + one.name = "one"; + one.outputName = "one"; + one.target = HostTarget(); + AddProbe(one, "twin", { (records / "twin").string(), "1" }); + Configuration other; + other.path = "./"; + other.name = "other"; + other.outputName = "other"; + other.target = HostTarget(); + AddProbe(other, "twin", { (records / "twin-2").string(), "1" }, true); + std::array twins = { &one, &other }; + RunTests(twins, serial); + const auto logOf = [](std::string_view name) { + std::ifstream in(fs::path("build") / "test-logs" / std::format("{}.log", name)); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + }; + const std::string firstTwin = Recorded(records / "twin").first; + const std::string secondTwin = Recorded(records / "twin-2").first; + Check(!firstTwin.empty() && logOf("twin").contains(std::format("kept in {}\n", firstTwin)), + std::format("the first of two failing tests of one name has a log of its own, which says where it kept what it left: {}", firstTwin)); + Check(!secondTwin.empty() && logOf("twin-2").contains(std::format("kept in {}\n", secondTwin)), + std::format("and so has the second, twin-2.log: {}", secondTwin)); + + fs::remove_all(staged, ec); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +}