Nostro/tests/Support/Check.inc
2026-11-01 18:35:23 +01:00

67 lines
2.5 KiB
PHP

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// What every test checks with, included after `import std;`. A failed check prints where and why and makes the test
// exit 1; the test goes on, so one run lists every failure.
namespace Test {
std::int32_t failures = 0;
void Check(bool condition, std::string_view what, std::source_location where = std::source_location::current()) {
if(!condition) {
std::println("FAIL {}:{}: {}", where.file_name(), where.line(), what);
failures++;
}
}
template<typename Actual, typename Expected>
void Equal(const Actual& actual, const Expected& expected, std::string_view what, std::source_location where = std::source_location::current()) {
if(!(actual == expected)) {
std::println("FAIL {}:{}: {}: expected '{}', got '{}'", where.file_name(), where.line(), what, expected, actual);
failures++;
}
}
// `code` throws an E whose what() contains `part`.
template<typename E = std::exception, typename Code>
void Throws(Code&& code, std::string_view part, std::string_view what, std::source_location where = std::source_location::current()) {
try {
code();
} catch(const E& e) {
if(!std::string_view(e.what()).contains(part)) {
std::println("FAIL {}:{}: {}: the error '{}' does not say '{}'", where.file_name(), where.line(), what, e.what(), part);
failures++;
}
return;
} catch(...) {
std::println("FAIL {}:{}: {}: threw something else", where.file_name(), where.line(), what);
failures++;
return;
}
std::println("FAIL {}:{}: {}: did not throw", where.file_name(), where.line(), what);
failures++;
}
std::int32_t Result() {
if(failures == 0) {
std::println("all checks passed");
return 0;
}
std::println("{} check(s) failed", failures);
return 1;
}
// A fresh directory for one test's files, deleted with everything in it when the test ends.
struct Directory {
std::filesystem::path path;
explicit Directory(std::string_view name) : path(std::filesystem::temp_directory_path() / std::format("nostro-{}-{}", name, std::random_device()())) {
std::filesystem::create_directories(path);
}
~Directory() {
std::error_code ignored;
std::filesystem::remove_all(path, ignored);
}
};
}