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