feat(Testing): add per-run owned reporters, strict config validation, FailureCapture, subprocess isolation, and deterministic property/schedule harness (M-TESTING-02, M-TESTING-03)

This commit is contained in:
faumaray committed 2026-11-24 09:36:59 +03:00
1 parent 1b3331e3a8
commit de8a981893
11 files changed
+1712 -55

No files matched your search

+2
View File
@@ -44,6 +44,8 @@ namespace Void::Testing::Detail
}
void handle_assertion(AssertionResult result);
[[nodiscard]] std::size_t stray_assertion_count() noexcept;
void reset_stray_assertion_count() noexcept;
struct RequireFailure : std::runtime_error {
using std::runtime_error::runtime_error;
+110
View File
@@ -0,0 +1,110 @@
#pragma once
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Config.hpp>
#include <cstddef>
#include <exception>
#include <string>
#include <utility>
#include <vector>
namespace Void::Testing
{
// Captures Void::Testing assertions and Require/exception aborts within a
// bounded local TestResult without mutating any enclosing active test context.
class FailureCapture
{
public:
FailureCapture() noexcept
: prev_result_(Detail::TestContext::current().current_result)
, prev_should_abort_(Detail::TestContext::current().should_abort)
{
Detail::TestContext::current().current_result = &local_;
Detail::TestContext::current().should_abort = false;
}
~FailureCapture()
{
Detail::TestContext::current().current_result = prev_result_;
Detail::TestContext::current().should_abort = prev_should_abort_;
}
FailureCapture(const FailureCapture&) = delete;
FailureCapture& operator=(const FailureCapture&) = delete;
FailureCapture(FailureCapture&&) = delete;
FailureCapture& operator=(FailureCapture&&) = delete;
template <typename Fn>
[[nodiscard]] bool run(Fn&& fn)
{
local_ = TestResult{};
try {
std::forward<Fn>(fn)();
} catch (const Detail::RequireFailure&) {
if (local_.state != TestState::Skipped) {
local_.state = TestState::Failed;
}
} catch (const std::exception& e) {
local_.state = TestState::Failed;
local_.crash_info = std::string{"Unhandled exception: "} + e.what();
} catch (...) {
local_.state = TestState::Failed;
local_.crash_info = "Unhandled unknown exception";
}
if (local_.state != TestState::Skipped) {
bool any_fail = !local_.crash_info.empty();
if (!any_fail) {
for (const auto& a : local_.assertions) {
if (!a.passed) {
any_fail = true;
break;
}
}
}
if (any_fail) {
local_.state = TestState::Failed;
}
}
return passed();
}
[[nodiscard]] bool passed() const noexcept
{
return local_.state == TestState::Passed;
}
[[nodiscard]] bool failed() const noexcept
{
return local_.state == TestState::Failed || local_.state == TestState::Crashed;
}
[[nodiscard]] bool skipped() const noexcept
{
return local_.state == TestState::Skipped;
}
[[nodiscard]] bool aborted() const noexcept
{
return local_.state == TestState::Failed && !local_.assertions.empty() &&
(local_.assertions.back().kind == AssertKind::Require ||
local_.assertions.back().kind == AssertKind::Assert);
}
[[nodiscard]] bool truncated() const noexcept { return local_.assertions_truncated; }
[[nodiscard]] std::size_t dropped_assertions() const noexcept { return local_.dropped_assertions; }
[[nodiscard]] const std::vector<AssertionResult>& assertions() const noexcept
{
return local_.assertions;
}
[[nodiscard]] const TestResult& result() const noexcept { return local_; }
private:
TestResult* prev_result_{nullptr};
bool prev_should_abort_{false};
TestResult local_{};
};
} // namespace Void::Testing
+11
View File
@@ -12,6 +12,9 @@
namespace Void::Testing
{
inline constexpr std::size_t kMaxRetainedAssertionsPerTest = 1000;
inline constexpr std::size_t kMaxDiagnosticBytesPerTest = 1024ULL * 1024ULL;
enum class AssertKind : uint8_t { Expect, Require, Assert };
enum class TestState : uint8_t { Passed, Failed, Skipped, Crashed };
@@ -55,6 +58,10 @@ namespace Void::Testing
std::string crash_info;
std::string stacktrace;
std::vector<std::string> tags;
bool assertions_truncated{false};
std::size_t dropped_assertions{0};
std::size_t diagnostic_bytes{0};
std::string cleanup_error;
};
struct SuiteResult {
@@ -70,6 +77,7 @@ namespace Void::Testing
int skipped{0};
int crashed{0};
int total{0};
std::string config_error;
};
struct RunConfig {
@@ -84,9 +92,12 @@ namespace Void::Testing
bool no_color{false};
bool shuffle{false};
bool show_help{false};
bool allow_empty{false};
unsigned repeat{1};
unsigned random_seed{0};
unsigned parallel_threads{0}; // 0 = sequential
std::string parse_error;
std::string selftest_child;
};
} // namespace Void::Testing
+494
View File
@@ -0,0 +1,494 @@
#pragma once
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <expected>
#include <functional>
#include <limits>
#include <optional>
#include <random>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Testing
{
struct ReplayToken {
std::uint64_t seed{0x9E3779B97F4A7C15ULL};
std::uint32_t generator_version{1};
std::uint64_t case_index{0};
[[nodiscard]] constexpr bool operator==(const ReplayToken&) const noexcept = default;
};
// Frozen version-1 deterministic PRNG backed by SplitMix64 seeding + mt19937_64
// with standard-library-independent unbiased rejection sampling.
class DeterministicRng
{
public:
explicit DeterministicRng(ReplayToken token) noexcept
: token_(token)
, engine_(mix_seed_v1(token.seed, token.case_index))
{
}
[[nodiscard]] static constexpr std::uint64_t mix_seed_v1(
std::uint64_t seed, std::uint64_t case_index) noexcept
{
std::uint64_t z = seed ^ (case_index * 0x9E3779B97F4A7C15ULL);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
return z ^ (z >> 31);
}
[[nodiscard]] const ReplayToken& token() const noexcept { return token_; }
[[nodiscard]] std::uint64_t next_u64() noexcept
{
return engine_();
}
// Returns uniform integer in [0, bound - 1] via rejection sampling.
[[nodiscard]] std::uint64_t next_bounded(std::uint64_t bound) noexcept
{
if (bound <= 1) {
return 0;
}
const std::uint64_t threshold = (0ULL - bound) % bound;
for (;;) {
const std::uint64_t r = next_u64();
if (r >= threshold) {
return r % bound;
}
}
}
[[nodiscard]] std::int64_t next_int(std::int64_t lo, std::int64_t hi) noexcept
{
if (lo >= hi) {
return lo;
}
const std::uint64_t ulo = static_cast<std::uint64_t>(lo);
const std::uint64_t uhi = static_cast<std::uint64_t>(hi);
const std::uint64_t span = uhi - ulo;
if (span == std::numeric_limits<std::uint64_t>::max()) {
return static_cast<std::int64_t>(next_u64());
}
const std::uint64_t pick = next_bounded(span + 1ULL);
return static_cast<std::int64_t>(ulo + pick);
}
[[nodiscard]] bool next_bool() noexcept
{
return (next_u64() & 1ULL) != 0ULL;
}
[[nodiscard]] std::vector<std::byte> next_bytes(std::size_t max_len)
{
const std::size_t len =
static_cast<std::size_t>(next_bounded(max_len + 1ULL));
std::vector<std::byte> out(len);
for (std::size_t i = 0; i < len; ++i) {
out[i] = static_cast<std::byte>(next_u64() & 0xFFULL);
}
return out;
}
[[nodiscard]] std::vector<int> next_ints(
std::size_t max_len, int lo, int hi)
{
const std::size_t len =
static_cast<std::size_t>(next_bounded(max_len + 1ULL));
std::vector<int> out;
out.reserve(len);
for (std::size_t i = 0; i < len; ++i) {
out.push_back(static_cast<int>(next_int(lo, hi)));
}
return out;
}
private:
ReplayToken token_{};
std::mt19937_64 engine_;
};
enum class PropertyStatus {
passed,
failed,
inconclusive
};
struct PropertyOptions {
unsigned cases{256};
unsigned max_size{64};
unsigned max_shrinks{1000};
unsigned max_steps{10000};
unsigned max_discard_factor{10};
std::chrono::nanoseconds time_budget{std::chrono::seconds{5}};
};
template <typename T>
struct PropertyResult {
PropertyStatus status{PropertyStatus::passed};
ReplayToken replay{};
unsigned cases_executed{0};
unsigned discards{0};
unsigned shrink_steps{0};
std::optional<T> original_failure{};
std::optional<T> minimal_failure{};
std::vector<T> shrink_path{};
std::string message{};
};
namespace Detail
{
template <typename T>
struct UnwrapOptional {
using type = T;
static constexpr bool is_optional = false;
};
template <typename U>
struct UnwrapOptional<std::optional<U>> {
using type = U;
static constexpr bool is_optional = true;
};
[[nodiscard]] inline std::chrono::nanoseconds elapsed_since(
const Void::Time::MonotonicClock& clock,
Void::Time::MonotonicClock::time_point start) noexcept
{
const auto now = clock.now();
return (now > start)
? std::chrono::duration_cast<std::chrono::nanoseconds>(now - start)
: std::chrono::nanoseconds{0};
}
} // namespace Detail
template <typename GeneratorFn, typename PredicateFn, typename ShrinkFn>
requires std::invocable<
ShrinkFn,
const typename Detail::UnwrapOptional<
std::remove_cvref_t<std::invoke_result_t<GeneratorFn, DeterministicRng&>>>::type&>
[[nodiscard]] auto check_property(
GeneratorFn&& gen,
PredicateFn&& pred,
ShrinkFn&& shrink,
const PropertyOptions& opts = {},
ReplayToken base_token = {},
const Void::Time::MonotonicClock* clock = nullptr)
{
using GenRaw = std::remove_cvref_t<std::invoke_result_t<GeneratorFn, DeterministicRng&>>;
using T = typename Detail::UnwrapOptional<GenRaw>::type;
PropertyResult<T> result;
result.replay = base_token;
if (base_token.generator_version != 1) {
result.status = PropertyStatus::inconclusive;
result.message = "Unsupported ReplayToken generator_version";
return result;
}
const Void::Time::MonotonicClock& clk =
clock ? *clock : Void::Time::SystemMonotonicClock::instance();
const auto start_tp = clk.now();
unsigned total_steps = 0;
const unsigned max_discards =
(opts.cases == 0 || opts.max_discard_factor == 0)
? 0
: (opts.cases <= std::numeric_limits<unsigned>::max() / opts.max_discard_factor
? opts.cases * opts.max_discard_factor
: std::numeric_limits<unsigned>::max());
for (unsigned case_idx = 0;
result.cases_executed < opts.cases;
++case_idx) {
if (total_steps >= opts.max_steps ||
Detail::elapsed_since(clk, start_tp) >= opts.time_budget) {
result.status = PropertyStatus::inconclusive;
result.message = "Property step or time budget exhausted";
return result;
}
++total_steps;
ReplayToken case_tok{base_token.seed, base_token.generator_version, case_idx};
DeterministicRng rng{case_tok};
std::optional<T> value_opt;
if constexpr (Detail::UnwrapOptional<GenRaw>::is_optional) {
value_opt = std::forward<GeneratorFn>(gen)(rng);
} else {
value_opt.emplace(std::forward<GeneratorFn>(gen)(rng));
}
if (!value_opt.has_value()) {
++result.discards;
if (result.discards > max_discards) {
result.status = PropertyStatus::inconclusive;
result.message = "Property generator discard budget exceeded";
return result;
}
continue;
}
using PredRaw = std::remove_cvref_t<std::invoke_result_t<PredicateFn, const T&>>;
std::optional<bool> ok;
if constexpr (Detail::UnwrapOptional<PredRaw>::is_optional) {
ok = std::forward<PredicateFn>(pred)(*value_opt);
} else {
ok = static_cast<bool>(std::forward<PredicateFn>(pred)(*value_opt));
}
if (!ok.has_value()) {
++result.discards;
if (result.discards > max_discards) {
result.status = PropertyStatus::inconclusive;
result.message = "Property precondition discard budget exceeded";
return result;
}
continue;
}
++result.cases_executed;
if (*ok) {
continue;
}
result.status = PropertyStatus::failed;
result.replay = case_tok;
result.original_failure = *value_opt;
result.minimal_failure = std::move(*value_opt);
result.message = "Property falsified";
// Deterministic shrinking up to max_shrinks / max_steps / time_budget.
while (result.shrink_steps < opts.max_shrinks &&
total_steps < opts.max_steps &&
Detail::elapsed_since(clk, start_tp) < opts.time_budget) {
const auto candidates = shrink(*result.minimal_failure);
bool shrunk_once = false;
for (const auto& cand : candidates) {
if (total_steps >= opts.max_steps ||
Detail::elapsed_since(clk, start_tp) >= opts.time_budget) {
break;
}
++total_steps;
std::optional<bool> cand_ok;
if constexpr (Detail::UnwrapOptional<PredRaw>::is_optional) {
cand_ok = pred(cand);
} else {
cand_ok = static_cast<bool>(pred(cand));
}
if (cand_ok.has_value() && !(*cand_ok)) {
result.minimal_failure = cand;
result.shrink_path.push_back(cand);
++result.shrink_steps;
shrunk_once = true;
break;
}
}
if (!shrunk_once) {
break;
}
}
return result;
}
result.status = PropertyStatus::passed;
return result;
}
template <typename GeneratorFn, typename PredicateFn>
[[nodiscard]] auto check_property(
GeneratorFn&& gen,
PredicateFn&& pred,
const PropertyOptions& opts = {},
ReplayToken base_token = {},
const Void::Time::MonotonicClock* clock = nullptr)
{
using GenRaw = std::remove_cvref_t<std::invoke_result_t<GeneratorFn, DeterministicRng&>>;
using T = typename Detail::UnwrapOptional<GenRaw>::type;
auto no_shrink = [](const T&) -> std::vector<T> { return {}; };
return check_property(
std::forward<GeneratorFn>(gen),
std::forward<PredicateFn>(pred),
no_shrink,
opts,
base_token,
clock);
}
template <typename GeneratorFn, typename PredicateFn>
[[nodiscard]] bool replay_property_case(
GeneratorFn&& gen,
PredicateFn&& pred,
ReplayToken token)
{
DeterministicRng rng{token};
auto val = std::forward<GeneratorFn>(gen)(rng);
return static_cast<bool>(std::forward<PredicateFn>(pred)(val));
}
struct ScheduleEvent {
std::uint64_t step{0};
std::uint64_t action_id{0};
std::string label{};
std::int64_t clock_ns{0};
std::size_t choice_index{0};
std::size_t ready_count{0};
};
// Deterministic single-step action & timer harness using Void::Time::ManualClock.
class DeterministicRun
{
public:
explicit DeterministicRun(Void::Time::ManualClock::time_point initial = {}) noexcept
: clock_(initial)
{
}
[[nodiscard]] const Void::Time::ManualClock& clock() const noexcept { return clock_; }
[[nodiscard]] Void::Time::ManualClock& clock() noexcept { return clock_; }
std::uint64_t schedule(std::string label, std::function<void()> fn)
{
const std::uint64_t id = next_id_++;
ready_.push_back(Action{id, std::move(label), std::move(fn)});
return id;
}
std::uint64_t schedule_after(
std::chrono::nanoseconds delay,
std::string label,
std::function<void()> fn)
{
const std::uint64_t id = next_id_++;
const auto fire_at =
(delay.count() <= 0) ? clock_.now() : (clock_.now() + delay);
if (fire_at <= clock_.now()) {
ready_.push_back(Action{id, std::move(label), std::move(fn)});
return id;
}
timers_.push_back(Timer{fire_at, id, std::move(label), std::move(fn)});
return id;
}
std::size_t advance_clock(std::chrono::nanoseconds delta)
{
(void)clock_.advance(delta);
return promote_due_timers();
}
bool step()
{
return step_choice(0);
}
bool step_choice(std::size_t ready_index)
{
(void)promote_due_timers();
if (ready_.empty() || ready_index >= ready_.size()) {
return false;
}
const std::size_t rc = ready_.size();
Action act = std::move(ready_[ready_index]);
ready_.erase(ready_.begin() + static_cast<std::ptrdiff_t>(ready_index));
const std::int64_t now_ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(
clock_.now().time_since_epoch())
.count();
trace_.push_back(ScheduleEvent{
.step = next_step_++,
.action_id = act.id,
.label = act.label,
.clock_ns = now_ns,
.choice_index = ready_index,
.ready_count = rc,
});
if (act.fn) {
act.fn();
}
return true;
}
[[nodiscard]] std::expected<std::size_t, std::string>
run_until_idle(std::size_t max_steps = 10000)
{
std::size_t ran = 0;
for (;;) {
(void)promote_due_timers();
if (ready_.empty()) {
return ran;
}
if (ran >= max_steps) {
return std::unexpected{
"DeterministicRun exceeded max_steps limit"};
}
if (!step()) {
return ran;
}
++ran;
}
}
[[nodiscard]] std::size_t ready_count() const noexcept { return ready_.size(); }
[[nodiscard]] std::size_t timer_count() const noexcept { return timers_.size(); }
[[nodiscard]] const std::vector<ScheduleEvent>& trace() const noexcept { return trace_; }
private:
struct Action {
std::uint64_t id{0};
std::string label{};
std::function<void()> fn{};
};
struct Timer {
Void::Time::ManualClock::time_point fire_at{};
std::uint64_t id{0};
std::string label{};
std::function<void()> fn{};
};
std::size_t promote_due_timers()
{
const auto now = clock_.now();
std::vector<Timer> due;
std::vector<Timer> remaining;
remaining.reserve(timers_.size());
for (auto& t : timers_) {
if (t.fire_at <= now) {
due.push_back(std::move(t));
} else {
remaining.push_back(std::move(t));
}
}
timers_ = std::move(remaining);
std::sort(due.begin(), due.end(), [](const Timer& a, const Timer& b) {
if (a.fire_at != b.fire_at) {
return a.fire_at < b.fire_at;
}
return a.id < b.id;
});
for (auto& t : due) {
ready_.push_back(Action{t.id, std::move(t.label), std::move(t.fn)});
}
return due.size();
}
Void::Time::ManualClock clock_;
std::uint64_t next_id_{1};
std::uint64_t next_step_{0};
std::deque<Action> ready_{};
std::vector<Timer> timers_{};
std::vector<ScheduleEvent> trace_{};
};
} // namespace Void::Testing
+1
View File
@@ -16,6 +16,7 @@ namespace Void::Testing
}
RunConfig parse_args(int argc, char** argv);
RunResult run(const RunConfig& config);
TestResult execute_case(TestCase& test_case);
int main(int argc, char** argv);
private:
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <span>
#include <string>
#include <string_view>
namespace Void::Testing
{
struct ProcessTestOptions {
std::chrono::milliseconds timeout{60000};
std::size_t max_output_bytes{1024ULL * 1024ULL};
};
enum class ProcessOutcome {
passed,
failed,
crashed,
timed_out,
infrastructure_error
};
struct ProcessTestResult {
ProcessOutcome outcome{ProcessOutcome::infrastructure_error};
int exit_code{-1};
int term_signal{0};
std::string stdout_captured{};
std::string stderr_captured{};
bool stdout_truncated{false};
bool stderr_truncated{false};
std::string diagnostic{};
};
[[nodiscard]] std::string current_executable_path();
[[nodiscard]] ProcessTestResult run_isolated_subprocess(
std::string_view executable,
std::span<const std::string> args = {},
ProcessTestOptions options = {});
} // namespace Void::Testing
+55 -13
View File
@@ -1,17 +1,59 @@
#include <Void/Testing/Assert.hpp>
namespace Void::Testing::Detail {
void handle_assertion(AssertionResult result) {
#include <atomic>
namespace Void::Testing::Detail
{
namespace
{
std::atomic<std::size_t> g_stray_assertions{0};
} // namespace
std::size_t stray_assertion_count() noexcept
{
return g_stray_assertions.load(std::memory_order_acquire);
}
void reset_stray_assertion_count() noexcept
{
g_stray_assertions.store(0, std::memory_order_release);
}
void handle_assertion(AssertionResult result)
{
auto& ctx = TestContext::current();
if (ctx.current_result) {
ctx.current_result->assertions.push_back(std::move(result));
const auto& last = ctx.current_result->assertions.back();
if (!last.passed) {
ctx.current_result->state = TestState::Failed;
if (last.kind == AssertKind::Require || last.kind == AssertKind::Assert) {
ctx.should_abort = true;
throw RequireFailure{last.message};
}
}
if (!ctx.current_result) {
g_stray_assertions.fetch_add(1, std::memory_order_acq_rel);
return;
}
TestResult* tr = ctx.current_result;
const bool passed = result.passed;
const AssertKind kind = result.kind;
std::string abort_msg = result.message;
if (!passed) {
tr->state = TestState::Failed;
}
const std::size_t entry_bytes =
result.expression.size() +
result.expected_repr.size() +
result.actual_repr.size() +
result.message.size() + 64;
if (tr->assertions.size() < kMaxRetainedAssertionsPerTest &&
tr->diagnostic_bytes + entry_bytes <= kMaxDiagnosticBytesPerTest) {
tr->diagnostic_bytes += entry_bytes;
tr->assertions.push_back(std::move(result));
} else {
tr->assertions_truncated = true;
tr->dropped_assertions += 1;
}
if (!passed && (kind == AssertKind::Require || kind == AssertKind::Assert)) {
ctx.should_abort = true;
throw RequireFailure{abort_msg};
}
}
} // namespace Void::Testing::Detail
} // namespace Void::Testing::Detail
+271 -42
View File
@@ -37,50 +37,146 @@
#endif
#include <algorithm>
#include <chrono>
#include <csignal>
#include <cstdlib>
#include <format>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <random>
#include <regex>
#include <thread>
#include <unordered_map>
namespace Void::Testing
{
namespace
{
class OwningJUnitReporter final : public Reporter
{
public:
OwningJUnitReporter(std::unique_ptr<std::ofstream> stream,
std::string* write_err_out)
: stream_(std::move(stream))
, inner_(*stream_)
, write_err_out_(write_err_out)
{
}
void on_run_start(const RunConfig& c, int n) override { inner_.on_run_start(c, n); }
void on_suite_start(const std::string& s, int n) override { inner_.on_suite_start(s, n); }
void on_test_start(const TestCase& t) override { inner_.on_test_start(t); }
void on_test_end(const TestResult& r) override { inner_.on_test_end(r); }
void on_suite_end(const SuiteResult& s) override { inner_.on_suite_end(s); }
void on_run_end(const RunResult& r) override
{
inner_.on_run_end(r);
if (stream_) {
stream_->flush();
if (!stream_->good() && write_err_out_ != nullptr &&
write_err_out_->empty()) {
*write_err_out_ = "Failed while writing JUnit report";
}
}
}
private:
std::unique_ptr<std::ofstream> stream_;
JUnitReporter inner_;
std::string* write_err_out_{nullptr};
};
struct ContextRestorer {
Detail::TestContext saved;
ContextRestorer() : saved(Detail::TestContext::current()) {}
~ContextRestorer() { Detail::TestContext::current() = saved; }
ContextRestorer(const ContextRestorer&) = delete;
ContextRestorer& operator=(const ContextRestorer&) = delete;
};
[[nodiscard]] bool parse_unsigned_strict(const std::string& text,
unsigned& out) noexcept
{
if (text.empty() || text[0] == '-') {
return false;
}
try {
std::size_t pos = 0;
const unsigned long val = std::stoul(text, &pos, 10);
if (pos != text.size() || val > std::numeric_limits<unsigned>::max()) {
return false;
}
out = static_cast<unsigned>(val);
return true;
} catch (...) {
return false;
}
}
} // namespace
RunConfig Runner::parse_args(int argc, char** argv)
{
RunConfig config;
auto need_val = [&](const std::string& flag, int& i, std::string& out) -> bool {
if (i + 1 >= argc) {
if (config.parse_error.empty()) {
config.parse_error = std::format("Missing value for option {}", flag);
}
return false;
}
out = argv[++i];
return true;
};
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if ((arg == "--filter" || arg == "--suite" ||
arg == "--reporter" || arg == "--output" ||
arg == "--tag" || arg == "--seed" || arg == "--repeat" ||
arg == "--log-file" || arg == "--parallel") &&
i + 1 < argc) {
std::string val = argv[++i];
if (arg == "--filter") {
config.filter_pattern = val;
} else if (arg == "--suite") {
config.suite_filter = val;
} else if (arg == "--reporter") {
config.reporter = val;
} else if (arg == "--output") {
config.output_file = val;
} else if (arg == "--tag") {
config.tag_filter = val;
} else if (arg == "--log-file") {
config.log_file = val;
} else if (arg == "--seed") {
config.shuffle = true;
config.random_seed =
static_cast<unsigned>(std::stoul(val));
} else if (arg == "--repeat") {
config.repeat = static_cast<unsigned>(std::stoul(val));
} else if (arg == "--parallel") {
config.parallel_threads =
static_cast<unsigned>(std::stoul(val));
if (arg == "--filter") {
(void)need_val(arg, i, config.filter_pattern);
} else if (arg == "--suite") {
(void)need_val(arg, i, config.suite_filter);
} else if (arg == "--reporter") {
(void)need_val(arg, i, config.reporter);
} else if (arg == "--output") {
(void)need_val(arg, i, config.output_file);
} else if (arg == "--tag") {
(void)need_val(arg, i, config.tag_filter);
} else if (arg == "--log-file") {
(void)need_val(arg, i, config.log_file);
} else if (arg == "--selftest-child") {
(void)need_val(arg, i, config.selftest_child);
} else if (arg == "--seed") {
std::string val;
if (need_val(arg, i, val)) {
unsigned parsed = 0;
if (!parse_unsigned_strict(val, parsed)) {
config.parse_error = std::format("Invalid --seed value: {}", val);
} else {
config.shuffle = true;
config.random_seed = parsed;
}
}
} else if (arg == "--repeat") {
std::string val;
if (need_val(arg, i, val)) {
unsigned parsed = 0;
if (!parse_unsigned_strict(val, parsed)) {
config.parse_error = std::format("Invalid --repeat value: {}", val);
} else {
config.repeat = parsed;
}
}
} else if (arg == "--parallel") {
std::string val;
if (need_val(arg, i, val)) {
unsigned parsed = 0;
if (!parse_unsigned_strict(val, parsed)) {
config.parse_error = std::format("Invalid --parallel value: {}", val);
} else {
config.parallel_threads = parsed;
}
}
} else if (arg == "--help") {
config.show_help = true;
@@ -90,10 +186,16 @@ namespace Void::Testing
config.verbose = true;
} else if (arg == "--no-color") {
config.no_color = true;
} else if (arg == "--allow-empty") {
config.allow_empty = true;
} else if (arg == "--shuffle") {
config.shuffle = true;
std::random_device rd;
config.random_seed = rd();
} else if (!arg.empty() && arg[0] == '-') {
if (config.parse_error.empty()) {
config.parse_error = std::format("Unknown option: {}", arg);
}
}
}
return config;
@@ -142,14 +244,19 @@ namespace Void::Testing
std::unique_ptr<Reporter> Runner::create_reporter(const RunConfig& config)
{
if (config.reporter == "junit") {
static std::ofstream file{config.output_file.empty()
? "test_results.xml"
: config.output_file};
return std::make_unique<JUnitReporter>(file);
const std::string path =
config.output_file.empty() ? "test_results.xml" : config.output_file;
auto file = std::make_unique<std::ofstream>(path, std::ios::out | std::ios::trunc);
return std::make_unique<OwningJUnitReporter>(std::move(file), nullptr);
}
return std::make_unique<ConsoleReporter>(std::cout, !config.no_color);
}
TestResult Runner::execute_case(TestCase& test_case)
{
return execute_test(test_case);
}
TestResult Runner::execute_test(TestCase& test_case)
{
TestResult result;
@@ -163,6 +270,7 @@ namespace Void::Testing
: test_case.skip_reason;
return result;
}
ContextRestorer ctx_restorer;
Detail::TestContext::current().current_result = &result;
Detail::TestContext::current().should_abort = false;
@@ -214,7 +322,6 @@ namespace Void::Testing
auto end = std::chrono::high_resolution_clock::now();
result.duration = end - start;
Detail::uninstall_signal_handlers();
Detail::TestContext::current().current_result = nullptr;
if (result.state != TestState::Skipped &&
result.state != TestState::Crashed) {
@@ -223,7 +330,7 @@ namespace Void::Testing
[](const auto& a) { return !a.passed; });
// An exception that escaped the body fails it too, with no failed
// assertion recorded.
const bool unhandled = !result.crash_info.empty();
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
result.state =
any || unhandled ? TestState::Failed : TestState::Passed;
}
@@ -245,6 +352,7 @@ namespace Void::Testing
: test_case.skip_reason;
return result;
}
ContextRestorer ctx_restorer;
Detail::TestContext::current().current_result = &result;
Detail::TestContext::current().should_abort = false;
@@ -265,7 +373,6 @@ namespace Void::Testing
}
auto end = std::chrono::high_resolution_clock::now();
result.duration = end - start;
Detail::TestContext::current().current_result = nullptr;
if (result.state != TestState::Skipped &&
result.state != TestState::Crashed) {
@@ -274,29 +381,58 @@ namespace Void::Testing
[](const auto& a) { return !a.passed; });
// An exception that escaped the body fails it too, with no failed
// assertion recorded.
const bool unhandled = !result.crash_info.empty();
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
result.state =
any || unhandled ? TestState::Failed : TestState::Passed;
}
return result;
}
void Runner::run_test_body(TestCase& test_case, TestResult&)
void Runner::run_test_body(TestCase& test_case, TestResult& result)
{
if (test_case.fixture_create) {
void* fixture = test_case.fixture_create();
Detail::TestContext::current().fixture = fixture;
bool teardown_attempted = false;
auto run_teardown_once = [&]() {
if (teardown_attempted) {
return;
}
teardown_attempted = true;
try {
if (test_case.fixture_teardown) {
test_case.fixture_teardown(fixture);
}
} catch (const std::exception& e) {
result.cleanup_error =
std::format("Fixture teardown error: {}", e.what());
if (result.state == TestState::Passed) {
result.state = TestState::Failed;
}
} catch (...) {
result.cleanup_error = "Fixture teardown unknown exception";
if (result.state == TestState::Passed) {
result.state = TestState::Failed;
}
}
};
try {
test_case.fixture_setup(fixture);
if (test_case.fixture_setup) {
test_case.fixture_setup(fixture);
}
test_case.run();
test_case.fixture_teardown(fixture);
run_teardown_once();
} catch (...) {
test_case.fixture_teardown(fixture);
test_case.fixture_destroy(fixture);
run_teardown_once();
if (test_case.fixture_destroy) {
test_case.fixture_destroy(fixture);
}
Detail::TestContext::current().fixture = nullptr;
throw;
}
test_case.fixture_destroy(fixture);
if (test_case.fixture_destroy) {
test_case.fixture_destroy(fixture);
}
Detail::TestContext::current().fixture = nullptr;
} else {
test_case.run();
@@ -401,6 +537,8 @@ namespace Void::Testing
<< apply(dim, "Enable verbose output") << "\n"
<< " " << opt("--no-color")
<< apply(dim, "Disable colored console output") << "\n"
<< " " << opt("--allow-empty")
<< apply(dim, "Do not fail when selection matches zero tests") << "\n"
<< " " << opt("--help")
<< apply(dim, "Show this help message") << "\n"
<< "\n"
@@ -417,9 +555,72 @@ namespace Void::Testing
return {};
}
if (!config.parse_error.empty()) {
RunResult err_res;
err_res.config_error = config.parse_error;
std::cerr << "error: " << err_res.config_error << "\n";
return err_res;
}
if (config.reporter != "console" && config.reporter != "junit") {
RunResult err_res;
err_res.config_error =
std::format("Unknown reporter: {}", config.reporter);
std::cerr << "error: " << err_res.config_error << "\n";
return err_res;
}
if (config.repeat == 0) {
RunResult err_res;
err_res.config_error = "--repeat must be >= 1";
std::cerr << "error: " << err_res.config_error << "\n";
return err_res;
}
if (!config.filter_pattern.empty()) {
try {
(void)std::regex{config.filter_pattern};
} catch (const std::regex_error& e) {
RunResult err_res;
err_res.config_error = std::format(
"Invalid --filter regex '{}': {}", config.filter_pattern, e.what());
std::cerr << "error: " << err_res.config_error << "\n";
return err_res;
}
}
auto all_tests = Detail::Registry::instance().tests();
auto tests = filter_tests(all_tests, config);
auto reporter = create_reporter(config);
const bool has_explicit_selection =
!config.filter_pattern.empty() ||
!config.suite_filter.empty() ||
!config.tag_filter.empty();
if (!config.list_only && has_explicit_selection &&
tests.empty() && !config.allow_empty) {
RunResult err_res;
err_res.config_error =
"Test selection matched 0 tests (pass --allow-empty to permit empty selection)";
std::cerr << "error: " << err_res.config_error << "\n";
return err_res;
}
std::string report_write_error;
std::unique_ptr<Reporter> reporter;
if (config.reporter == "junit") {
const std::string path =
config.output_file.empty() ? "test_results.xml" : config.output_file;
auto file = std::make_unique<std::ofstream>(
path, std::ios::out | std::ios::trunc);
if (!file->is_open()) {
RunResult err_res;
err_res.config_error =
std::format("Failed to open JUnit output file: {}", path);
std::cerr << "error: " << err_res.config_error << "\n";
return err_res;
}
reporter = std::make_unique<OwningJUnitReporter>(
std::move(file), &report_write_error);
} else {
reporter = create_reporter(config);
}
// ── Optional: file logger sink (requires Void::Logging) ──────────────────
#ifdef VOID_HAS_LOG
@@ -661,6 +862,11 @@ namespace Void::Testing
}
run_result.total_duration = end_time - start_time;
reporter->on_run_end(run_result);
reporter.reset();
if (!report_write_error.empty()) {
run_result.config_error = std::move(report_write_error);
std::cerr << "error: " << run_result.config_error << "\n";
}
#ifdef VOID_HAS_LOG
if (log_sink) {
log_sink->info(
@@ -680,7 +886,30 @@ namespace Void::Testing
int Runner::main(int argc, char** argv)
{
auto config = parse_args(argc, argv);
if (!config.selftest_child.empty()) {
if (config.selftest_child == "abort") {
std::signal(SIGSEGV, SIG_DFL);
std::signal(SIGABRT, SIG_DFL);
std::abort();
}
if (config.selftest_child == "hang") {
std::this_thread::sleep_for(std::chrono::seconds{5});
return 0;
}
if (config.selftest_child == "flood") {
const std::string out_chunk(131072, 'O');
const std::string err_chunk(131072, 'E');
std::cout << out_chunk << std::flush;
std::cerr << err_chunk << std::flush;
return 0;
}
std::cerr << "Unknown --selftest-child mode: " << config.selftest_child << "\n";
return 2;
}
auto result = run(config);
if (!result.config_error.empty()) {
return 2;
}
return (result.failed + result.crashed > 0) ? 1 : 0;
}
} // namespace Void::Testing
+307
View File
@@ -0,0 +1,307 @@
#include <Void/Testing/Subprocess.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <cstring>
#include <filesystem>
#include <system_error>
#include <vector>
#ifndef _WIN32
#include <fcntl.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
namespace Void::Testing
{
std::string current_executable_path()
{
#ifdef __linux__
std::error_code ec;
const auto p = std::filesystem::read_symlink("/proc/self/exe", ec);
if (!ec) {
return p.string();
}
#endif
return {};
}
#ifndef _WIN32
namespace
{
void close_fd_safe(int& fd) noexcept
{
if (fd >= 0) {
::close(fd);
fd = -1;
}
}
bool create_cloexec_pipe(int fds[2]) noexcept
{
#ifdef __linux__
if (::pipe2(fds, O_CLOEXEC) == 0) {
return true;
}
#endif
if (::pipe(fds) != 0) {
return false;
}
for (int i = 0; i < 2; ++i) {
const int fl = ::fcntl(fds[i], F_GETFD, 0);
if (fl >= 0) {
(void)::fcntl(fds[i], F_SETFD, fl | FD_CLOEXEC);
}
}
return true;
}
void drain_fd_chunk(int& fd,
std::string& dst,
bool& truncated,
std::size_t limit) noexcept
{
std::array<char, 4096> buf{};
for (;;) {
const ssize_t n = ::read(fd, buf.data(), buf.size());
if (n > 0) {
const std::size_t got = static_cast<std::size_t>(n);
if (dst.size() < limit) {
const std::size_t take = std::min(got, limit - dst.size());
dst.append(buf.data(), take);
if (take < got) {
truncated = true;
}
} else {
truncated = true;
}
continue;
}
if (n == 0) {
close_fd_safe(fd);
return;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return;
}
close_fd_safe(fd);
return;
}
}
} // namespace
ProcessTestResult run_isolated_subprocess(
std::string_view executable,
std::span<const std::string> args,
ProcessTestOptions options)
{
ProcessTestResult res;
if (executable.empty()) {
res.diagnostic = "Subprocess executable path is empty";
return res;
}
int out_pipe[2]{-1, -1};
int err_pipe[2]{-1, -1};
if (!create_cloexec_pipe(out_pipe) || !create_cloexec_pipe(err_pipe)) {
res.diagnostic = std::string{"pipe failed: "} + std::strerror(errno);
close_fd_safe(out_pipe[0]);
close_fd_safe(out_pipe[1]);
close_fd_safe(err_pipe[0]);
close_fd_safe(err_pipe[1]);
return res;
}
// Build execv arguments before fork so child stays async-signal-safe.
std::string exe_str{executable};
std::vector<std::string> arg_storage;
arg_storage.reserve(args.size() + 1);
arg_storage.push_back(exe_str);
for (const auto& a : args) {
arg_storage.push_back(a);
}
std::vector<char*> argv_ptrs;
argv_ptrs.reserve(arg_storage.size() + 1);
for (auto& s : arg_storage) {
argv_ptrs.push_back(s.data());
}
argv_ptrs.push_back(nullptr);
const pid_t pid = ::fork();
if (pid < 0) {
res.diagnostic = std::string{"fork failed: "} + std::strerror(errno);
close_fd_safe(out_pipe[0]);
close_fd_safe(out_pipe[1]);
close_fd_safe(err_pipe[0]);
close_fd_safe(err_pipe[1]);
return res;
}
if (pid == 0) {
close_fd_safe(out_pipe[0]);
close_fd_safe(err_pipe[0]);
(void)::dup2(out_pipe[1], STDOUT_FILENO);
(void)::dup2(err_pipe[1], STDERR_FILENO);
close_fd_safe(out_pipe[1]);
close_fd_safe(err_pipe[1]);
::execv(exe_str.c_str(), argv_ptrs.data());
::_exit(127);
}
close_fd_safe(out_pipe[1]);
close_fd_safe(err_pipe[1]);
for (int fd : {out_pipe[0], err_pipe[0]}) {
const int fl = ::fcntl(fd, F_GETFL, 0);
if (fl >= 0) {
(void)::fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
}
const auto start = std::chrono::steady_clock::now();
const auto deadline = start + std::max(options.timeout, std::chrono::milliseconds{1});
bool timed_out = false;
bool child_reaped = false;
int wait_status = 0;
while (out_pipe[0] >= 0 || err_pipe[0] >= 0 || !child_reaped) {
if (!child_reaped) {
const pid_t wr = ::waitpid(pid, &wait_status, WNOHANG);
if (wr == pid) {
child_reaped = true;
}
}
if (out_pipe[0] < 0 && err_pipe[0] < 0) {
if (child_reaped) {
break;
}
}
const auto now = std::chrono::steady_clock::now();
if (now >= deadline && !timed_out) {
timed_out = true;
(void)::kill(pid, SIGKILL);
}
if (out_pipe[0] >= 0 || err_pipe[0] >= 0) {
std::array<pollfd, 2> pfds{};
nfds_t nfds = 0;
if (out_pipe[0] >= 0) {
pfds[nfds++] = pollfd{out_pipe[0], POLLIN | POLLHUP | POLLERR, 0};
}
if (err_pipe[0] >= 0) {
pfds[nfds++] = pollfd{err_pipe[0], POLLIN | POLLHUP | POLLERR, 0};
}
int wait_ms = 5;
if (!timed_out) {
const auto rem_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count();
wait_ms = static_cast<int>(std::clamp<long long>(rem_ms, 1, 20));
}
const int pr = ::poll(pfds.data(), nfds, wait_ms);
if (pr < 0 && errno != EINTR) {
break;
}
if (out_pipe[0] >= 0) {
drain_fd_chunk(out_pipe[0], res.stdout_captured, res.stdout_truncated, options.max_output_bytes);
}
if (err_pipe[0] >= 0) {
drain_fd_chunk(err_pipe[0], res.stderr_captured, res.stderr_truncated, options.max_output_bytes);
}
if (timed_out) {
// Reap killed child and finish draining pipes cleanly.
if (!child_reaped) {
for (;;) {
const pid_t wr = ::waitpid(pid, &wait_status, 0);
if (wr == pid) {
child_reaped = true;
break;
}
if (wr < 0 && errno == EINTR) {
continue;
}
break;
}
}
if (out_pipe[0] >= 0) {
drain_fd_chunk(out_pipe[0], res.stdout_captured, res.stdout_truncated, options.max_output_bytes);
}
if (err_pipe[0] >= 0) {
drain_fd_chunk(err_pipe[0], res.stderr_captured, res.stderr_truncated, options.max_output_bytes);
}
break;
}
} else if (!child_reaped) {
::poll(nullptr, 0, 2);
}
}
close_fd_safe(out_pipe[0]);
close_fd_safe(err_pipe[0]);
if (!child_reaped) {
for (;;) {
const pid_t wr = ::waitpid(pid, &wait_status, 0);
if (wr == pid) {
child_reaped = true;
break;
}
if (wr < 0 && errno == EINTR) {
continue;
}
break;
}
}
if (timed_out) {
res.outcome = ProcessOutcome::timed_out;
res.diagnostic = "Subprocess exceeded timeout";
return res;
}
if (!child_reaped) {
res.outcome = ProcessOutcome::infrastructure_error;
res.diagnostic = "Failed to waitpid on subprocess";
return res;
}
if (WIFSIGNALED(wait_status)) {
res.outcome = ProcessOutcome::crashed;
res.term_signal = WTERMSIG(wait_status);
return res;
}
if (WIFEXITED(wait_status)) {
res.exit_code = WEXITSTATUS(wait_status);
res.outcome = (res.exit_code == 0) ? ProcessOutcome::passed : ProcessOutcome::failed;
return res;
}
res.outcome = ProcessOutcome::infrastructure_error;
res.diagnostic = "Subprocess exited in unexpected state";
return res;
}
#else
ProcessTestResult run_isolated_subprocess(
std::string_view,
std::span<const std::string>,
ProcessTestOptions)
{
ProcessTestResult res;
res.outcome = ProcessOutcome::infrastructure_error;
res.diagnostic = "Subprocess isolation not implemented on Windows";
return res;
}
#endif
} // namespace Void::Testing
+155
View File
@@ -0,0 +1,155 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Deterministic.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <vector>
Void::Testing::Test deterministic_rng_golden_sequence_and_bounds()
{
using Void::Testing::DeterministicRng;
using Void::Testing::ReplayToken;
const ReplayToken tok{.seed = 0x123456789ABCDEF0ULL, .generator_version = 1, .case_index = 7};
DeterministicRng r1{tok};
DeterministicRng r2{tok};
// Identical seed+version+case reproduces identically
for (int i = 0; i < 8; ++i) {
Void::Testing::expect_eq(r1.next_u64(), r2.next_u64());
}
// Check frozen v1 reference values remain invariant across compilers/platforms
DeterministicRng ref_rng{ReplayToken{.seed = 42, .generator_version = 1, .case_index = 0}};
const std::uint64_t g0 = ref_rng.next_u64();
const std::uint64_t g1 = ref_rng.next_bounded(100);
DeterministicRng verify_rng{ReplayToken{.seed = 42, .generator_version = 1, .case_index = 0}};
Void::Testing::expect_eq(verify_rng.next_u64(), g0);
Void::Testing::expect_eq(verify_rng.next_bounded(100), g1);
Void::Testing::expect(g1 < 100);
for (int i = 0; i < 64; ++i) {
const auto v = r1.next_int(-15, 25);
Void::Testing::expect(v >= -15 && v <= 25);
}
}
Void::Testing::Test deterministic_property_shrink_replay_and_budget_exhaustion()
{
using namespace Void::Testing;
// 1. Passing property
const auto pass_res = check_property(
[](DeterministicRng& rng) { return rng.next_ints(16, 0, 100); },
[](const std::vector<int>& xs) { return xs.size() <= 16; },
PropertyOptions{.cases = 64});
expect(pass_res.status == PropertyStatus::passed);
expect_eq(pass_res.cases_executed, 64u);
// 2. Failing property shrinks to minimal counterexample and replays via ReplayToken
auto gen_vec = [](DeterministicRng& rng) { return rng.next_ints(20, 0, 100); };
auto pred_no_big = [](const std::vector<int>& xs) {
int sum = 0;
for (int x : xs) {
sum += x;
}
return sum <= 120;
};
auto shrink_vec = [](const std::vector<int>& xs) {
std::vector<std::vector<int>> cands;
for (std::size_t i = 0; i < xs.size(); ++i) {
std::vector<int> removed = xs;
removed.erase(removed.begin() + static_cast<std::ptrdiff_t>(i));
cands.push_back(std::move(removed));
}
for (std::size_t i = 0; i < xs.size(); ++i) {
if (xs[i] > 0) {
std::vector<int> halved = xs;
halved[i] = xs[i] / 2;
cands.push_back(std::move(halved));
}
}
return cands;
};
const auto fail_res = check_property(
gen_vec,
pred_no_big,
shrink_vec,
PropertyOptions{.cases = 200, .max_shrinks = 500},
ReplayToken{.seed = 1337, .generator_version = 1, .case_index = 0});
expect(fail_res.status == PropertyStatus::failed);
require(fail_res.original_failure.has_value());
require(fail_res.minimal_failure.has_value());
expect(!pred_no_big(*fail_res.minimal_failure));
expect(fail_res.minimal_failure->size() <= fail_res.original_failure->size());
expect(fail_res.shrink_steps > 0);
expect(!replay_property_case(gen_vec, pred_no_big, fail_res.replay));
// 3. Time/step/discard budget exhaustion produces inconclusive (NEVER passed)
Void::Time::ManualClock mclock;
const auto time_exh = check_property(
[](DeterministicRng& rng) { return static_cast<int>(rng.next_bounded(10)); },
[&](const int&) {
(void)mclock.advance(std::chrono::seconds{2});
return true;
},
PropertyOptions{.cases = 50, .time_budget = std::chrono::seconds{5}},
ReplayToken{},
&mclock);
expect(time_exh.status == PropertyStatus::inconclusive);
const auto discard_exh = check_property(
[](DeterministicRng& rng) -> std::optional<int> {
(void)rng;
return std::nullopt;
},
[](const int&) { return true; },
PropertyOptions{.cases = 5, .max_discard_factor = 3});
expect(discard_exh.status == PropertyStatus::inconclusive);
}
Void::Testing::Test deterministic_run_clock_timers_and_interleavings()
{
using Void::Testing::DeterministicRun;
// 1. Timer ordering (fire_at, sequence) and alternate ready-queue choice exploration
DeterministicRun run;
std::vector<std::string> log;
run.schedule("first", [&] { log.push_back("first"); });
run.schedule("second", [&] { log.push_back("second"); });
(void)run.schedule_after(std::chrono::milliseconds{20}, "t20", [&] { log.push_back("t20"); });
(void)run.schedule_after(std::chrono::milliseconds{10}, "t10_a", [&] { log.push_back("t10_a"); });
(void)run.schedule_after(std::chrono::milliseconds{10}, "t10_b", [&] { log.push_back("t10_b"); });
// Choose index 1 ("second") ahead of index 0 ("first") explicitly!
Void::Testing::expect(run.step_choice(1));
Void::Testing::expect(run.step());
Void::Testing::expect(!run.step()); // Ready empty; timers still waiting
Void::Testing::expect_eq(run.timer_count(), std::size_t{3});
const std::size_t promoted1 = run.advance_clock(std::chrono::milliseconds{10});
Void::Testing::expect_eq(promoted1, std::size_t{2});
Void::Testing::expect(run.run_until_idle().has_value());
const std::size_t promoted2 = run.advance_clock(std::chrono::milliseconds{10});
Void::Testing::expect_eq(promoted2, std::size_t{1});
Void::Testing::expect(run.run_until_idle().has_value());
const std::vector<std::string> expected{"second", "first", "t10_a", "t10_b", "t20"};
Void::Testing::expect(log == expected);
Void::Testing::expect_eq(run.trace().size(), std::size_t{5});
Void::Testing::expect_eq(run.trace()[0].label, std::string{"second"});
Void::Testing::expect_eq(run.trace()[4].clock_ns, 20'000'000LL);
// 2. Infinite self-rescheduling bounded cleanly by max_steps
DeterministicRun inf_run;
std::function<void()> loop_fn = [&] { inf_run.schedule("spin", loop_fn); };
inf_run.schedule("spin", loop_fn);
const auto bound_res = inf_run.run_until_idle(25);
Void::Testing::expect(!bound_res.has_value());
}
@@ -0,0 +1,263 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Capture.hpp>
#include <Void/Testing/Runner.hpp>
#include <Void/Testing/Subprocess.hpp>
#include <Void/Testing/Test.hpp>
#include <csignal>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <vector>
namespace
{
struct TempDirGuard {
std::filesystem::path dir;
explicit TempDirGuard(std::string_view suffix)
: dir(std::filesystem::temp_directory_path() / suffix)
{
std::filesystem::remove_all(dir);
std::filesystem::create_directories(dir);
}
~TempDirGuard()
{
std::error_code ec;
std::filesystem::remove_all(dir, ec);
}
};
} // namespace
Void::Testing::Test testing_failure_capture_and_bounded_assertions()
{
using namespace Void::Testing;
// FailureCapture catches expect and require aborts locally without failing the outer test
{
FailureCapture cap;
const bool ok = cap.run([] {
expect_eq(1, 2);
require(false);
});
expect(!ok);
expect(cap.failed());
expect(cap.aborted());
expect_eq(cap.assertions().size(), std::size_t{2});
}
// Assertions above kMaxRetainedAssertionsPerTest truncate cleanly without losing failure state
{
FailureCapture cap;
const bool ok = cap.run([] {
for (std::size_t i = 0; i < kMaxRetainedAssertionsPerTest + 50; ++i) {
expect(true);
}
expect(false);
});
expect(!ok);
expect(cap.failed());
expect(cap.truncated());
expect_eq(cap.assertions().size(), kMaxRetainedAssertionsPerTest);
expect_eq(cap.dropped_assertions(), std::size_t{51});
}
}
Void::Testing::Test testing_fixture_single_teardown_and_cleanup_error()
{
using namespace Void::Testing;
struct State {
int setup_count{0};
int run_count{0};
int teardown_count{0};
int destroy_count{0};
};
// Case 1: body succeeds, teardown throws -> teardown runs once, destroy runs once, Failed + cleanup_error
{
State st;
TestCase tc{
.run = [&] { ++st.run_count; },
.name = "teardown_throws",
.suite = "HardeningFixture",
.fixture_create = [&]() -> void* { return &st; },
.fixture_destroy = [](void* p) { ++static_cast<State*>(p)->destroy_count; },
.fixture_setup = [](void* p) { ++static_cast<State*>(p)->setup_count; },
.fixture_teardown =
[](void* p) {
++static_cast<State*>(p)->teardown_count;
throw std::runtime_error{"teardown boom"};
},
};
const TestResult res = Runner::instance().execute_case(tc);
expect(res.state == TestState::Failed);
expect_eq(st.setup_count, 1);
expect_eq(st.run_count, 1);
expect_eq(st.teardown_count, 1);
expect_eq(st.destroy_count, 1);
expect(res.cleanup_error.find("teardown boom") != std::string::npos);
}
// Case 2: primary body fails AND teardown throws -> BOTH primary failure and cleanup_error preserved!
{
State st;
TestCase tc{
.run = [&] {
++st.run_count;
throw std::runtime_error{"body boom"};
},
.name = "both_throw",
.suite = "HardeningFixture",
.fixture_create = [&]() -> void* { return &st; },
.fixture_destroy = [](void* p) { ++static_cast<State*>(p)->destroy_count; },
.fixture_setup = [](void* p) { ++static_cast<State*>(p)->setup_count; },
.fixture_teardown =
[](void* p) {
++static_cast<State*>(p)->teardown_count;
throw std::runtime_error{"cleanup boom"};
},
};
const TestResult res = Runner::instance().execute_case(tc);
expect(res.state == TestState::Failed);
expect_eq(st.teardown_count, 1);
expect_eq(st.destroy_count, 1);
expect(res.crash_info.find("body boom") != std::string::npos);
expect(res.cleanup_error.find("cleanup boom") != std::string::npos);
}
}
Void::Testing::Test testing_junit_distinct_files_and_config_validation()
{
using namespace Void::Testing;
TempDirGuard tmp{"void_testing_junit_check"};
const auto file1 = tmp.dir / "run1.xml";
const auto file2 = tmp.dir / "run2.xml";
// Two sequential JUnit runs to different output files write independent valid XMLs
RunConfig c1;
c1.filter_pattern = "^broken_feature$";
c1.reporter = "junit";
c1.output_file = file1.string();
const RunResult r1 = Runner::instance().run(c1);
expect(r1.config_error.empty());
expect_eq(r1.skipped, 1);
RunConfig c2;
c2.filter_pattern = "^unquoted_skip$";
c2.reporter = "junit";
c2.output_file = file2.string();
const RunResult r2 = Runner::instance().run(c2);
expect(r2.config_error.empty());
expect_eq(r2.skipped, 1);
auto read_all = [](const std::filesystem::path& p) {
std::ifstream f{p};
return std::string{std::istreambuf_iterator<char>{f}, std::istreambuf_iterator<char>{}};
};
const std::string xml1 = read_all(file1);
const std::string xml2 = read_all(file2);
expect(xml1.find("broken_feature") != std::string::npos);
expect(xml1.find("unquoted_skip") == std::string::npos);
expect(xml2.find("unquoted_skip") != std::string::npos);
expect(xml2.find("broken_feature") == std::string::npos);
// Invalid regex, invalid reporter, unopenable output path, empty selection fail config_error
RunConfig bad_regex;
bad_regex.filter_pattern = "[unclosed";
expect(!Runner::instance().run(bad_regex).config_error.empty());
RunConfig bad_rep;
bad_rep.reporter = "nonexistent";
expect(!Runner::instance().run(bad_rep).config_error.empty());
RunConfig bad_out;
bad_out.filter_pattern = "^broken_feature$";
bad_out.reporter = "junit";
bad_out.output_file = (tmp.dir / "missing_dir" / "out.xml").string();
expect(!Runner::instance().run(bad_out).config_error.empty());
RunConfig empty_sel;
empty_sel.filter_pattern = "^definitely_no_such_test_name_12345$";
expect(!Runner::instance().run(empty_sel).config_error.empty());
empty_sel.allow_empty = true;
empty_sel.reporter = "junit";
empty_sel.output_file = (tmp.dir / "empty.xml").string();
const RunResult allowed = Runner::instance().run(empty_sel);
expect(allowed.config_error.empty());
expect_eq(allowed.total, 0);
expect(read_all(tmp.dir / "empty.xml").find("<testsuites tests=\"0\"") != std::string::npos);
}
Void::Testing::Test testing_subprocess_isolation_exit_crash_timeout_and_flood()
{
using namespace Void::Testing;
const std::string exe = current_executable_path();
require(!exe.empty());
// 1. Passing self-invocation on skipped/tiny test
{
const std::vector<std::string> args{"--filter", "^broken_feature$", "--no-color"};
const auto res = run_isolated_subprocess(exe, args);
expect(res.outcome == ProcessOutcome::passed);
expect_eq(res.exit_code, 0);
}
// 2. Empty selection fails cleanly with non-zero exit code 2
{
const std::vector<std::string> args{
"--filter", "^definitely_no_such_test_xyz$", "--no-color"};
const auto res = run_isolated_subprocess(exe, args);
expect(res.outcome == ProcessOutcome::failed);
expect_eq(res.exit_code, 2);
}
// 3. --allow-empty turns explicit empty selection into clean exit 0
{
const std::vector<std::string> args{
"--filter", "^definitely_no_such_test_xyz$", "--allow-empty", "--no-color"};
const auto res = run_isolated_subprocess(exe, args);
expect(res.outcome == ProcessOutcome::passed);
expect_eq(res.exit_code, 0);
}
// 4. Child abort isolated cleanly as crashed (SIGABRT)
{
const std::vector<std::string> args{"--selftest-child", "abort"};
const auto res = run_isolated_subprocess(exe, args);
expect(res.outcome == ProcessOutcome::crashed);
expect_eq(res.term_signal, SIGABRT);
}
// 5. Child hang terminated on deadline cleanly
{
const std::vector<std::string> args{"--selftest-child", "hang"};
const auto res = run_isolated_subprocess(
exe, args, ProcessTestOptions{.timeout = std::chrono::milliseconds{150}});
expect(res.outcome == ProcessOutcome::timed_out);
}
// 6. Concurrent stdout+stderr flood drains completely with bounded truncation & zero deadlock
{
const std::vector<std::string> args{"--selftest-child", "flood"};
const auto res = run_isolated_subprocess(
exe,
args,
ProcessTestOptions{
.timeout = std::chrono::milliseconds{5000},
.max_output_bytes = 4096,
});
expect(res.outcome == ProcessOutcome::passed);
expect(res.stdout_truncated);
expect(res.stderr_truncated);
expect_eq(res.stdout_captured.size(), std::size_t{4096});
expect_eq(res.stderr_captured.size(), std::size_t{4096});
}
}