diff --git a/include/Void/Testing/CompletionObserver.hpp b/include/Void/Testing/CompletionObserver.hpp new file mode 100644 index 0000000..6f0d7fa --- /dev/null +++ b/include/Void/Testing/CompletionObserver.hpp @@ -0,0 +1,140 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Testing +{ + +/// Small synchronization gate for deterministic completion-order tests. +/// +/// Participants call `arrive()` after a computation returned and can then +/// block in `wait_release()`. The test thread can wait for a number of +/// arrivals (`wait_for`) and release blocked participants explicitly, on +/// failure, or after a timeout. All waits are bounded. +class CompletionGate +{ + public: + + using Clock = std::chrono::steady_clock; + + CompletionGate() = default; + + CompletionGate(const CompletionGate&) = delete; + CompletionGate& operator=(const CompletionGate&) = delete; + + /// Record one completed invocation and wake `wait_for` waiters. + void arrive() noexcept + { + std::lock_guard lock{mutex_}; + ++arrivals_; + condition_.notify_all(); + } + + [[nodiscard]] std::size_t arrivals() const noexcept + { + std::lock_guard lock{mutex_}; + return arrivals_; + } + + /// Wait until at least `count` invocations arrived. Returns false on + /// timeout. + [[nodiscard]] bool wait_for(std::size_t count, + std::chrono::milliseconds timeout) + { + std::unique_lock lock{mutex_}; + return condition_.wait_for( + lock, timeout, [&] { return arrivals_ >= count; }); + } + + /// Unblock every current and future `wait_release` caller. + void release() noexcept + { + std::lock_guard lock{mutex_}; + released_ = true; + condition_.notify_all(); + } + + [[nodiscard]] bool released() const noexcept + { + std::lock_guard lock{mutex_}; + return released_; + } + + /// Block until `release()`; returns false on timeout so a failing test + /// can still finish. + [[nodiscard]] bool wait_release(std::chrono::milliseconds timeout) + { + std::unique_lock lock{mutex_}; + return condition_.wait_for(lock, timeout, + [&] { return released_; }); + } + + private: + + mutable std::mutex mutex_; + std::condition_variable condition_; + std::size_t arrivals_{0}; + bool released_{false}; +}; + +/// Callable adapter that runs an observer exactly once after a successful +/// invocation returns, and before the enclosing future is fulfilled. +/// +/// The observer is *not* called when the callable throws; the exception is +/// forwarded unchanged. Void, value, reference and move-only results are +/// preserved. The observer itself must not throw; an exception from it +/// propagates instead of the result. +template class ObservedCallable +{ + public: + + template + ObservedCallable(F&& fn, O&& observer) + : fn_(std::forward(fn)) + , observer_(std::forward(observer)) + { + } + + template + requires std::invocable + decltype(auto) operator()(Args&&... args) + { + using Result = std::invoke_result_t; + if constexpr (std::is_void_v) { + std::invoke(fn_, std::forward(args)...); + std::invoke(observer_); + return; + } else if constexpr (std::is_reference_v) { + Result result = + std::invoke(fn_, std::forward(args)...); + std::invoke(observer_); + return std::forward(result); + } else { + Result result = + std::invoke(fn_, std::forward(args)...); + std::invoke(observer_); + return result; + } + } + + private: + + Fn fn_; + Observer observer_; +}; + +template +[[nodiscard]] auto observe_completion(Fn&& fn, Observer&& observer) +{ + return ObservedCallable, std::decay_t>( + std::forward(fn), std::forward(observer)); +} + +} // namespace Void::Testing diff --git a/tests/standalone/Testing/CompletionObserver.cpp b/tests/standalone/Testing/CompletionObserver.cpp new file mode 100644 index 0000000..18e4ad3 --- /dev/null +++ b/tests/standalone/Testing/CompletionObserver.cpp @@ -0,0 +1,137 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using namespace std::chrono_literals; + +[[nodiscard]] std::vector completion_order(char first, char second) +{ + Void::Testing::CompletionGate gate; + std::mutex mutex; + std::vector order; + + const auto task = [&](char id) { + return Void::Testing::observe_completion( + [id] { return id; }, + [&, id] { + { + std::lock_guard lock{mutex}; + order.push_back(id); + } + gate.arrive(); + (void)gate.wait_release(5s); + }); + }; + + auto a = task(first); + auto b = task(second); + auto first_future = std::async(std::launch::async, std::move(a)); + if (!gate.wait_for(1, 5s)) { + return {}; + } + auto second_future = std::async(std::launch::async, std::move(b)); + const bool both = gate.wait_for(2, 5s); + gate.release(); + Void::Testing::expect_eq(first_future.get(), first); + Void::Testing::expect_eq(second_future.get(), second); + if (!both) { + return {}; + } + + std::lock_guard lock{mutex}; + return order; +} + +} // namespace + +Void::Testing::Test completion_observer_runs_before_future_ready() +{ + Void::Testing::CompletionGate gate; + std::promise observed; + auto wrapped = Void::Testing::observe_completion( + [] { return 42; }, + [&] { + observed.set_value(); + (void)gate.wait_release(5s); + }); + + auto future = std::async(std::launch::async, std::move(wrapped)); + observed.get_future().wait(); + // The observer already ran, but the callable has not returned yet. + Void::Testing::expect(future.wait_for(0ms) == + std::future_status::timeout); + gate.release(); + Void::Testing::expect_eq(future.get(), 42); +} + +Void::Testing::Test completion_observer_preserves_result_categories() +{ + int observed = 0; + + auto void_callable = + Void::Testing::observe_completion([] {}, [&] { ++observed; }); + void_callable(); + Void::Testing::expect_eq(observed, 1); + + auto move_only = Void::Testing::observe_completion( + [] { return std::make_unique(7); }, + [&] { ++observed; }); + auto value = move_only(); + Void::Testing::require(value != nullptr); + Void::Testing::expect_eq(*value, 7); + Void::Testing::expect_eq(observed, 2); + + int storage = 5; + auto reference = Void::Testing::observe_completion( + [&]() -> int& { return storage; }, [] {}); + int& ref = reference(); + ref = 9; + Void::Testing::expect_eq(storage, 9); +} + +Void::Testing::Test completion_observer_forwards_exceptions() +{ + int observed = 0; + auto throwing = Void::Testing::observe_completion( + []() -> int { throw std::runtime_error{"boom"}; }, + [&] { ++observed; }); + + bool caught = false; + try { + (void)throwing(); + } catch (const std::runtime_error&) { + caught = true; + } + Void::Testing::expect(caught); + Void::Testing::expect_eq(observed, 0); +} + +Void::Testing::Test completion_gate_release_and_timeout() +{ + Void::Testing::CompletionGate gate; + Void::Testing::expect(!gate.wait_release(5ms)); + gate.arrive(); + Void::Testing::expect(gate.wait_for(1, 5ms)); + Void::Testing::expect(!gate.wait_for(2, 5ms)); + gate.release(); + Void::Testing::expect(gate.wait_release(5ms)); +} + +Void::Testing::Test completion_order_is_deterministic() +{ + Void::Testing::expect(completion_order('A', 'B') == + std::vector{'A', 'B'}); + Void::Testing::expect(completion_order('B', 'A') == + std::vector{'B', 'A'}); +}