Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection based, no app coupling), verified by the test suite (1103 passing): Data reflection: - Reflect.hpp now (de)serializes chrono::duration, chrono::time_point, std::variant (tagged), std::array, and non-string-keyed std::map; Meta.hpp gains is_time_point_v et al. Async: - EventBus gains Mode::Async (worker-thread dispatch + flush()). - ThreadPool gains a bounded queue, try_submit(), and rejection stats. New modules / containers: - Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker, ResourceMonitor. - Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V> (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats). - System: process/CPU/memory metrics (Metrics.hpp) and a streaming Process API. Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions, history states, deferred events), Configuration/Logging reflection helpers, and the accompanying test suites. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
43b5a81504
commit
80293ee56f
93 files changed
+8500
-3312
No files matched your search
@@ -17,7 +17,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
#if defined(VOID_SERVICE_V1_PATH) && defined(VOID_SERVICE_V2_PATH) && \
|
||||
__has_include(<dlfcn.h>)
|
||||
@@ -44,7 +45,7 @@ namespace
|
||||
using Success = int;
|
||||
|
||||
struct Work : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& svc = service<VoidTest::ICalc>();
|
||||
const int total = svc.accumulate(1);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::EventBus::EventBus;
|
||||
using Void::EventBus::Mode;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct Tick {
|
||||
int n = 0;
|
||||
};
|
||||
|
||||
struct EventBusAsync : Void::Testing::Suite<EventBusAsync> {
|
||||
// Async handlers run on the bus worker, not the publisher thread.
|
||||
Test handler_runs_off_publisher_thread()
|
||||
{
|
||||
EventBus bus{Mode::Async};
|
||||
std::atomic<std::thread::id> handler_thread{};
|
||||
bus.subscribe<Tick>([&](const Tick&) {
|
||||
handler_thread.store(std::this_thread::get_id());
|
||||
});
|
||||
bus.publish(Tick{1});
|
||||
bus.flush();
|
||||
Void::Testing::expect(handler_thread.load() !=
|
||||
std::this_thread::get_id());
|
||||
}
|
||||
|
||||
// flush() guarantees every published event has been delivered.
|
||||
Test flush_delivers_all_events()
|
||||
{
|
||||
EventBus bus{Mode::Async};
|
||||
std::atomic<int> total{0};
|
||||
bus.subscribe<Tick>([&](const Tick& t) {
|
||||
total.fetch_add(t.n, std::memory_order_relaxed);
|
||||
});
|
||||
for (int i = 1; i <= 50; ++i) {
|
||||
bus.publish(Tick{i});
|
||||
}
|
||||
bus.flush();
|
||||
Void::Testing::expect_eq(total.load(), 50 * 51 / 2);
|
||||
}
|
||||
|
||||
// Unsubscribing before publish means the handler never fires.
|
||||
Test unsubscribe_before_publish_not_called()
|
||||
{
|
||||
EventBus bus{Mode::Async};
|
||||
std::atomic<int> count{0};
|
||||
const auto id = bus.subscribe<Tick>(
|
||||
[&](const Tick&) { count.fetch_add(1); });
|
||||
bus.unsubscribe(id);
|
||||
bus.publish(Tick{1});
|
||||
bus.flush();
|
||||
Void::Testing::expect_eq(count.load(), 0);
|
||||
}
|
||||
|
||||
// Sync mode (the default) still delivers inline within publish().
|
||||
Test sync_mode_delivers_inline()
|
||||
{
|
||||
EventBus bus; // Mode::Sync
|
||||
int seen = 0;
|
||||
bus.subscribe<Tick>([&](const Tick& t) { seen = t.n; });
|
||||
bus.publish(Tick{7});
|
||||
Void::Testing::expect_eq(seen, 7); // no flush needed
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Concurrency::ThreadPool;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ThreadPoolBackpressure
|
||||
: Void::Testing::Suite<ThreadPoolBackpressure> {
|
||||
// Unbounded pool (the default) accepts everything and never
|
||||
// rejects.
|
||||
Test unbounded_default_accepts_all()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
std::atomic<int> sum{0};
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
auto f = pool.try_submit([&sum] {
|
||||
sum.fetch_add(1, std::memory_order_relaxed);
|
||||
});
|
||||
Void::Testing::expect(f.has_value());
|
||||
f->wait();
|
||||
}
|
||||
const auto s = pool.stats();
|
||||
Void::Testing::expect_eq(s.submitted, std::uint64_t{100});
|
||||
Void::Testing::expect_eq(s.completed, std::uint64_t{100});
|
||||
Void::Testing::expect_eq(s.rejected, std::uint64_t{0});
|
||||
Void::Testing::expect_eq(sum.load(), 100);
|
||||
}
|
||||
|
||||
// A bounded pool rejects try_submit once the queue is full.
|
||||
Test bounded_pool_rejects_when_full()
|
||||
{
|
||||
ThreadPool pool{1, /*max_queue=*/2};
|
||||
std::atomic<bool> started{false};
|
||||
std::atomic<bool> release{false};
|
||||
|
||||
// Occupy the single worker so the queue can fill up.
|
||||
auto blocker = pool.submit([&] {
|
||||
started.store(true, std::memory_order_release);
|
||||
while (!release.load(std::memory_order_acquire)) {
|
||||
std::this_thread::yield();
|
||||
}
|
||||
});
|
||||
while (!started.load(std::memory_order_acquire)) {
|
||||
std::this_thread::yield();
|
||||
}
|
||||
|
||||
auto a = pool.try_submit([] {}); // queue size 1
|
||||
auto b = pool.try_submit([] {}); // queue size 2 (== max)
|
||||
auto c = pool.try_submit([] {}); // full -> rejected
|
||||
Void::Testing::expect(a.has_value());
|
||||
Void::Testing::expect(b.has_value());
|
||||
Void::Testing::expect(!c.has_value());
|
||||
|
||||
release.store(true, std::memory_order_release);
|
||||
blocker.wait();
|
||||
a->wait();
|
||||
b->wait();
|
||||
|
||||
const auto s = pool.stats();
|
||||
Void::Testing::expect(s.rejected >= 1);
|
||||
Void::Testing::expect_eq(s.submitted, std::uint64_t{3});
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,42 @@
|
||||
#include <Void/Configuration/Argparse.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace arg = Void::Argparse;
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Opts {
|
||||
[[= arg::Short{
|
||||
'v'}]][[= arg::Help{"verbose output"}]] bool verbose = false;
|
||||
[[= arg::Help{"output path"}]] std::string out = "a.out";
|
||||
std::optional<std::string> config;
|
||||
[[= arg::Positional{}]] std::string input = "";
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test argparse_reflective_parse()
|
||||
{
|
||||
const char* argv[] = {"prog", "-v", "--out=x.bin", "foo.txt"};
|
||||
const auto o = arg::parse<Opts>(4, argv, "prog");
|
||||
Void::Testing::expect(o.has_value());
|
||||
Void::Testing::expect_eq(o->verbose, true);
|
||||
Void::Testing::expect_eq(o->out, std::string{"x.bin"});
|
||||
Void::Testing::expect_eq(o->input, std::string{"foo.txt"});
|
||||
Void::Testing::expect(!o->config.has_value());
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test argparse_reflective_defaults()
|
||||
{
|
||||
const char* argv[] = {"prog", "bar.txt"};
|
||||
const auto o = arg::parse<Opts>(2, argv, "prog");
|
||||
Void::Testing::expect(o.has_value());
|
||||
Void::Testing::expect_eq(o->verbose, false); // flag default
|
||||
Void::Testing::expect_eq(o->out, std::string{"a.out"}); // option default
|
||||
Void::Testing::expect_eq(o->input, std::string{"bar.txt"});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#include <Void/Configuration/Bind.hpp>
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace C = Void::Configuration;
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Settings {
|
||||
[[= C::Key{"log_level"}]] std::string level = "info";
|
||||
[[= C::Required{}]] std::string host = "";
|
||||
int port = 8080;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test bind_key_override_and_values()
|
||||
{
|
||||
C::Config cfg;
|
||||
cfg.set("log_level", "debug"); // bound via Key override
|
||||
cfg.set("host", "localhost");
|
||||
cfg.set("port", "9090");
|
||||
const auto r = C::bind<Settings>(cfg);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->level, std::string{"debug"});
|
||||
Void::Testing::expect_eq(r->host, std::string{"localhost"});
|
||||
Void::Testing::expect_eq(r->port, 9090);
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test bind_keeps_defaults_when_absent()
|
||||
{
|
||||
C::Config cfg;
|
||||
cfg.set("host", "h"); // only the required key
|
||||
const auto r = C::bind<Settings>(cfg);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->level, std::string{"info"}); // default
|
||||
Void::Testing::expect_eq(r->port, 8080); // default
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test bind_required_missing_fails()
|
||||
{
|
||||
C::Config cfg;
|
||||
cfg.set("log_level", "x"); // host (required) missing
|
||||
const auto r = C::bind<Settings>(cfg);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Configuration::Config;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ByteSize : Void::Testing::Suite<ByteSize> {
|
||||
Test si_units()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("a", "10KB");
|
||||
cfg.set("b", "2MB");
|
||||
cfg.set("c", "1GB");
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("a").value(),
|
||||
std::uint64_t{10'000});
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("b").value(),
|
||||
std::uint64_t{2'000'000});
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("c").value(),
|
||||
std::uint64_t{1'000'000'000});
|
||||
}
|
||||
|
||||
Test binary_units()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("a", "1KiB");
|
||||
cfg.set("b", "1GiB");
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("a").value(),
|
||||
std::uint64_t{1024});
|
||||
Void::Testing::expect_eq(cfg.get_as<std::uint64_t>("b").value(),
|
||||
std::uint64_t{1024ull * 1024 * 1024});
|
||||
}
|
||||
|
||||
Test bare_and_fractional()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("plain", "512");
|
||||
cfg.set("half", "1.5KB");
|
||||
cfg.set("bytes", "64B");
|
||||
Void::Testing::expect_eq(
|
||||
cfg.get_as<std::size_t>("plain").value(), std::size_t{512});
|
||||
Void::Testing::expect_eq(
|
||||
cfg.get_as<std::size_t>("half").value(), std::size_t{1500});
|
||||
Void::Testing::expect_eq(
|
||||
cfg.get_as<std::size_t>("bytes").value(), std::size_t{64});
|
||||
}
|
||||
|
||||
Test invalid_unit_is_error()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("bad", "10ZZ");
|
||||
Void::Testing::expect(
|
||||
!cfg.get_as<std::uint64_t>("bad").has_value());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,86 @@
|
||||
#include <Void/Containers/BufferPool.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::BufferPool::BufferPool;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct BufferPoolTests : Void::Testing::Suite<BufferPoolTests> {
|
||||
// Logical size is the request; capacity rounds up to a power of
|
||||
// two.
|
||||
Test acquire_rounds_capacity_to_size_class()
|
||||
{
|
||||
BufferPool<std::int16_t> pool;
|
||||
auto buf = pool.acquire(500);
|
||||
Void::Testing::expect_eq(buf.size(), std::size_t{500});
|
||||
Void::Testing::expect_eq(buf.capacity(), std::size_t{512});
|
||||
}
|
||||
|
||||
// A fresh request allocates; a same-class request after drop
|
||||
// reuses.
|
||||
Test reuses_storage_of_same_size_class()
|
||||
{
|
||||
BufferPool<std::int16_t> pool;
|
||||
std::int16_t* first = nullptr;
|
||||
{
|
||||
auto buf = pool.acquire(500);
|
||||
first = buf.data();
|
||||
} // returned to the pool here
|
||||
Void::Testing::expect_eq(pool.stats().allocations,
|
||||
std::uint64_t{1});
|
||||
Void::Testing::expect_eq(pool.stats().pooled, std::size_t{1});
|
||||
|
||||
auto buf2 = pool.acquire(300); // also class 512
|
||||
Void::Testing::expect_eq(pool.stats().reuses, std::uint64_t{1});
|
||||
Void::Testing::expect_eq(pool.stats().allocations,
|
||||
std::uint64_t{1});
|
||||
// Same backing storage -> no reallocation.
|
||||
Void::Testing::expect(buf2.data() == first);
|
||||
Void::Testing::expect_eq(buf2.capacity(), std::size_t{512});
|
||||
}
|
||||
|
||||
Test distinct_size_classes_use_distinct_buckets()
|
||||
{
|
||||
BufferPool<float> pool;
|
||||
{
|
||||
auto a = pool.acquire(500); // class 512
|
||||
auto b = pool.acquire(1000); // class 1024
|
||||
Void::Testing::expect_eq(a.capacity(), std::size_t{512});
|
||||
Void::Testing::expect_eq(b.capacity(), std::size_t{1024});
|
||||
}
|
||||
Void::Testing::expect_eq(pool.stats().allocations,
|
||||
std::uint64_t{2});
|
||||
Void::Testing::expect_eq(pool.stats().pooled, std::size_t{2});
|
||||
}
|
||||
|
||||
Test buffer_is_writable_and_iterable()
|
||||
{
|
||||
BufferPool<int> pool;
|
||||
auto buf = pool.acquire(4);
|
||||
for (std::size_t i = 0; i < buf.size(); ++i) {
|
||||
buf[i] = static_cast<int>(i * i);
|
||||
}
|
||||
int sum = 0;
|
||||
for (int v : buf) {
|
||||
sum += v;
|
||||
}
|
||||
Void::Testing::expect_eq(sum, 0 + 1 + 4 + 9);
|
||||
Void::Testing::expect_eq(buf.span().size(), std::size_t{4});
|
||||
}
|
||||
|
||||
Test shrink_drops_pooled_storage()
|
||||
{
|
||||
BufferPool<int> pool;
|
||||
{
|
||||
auto a = pool.acquire(10);
|
||||
}
|
||||
Void::Testing::expect_eq(pool.stats().pooled, std::size_t{1});
|
||||
pool.shrink();
|
||||
Void::Testing::expect_eq(pool.stats().pooled, std::size_t{0});
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,123 @@
|
||||
#include <Void/Containers/Cache.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Cache::Cache;
|
||||
using Void::Cache::Policy;
|
||||
using Void::Testing::Test;
|
||||
using namespace std::chrono_literals;
|
||||
using TP = std::chrono::steady_clock::time_point;
|
||||
|
||||
// A manually-advanced clock for deterministic TTL tests.
|
||||
struct ManualClock {
|
||||
std::shared_ptr<TP> now =
|
||||
std::make_shared<TP>(std::chrono::steady_clock::now());
|
||||
auto fn() const
|
||||
{
|
||||
auto p = now;
|
||||
return [p] { return *p; };
|
||||
}
|
||||
void advance(std::chrono::nanoseconds d) const { *now += d; }
|
||||
};
|
||||
|
||||
struct CacheTests : Void::Testing::Suite<CacheTests> {
|
||||
// ── TTL ───────────────────────────────────────────────────
|
||||
Test ttl_expires_lazily()
|
||||
{
|
||||
ManualClock clk;
|
||||
Cache<int, std::string> c{4, Policy::LRU, 100ms, clk.fn()};
|
||||
c.put(1, "a");
|
||||
clk.advance(50ms);
|
||||
Void::Testing::expect(c.get(1).has_value());
|
||||
clk.advance(60ms); // now 110ms > 100ms TTL
|
||||
Void::Testing::expect(!c.get(1).has_value());
|
||||
Void::Testing::expect_eq(c.stats().expirations,
|
||||
std::uint64_t{1});
|
||||
}
|
||||
|
||||
Test per_entry_ttl_overrides_default()
|
||||
{
|
||||
ManualClock clk;
|
||||
Cache<int, int> c{4, Policy::LRU, 100ms, clk.fn()};
|
||||
c.put(1, 10, 10ms); // shorter than default
|
||||
clk.advance(20ms);
|
||||
Void::Testing::expect(!c.get(1).has_value());
|
||||
}
|
||||
|
||||
Test sweep_purges_expired()
|
||||
{
|
||||
ManualClock clk;
|
||||
Cache<int, int> c{8, Policy::LRU, 10ms, clk.fn()};
|
||||
c.put(1, 1);
|
||||
c.put(2, 2);
|
||||
clk.advance(20ms);
|
||||
Void::Testing::expect_eq(c.sweep(), std::size_t{2});
|
||||
Void::Testing::expect_eq(c.size(), std::size_t{0});
|
||||
}
|
||||
|
||||
// ── eviction policies ─────────────────────────────────────
|
||||
Test lru_evicts_least_recently_used()
|
||||
{
|
||||
Cache<int, int> c{2, Policy::LRU};
|
||||
c.put(1, 1);
|
||||
c.put(2, 2);
|
||||
(void)c.get(1); // promote 1
|
||||
c.put(3, 3); // evicts 2
|
||||
Void::Testing::expect(c.contains(1));
|
||||
Void::Testing::expect(!c.contains(2));
|
||||
Void::Testing::expect(c.contains(3));
|
||||
}
|
||||
|
||||
Test fifo_evicts_oldest_inserted()
|
||||
{
|
||||
Cache<int, int> c{2, Policy::FIFO};
|
||||
c.put(1, 1);
|
||||
c.put(2, 2);
|
||||
(void)c.get(1); // does NOT promote under FIFO
|
||||
c.put(3, 3); // evicts 1 (oldest inserted)
|
||||
Void::Testing::expect(!c.contains(1));
|
||||
Void::Testing::expect(c.contains(2));
|
||||
Void::Testing::expect(c.contains(3));
|
||||
}
|
||||
|
||||
Test lfu_evicts_least_frequently_used()
|
||||
{
|
||||
Cache<int, int> c{2, Policy::LFU};
|
||||
c.put(1, 1);
|
||||
c.put(2, 2);
|
||||
(void)c.get(1);
|
||||
(void)c.get(1); // 1 is hot
|
||||
c.put(3, 3); // evicts 2 (lower frequency)
|
||||
Void::Testing::expect(c.contains(1));
|
||||
Void::Testing::expect(!c.contains(2));
|
||||
Void::Testing::expect(c.contains(3));
|
||||
}
|
||||
|
||||
// ── stats ─────────────────────────────────────────────────
|
||||
Test stats_track_hits_and_misses()
|
||||
{
|
||||
Cache<int, int> c{4};
|
||||
c.put(1, 1);
|
||||
(void)c.get(1); // hit
|
||||
(void)c.get(2); // miss
|
||||
(void)c.get(1); // hit
|
||||
const auto s = c.stats();
|
||||
Void::Testing::expect_eq(s.hits, std::uint64_t{2});
|
||||
Void::Testing::expect_eq(s.misses, std::uint64_t{1});
|
||||
}
|
||||
|
||||
Test stats_track_evictions()
|
||||
{
|
||||
Cache<int, int> c{1, Policy::LRU};
|
||||
c.put(1, 1);
|
||||
c.put(2, 2); // evicts 1
|
||||
Void::Testing::expect_eq(c.stats().evictions, std::uint64_t{1});
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <Void/Containers/Debug.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct P {
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test debug_dump_reflects_struct_elements()
|
||||
{
|
||||
std::vector<P> v{{1, 2}, {3, 4}};
|
||||
Void::Testing::expect_eq(Void::Containers::debug_dump(v),
|
||||
std::string{"[P{x: 1, y: 2}, P{x: 3, y: 4}]"});
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test debug_dump_handles_scalars()
|
||||
{
|
||||
std::vector<int> n{1, 2, 3};
|
||||
Void::Testing::expect_eq(Void::Containers::debug_dump(n),
|
||||
std::string{"[1, 2, 3]"});
|
||||
std::vector<int> empty;
|
||||
Void::Testing::expect_eq(Void::Containers::debug_dump(empty),
|
||||
std::string{"[]"});
|
||||
}
|
||||
+121
-124
@@ -1,138 +1,135 @@
|
||||
#include <Void/Core/Bits.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// ── popcount ──────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test popcount_zero()
|
||||
namespace
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::popcount(0u), 0);
|
||||
}
|
||||
using Void::Testing::Test;
|
||||
|
||||
Void::Testing::Test popcount_all_ones_u8()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::popcount(std::uint8_t{0xFF}), 8);
|
||||
}
|
||||
struct Bits : Void::Testing::Suite<Bits> {
|
||||
// ── popcount ──────────────────────────────────────────────
|
||||
Test popcount_zero()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::popcount(0u), 0);
|
||||
}
|
||||
Test popcount_all_ones_u8()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::popcount(std::uint8_t{0xFF}), 8);
|
||||
}
|
||||
Test popcount_u32()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::popcount(std::uint32_t{0x0F0F0F0F}), 16);
|
||||
}
|
||||
|
||||
Void::Testing::Test popcount_u32()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::popcount(std::uint32_t{0x0F0F0F0F}), 16);
|
||||
}
|
||||
// ── test/set/clear/toggle ─────────────────────────────────
|
||||
Test test_bit_set()
|
||||
{
|
||||
Void::Testing::expect(
|
||||
Void::Bits::test_bit(std::uint8_t{0b00000100u}, 2));
|
||||
}
|
||||
Test test_bit_clear()
|
||||
{
|
||||
Void::Testing::expect(
|
||||
!Void::Bits::test_bit(std::uint8_t{0b00000100u}, 0));
|
||||
}
|
||||
Test set_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::set_bit(std::uint8_t{0u}, 3),
|
||||
std::uint8_t{0b00001000u});
|
||||
}
|
||||
Test clear_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::clear_bit(std::uint8_t{0xFF}, 3),
|
||||
std::uint8_t{0b11110111u});
|
||||
}
|
||||
Test toggle_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::toggle_bit(std::uint8_t{0u}, 5),
|
||||
std::uint8_t{0b00100000u});
|
||||
}
|
||||
|
||||
// ── test/set/clear/toggle ────────────────────────────────────────────────────
|
||||
// ── extract / deposit ─────────────────────────────────────
|
||||
Test extract_bits_works()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::extract_bits(std::uint8_t{0b10110100u}, 4, 4),
|
||||
std::uint8_t{0b1011u});
|
||||
}
|
||||
Test deposit_bits_works()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::deposit_bits(std::uint8_t{0u},
|
||||
std::uint8_t{0b1010u}, 4, 4),
|
||||
std::uint8_t{0b10100000u});
|
||||
}
|
||||
|
||||
Void::Testing::Test test_bit_set()
|
||||
{
|
||||
Void::Testing::expect(Void::Bits::test_bit(std::uint8_t{0b00000100u}, 2));
|
||||
}
|
||||
// ── rotation ──────────────────────────────────────────────
|
||||
Test rotl_8()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::rotl(std::uint8_t{0b10000001u}, 1),
|
||||
std::uint8_t{0b00000011u});
|
||||
}
|
||||
Test rotr_8()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::rotr(std::uint8_t{0b10000001u}, 1),
|
||||
std::uint8_t{0b11000000u});
|
||||
}
|
||||
|
||||
Void::Testing::Test test_bit_clear()
|
||||
{
|
||||
Void::Testing::expect(!Void::Bits::test_bit(std::uint8_t{0b00000100u}, 0));
|
||||
}
|
||||
// ── pow2 helpers ──────────────────────────────────────────
|
||||
Test has_single_bit()
|
||||
{
|
||||
Void::Testing::expect(Void::Bits::has_single_bit(64u));
|
||||
Void::Testing::expect(!Void::Bits::has_single_bit(63u));
|
||||
}
|
||||
Test ceil_pow2_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::ceil_pow2(5u), 8u);
|
||||
Void::Testing::expect_eq(Void::Bits::ceil_pow2(8u), 8u);
|
||||
}
|
||||
Test floor_pow2_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::floor_pow2(5u), 4u);
|
||||
}
|
||||
|
||||
Void::Testing::Test set_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::set_bit(std::uint8_t{0u}, 3),
|
||||
std::uint8_t{0b00001000u});
|
||||
}
|
||||
// ── align ─────────────────────────────────────────────────
|
||||
Test align_up_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::align_up(13u, 8u), 16u);
|
||||
Void::Testing::expect_eq(Void::Bits::align_up(8u, 8u), 8u);
|
||||
}
|
||||
Test align_down_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::align_down(13u, 8u), 8u);
|
||||
}
|
||||
|
||||
Void::Testing::Test clear_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::clear_bit(std::uint8_t{0xFF}, 3),
|
||||
std::uint8_t{0b11110111u});
|
||||
}
|
||||
// ── masks ─────────────────────────────────────────────────
|
||||
Test low_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::low_mask<std::uint8_t>(4),
|
||||
std::uint8_t{0x0F});
|
||||
}
|
||||
Test range_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::range_mask<std::uint8_t>(2, 5),
|
||||
std::uint8_t{0b00111100u});
|
||||
}
|
||||
|
||||
Void::Testing::Test toggle_bit_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::toggle_bit(std::uint8_t{0u}, 5),
|
||||
std::uint8_t{0b00100000u});
|
||||
}
|
||||
|
||||
// ── extract / deposit ─────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test extract_bits_works()
|
||||
{
|
||||
// bits 4-7 of 0b10110100 = 0b1011
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::extract_bits(std::uint8_t{0b10110100u}, 4, 4),
|
||||
std::uint8_t{0b1011u});
|
||||
}
|
||||
|
||||
Void::Testing::Test deposit_bits_works()
|
||||
{
|
||||
// deposit 0b1010 into bits 4-7 of 0x00
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::deposit_bits(std::uint8_t{0u}, std::uint8_t{0b1010u}, 4, 4),
|
||||
std::uint8_t{0b10100000u});
|
||||
}
|
||||
|
||||
// ── rotation ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test rotl_8()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::rotl(std::uint8_t{0b10000001u}, 1),
|
||||
std::uint8_t{0b00000011u});
|
||||
}
|
||||
|
||||
Void::Testing::Test rotr_8()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::rotr(std::uint8_t{0b10000001u}, 1),
|
||||
std::uint8_t{0b11000000u});
|
||||
}
|
||||
|
||||
// ── pow2 helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test has_single_bit()
|
||||
{
|
||||
Void::Testing::expect(Void::Bits::has_single_bit(64u));
|
||||
Void::Testing::expect(!Void::Bits::has_single_bit(63u));
|
||||
}
|
||||
|
||||
Void::Testing::Test ceil_pow2_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::ceil_pow2(5u), 8u);
|
||||
Void::Testing::expect_eq(Void::Bits::ceil_pow2(8u), 8u);
|
||||
}
|
||||
|
||||
Void::Testing::Test floor_pow2_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::floor_pow2(5u), 4u);
|
||||
}
|
||||
|
||||
// ── align ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test align_up_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::align_up(13u, 8u), 16u);
|
||||
Void::Testing::expect_eq(Void::Bits::align_up(8u, 8u), 8u);
|
||||
}
|
||||
|
||||
Void::Testing::Test align_down_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::align_down(13u, 8u), 8u);
|
||||
}
|
||||
|
||||
// ── masks ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test low_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::low_mask<std::uint8_t>(4),
|
||||
std::uint8_t{0x0F});
|
||||
}
|
||||
|
||||
Void::Testing::Test range_mask_works()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::range_mask<std::uint8_t>(2, 5),
|
||||
std::uint8_t{0b00111100u});
|
||||
}
|
||||
|
||||
// ── byteswap / endian ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test byteswap_u32()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Bits::byteswap(std::uint32_t{0x12345678u}),
|
||||
std::uint32_t{0x78563412u});
|
||||
}
|
||||
// ── byteswap / endian ─────────────────────────────────────
|
||||
Test byteswap_u32()
|
||||
{
|
||||
Void::Testing::expect_eq(
|
||||
Void::Bits::byteswap(std::uint32_t{0x12345678u}),
|
||||
std::uint32_t{0x78563412u});
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,32 @@
|
||||
#include <Void/Core/Flags.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
enum class Perm : unsigned { Read = 1, Write = 2, Exec = 4 };
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test flags_to_string_lists_set_names()
|
||||
{
|
||||
const auto f = Void::Flags::Flags<Perm>{Perm::Read} | Perm::Exec;
|
||||
Void::Testing::expect_eq(Void::Flags::to_string(f),
|
||||
std::string{"Read|Exec"});
|
||||
Void::Testing::expect_eq(Void::Flags::to_string(Void::Flags::Flags<Perm>{}),
|
||||
std::string{});
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test flags_parse_names()
|
||||
{
|
||||
const auto f = Void::Flags::parse<Perm>("Read|Write");
|
||||
Void::Testing::expect(f.test(Perm::Read));
|
||||
Void::Testing::expect(f.test(Perm::Write));
|
||||
Void::Testing::expect(!f.test(Perm::Exec));
|
||||
// unknown names ignored
|
||||
const auto g = Void::Flags::parse<Perm>("Exec|Nope");
|
||||
Void::Testing::expect(g.test(Perm::Exec) && !g.test(Perm::Read));
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
#include <Void/Core/Meta.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace M = Void::Meta;
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Point {
|
||||
int x = 1;
|
||||
int y = 2;
|
||||
};
|
||||
struct Nest {
|
||||
Point p;
|
||||
std::string tag = "z";
|
||||
};
|
||||
enum class Color { Red, Green, Blue };
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test meta_field_walk()
|
||||
{
|
||||
Void::Testing::expect_eq(M::field_count<Point>(), std::size_t{2});
|
||||
const auto names = M::field_names<Point>();
|
||||
Void::Testing::expect_eq(names.size(), std::size_t{2});
|
||||
Void::Testing::expect(names[0] == "x" && names[1] == "y");
|
||||
|
||||
Point p{3, 4};
|
||||
int sum = 0;
|
||||
M::for_each_field(p, [&](std::string_view, auto& f) { sum += f; });
|
||||
Void::Testing::expect_eq(sum, 7);
|
||||
|
||||
// mutate through for_each_field
|
||||
M::for_each_field(p, [](std::string_view, auto& f) { f += 1; });
|
||||
Void::Testing::expect(p.x == 4 && p.y == 5);
|
||||
}
|
||||
|
||||
Void::Testing::Test meta_equal_compare_hash()
|
||||
{
|
||||
Point a{3, 4};
|
||||
Point b{3, 4};
|
||||
Point c{3, 5};
|
||||
Void::Testing::expect(M::equal(a, b));
|
||||
Void::Testing::expect(!M::equal(a, c));
|
||||
Void::Testing::expect(M::compare(a, c) == std::strong_ordering::less);
|
||||
Void::Testing::expect(M::compare(a, b) == std::strong_ordering::equal);
|
||||
Void::Testing::expect_eq(M::hash(a), M::hash(b));
|
||||
Void::Testing::expect(M::hash(a) != M::hash(c));
|
||||
}
|
||||
|
||||
Void::Testing::Test meta_repr_nested()
|
||||
{
|
||||
Point p{5, 6};
|
||||
Void::Testing::expect_eq(M::repr(p), std::string{"Point{x: 5, y: 6}"});
|
||||
Nest n{Point{1, 2}, "hi"};
|
||||
Void::Testing::expect_eq(
|
||||
M::repr(n), std::string{"Nest{p: Point{x: 1, y: 2}, tag: hi}"});
|
||||
}
|
||||
|
||||
Void::Testing::Test meta_enum_utilities()
|
||||
{
|
||||
Void::Testing::expect_eq(M::enum_count<Color>, std::size_t{3});
|
||||
constexpr auto vals = M::enum_values<Color>();
|
||||
Void::Testing::expect(vals[0] == Color::Red && vals[2] == Color::Blue);
|
||||
const auto entries = M::enum_entries<Color>();
|
||||
Void::Testing::expect(entries[1].first == Color::Green &&
|
||||
entries[1].second == "Green");
|
||||
Void::Testing::expect(M::enum_name(Color::Blue) == "Blue");
|
||||
Void::Testing::expect(M::enum_parse<Color>("Green").value() ==
|
||||
Color::Green);
|
||||
Void::Testing::expect(!M::enum_parse<Color>("Nope").has_value());
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Marker {
|
||||
};
|
||||
struct Annotated {
|
||||
[[= Marker{}]] int tagged = 0;
|
||||
int plain = 0;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test meta_member_annotations()
|
||||
{
|
||||
static constexpr auto members = M::members_v<Annotated>;
|
||||
static_assert(M::has_annotation<Marker>(members[0]));
|
||||
static_assert(!M::has_annotation<Marker>(members[1]));
|
||||
Void::Testing::expect(M::has_annotation<Marker>(members[0]));
|
||||
Void::Testing::expect(!M::has_annotation<Marker>(members[1]));
|
||||
}
|
||||
|
||||
Void::Testing::Test meta_type_name()
|
||||
{
|
||||
Void::Testing::expect_eq(M::type_name<Point>(), std::string{"Point"});
|
||||
Void::Testing::expect_eq(M::type_name<Nest>(), std::string{"Nest"});
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#include <Void/Data/Csv.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Rec {
|
||||
std::string name = "";
|
||||
int age = 0;
|
||||
double score = 0;
|
||||
bool ok = false;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test csv_header_and_to_row()
|
||||
{
|
||||
const auto h = Void::Csv::header_row<Rec>();
|
||||
Void::Testing::expect_eq(h.size(), std::size_t{4});
|
||||
Void::Testing::expect(h[0] == "name" && h[1] == "age" && h[3] == "ok");
|
||||
|
||||
Rec r{"neo", 30, 9.5, true};
|
||||
const auto row = Void::Csv::to_row(r);
|
||||
Void::Testing::expect(row[0] == "neo" && row[1] == "30" &&
|
||||
row[3] == "true");
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test csv_from_row_round_trip()
|
||||
{
|
||||
Rec r{"trin", 28, 7.25, false};
|
||||
const auto back = Void::Csv::from_row<Rec>(Void::Csv::to_row(r));
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect_eq(back->name, std::string{"trin"});
|
||||
Void::Testing::expect_eq(back->age, 28);
|
||||
Void::Testing::expect(back->score > 7.2 && back->score < 7.3);
|
||||
Void::Testing::expect_eq(back->ok, false);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Testing::Test;
|
||||
|
||||
const char* kDoc = R"({
|
||||
"name": "root",
|
||||
"nested": { "a": { "b": [10, 20, 30] } },
|
||||
"weird/key": 7,
|
||||
"flag": true
|
||||
})";
|
||||
|
||||
struct JsonQuery : Void::Testing::Suite<JsonQuery> {
|
||||
// ── JSON Pointer (at) ─────────────────────────────────────
|
||||
Test pointer_walks_objects_and_arrays()
|
||||
{
|
||||
auto doc = Void::Json::parse(kDoc);
|
||||
Void::Testing::expect(doc.has_value());
|
||||
const auto* v = doc->at("/nested/a/b/1");
|
||||
Void::Testing::expect(v != nullptr);
|
||||
Void::Testing::expect_eq(v->as_number(), 20.0);
|
||||
}
|
||||
|
||||
Test empty_pointer_is_whole_document()
|
||||
{
|
||||
auto doc = Void::Json::parse(kDoc);
|
||||
const auto* v = doc->at("");
|
||||
Void::Testing::expect(v == &*doc);
|
||||
}
|
||||
|
||||
Test missing_path_returns_null()
|
||||
{
|
||||
auto doc = Void::Json::parse(kDoc);
|
||||
Void::Testing::expect(doc->at("/nested/missing") == nullptr);
|
||||
Void::Testing::expect(doc->at("/nested/a/b/9") == nullptr);
|
||||
Void::Testing::expect(doc->at("/flag/x") == nullptr);
|
||||
}
|
||||
|
||||
Test escaped_token()
|
||||
{
|
||||
auto doc = Void::Json::parse(kDoc);
|
||||
const auto* v = doc->at("/weird~1key"); // ~1 -> '/'
|
||||
Void::Testing::expect(v != nullptr);
|
||||
Void::Testing::expect_eq(v->as_number(), 7.0);
|
||||
}
|
||||
|
||||
// ── SAX streaming parse ───────────────────────────────────
|
||||
Test sax_fires_events_in_order()
|
||||
{
|
||||
std::vector<std::string> events;
|
||||
Void::Json::SaxHandler h;
|
||||
h.on_object_begin = [&] { events.push_back("{"); };
|
||||
h.on_object_end = [&] { events.push_back("}"); };
|
||||
h.on_array_begin = [&] { events.push_back("["); };
|
||||
h.on_array_end = [&] { events.push_back("]"); };
|
||||
h.on_key = [&](std::string_view k) {
|
||||
events.push_back("key:" + std::string{k});
|
||||
};
|
||||
h.on_number = [&](double d) {
|
||||
events.push_back("num:" + std::to_string((int)d));
|
||||
};
|
||||
h.on_bool = [&](bool b) {
|
||||
events.push_back(b ? "true" : "false");
|
||||
};
|
||||
h.on_string = [&](std::string_view s) {
|
||||
events.push_back("str:" + std::string{s});
|
||||
};
|
||||
|
||||
auto err =
|
||||
Void::Json::parse_sax(R"({"a":[1,2],"b":"x","c":true})", h);
|
||||
Void::Testing::expect(!err.has_value());
|
||||
|
||||
const std::vector<std::string> expected{
|
||||
"{", "key:a", "[", "num:1", "num:2", "]",
|
||||
"key:b", "str:x", "key:c", "true", "}"};
|
||||
Void::Testing::expect(events == expected);
|
||||
}
|
||||
|
||||
Test sax_reports_malformed_input()
|
||||
{
|
||||
Void::Json::SaxHandler h;
|
||||
auto err = Void::Json::parse_sax(R"({"a": })", h);
|
||||
Void::Testing::expect(err.has_value());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,61 @@
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace J = Void::Json;
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Address {
|
||||
std::string city = "?";
|
||||
int zip = 0;
|
||||
};
|
||||
struct User {
|
||||
[[= J::Rename{"user_id"}]] int id = 0;
|
||||
[[= J::Skip{}]] int cache = 99;
|
||||
[[= J::Required{}]] std::string name = "";
|
||||
[[= J::Flatten{}]] Address addr{};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test json_annotations_to_json()
|
||||
{
|
||||
User u{7, 99, "neo", Address{"zion", 100}};
|
||||
const auto j = J::to_json(u);
|
||||
Void::Testing::expect(j.find("user_id") != nullptr); // Rename
|
||||
Void::Testing::expect_eq(j.find("user_id")->as_int(), std::int64_t{7});
|
||||
Void::Testing::expect(j.find("cache") == nullptr); // Skip
|
||||
Void::Testing::expect(j.find("name") != nullptr);
|
||||
// Flatten: Address keys appear at top level, "addr" does not.
|
||||
Void::Testing::expect(j.find("city") != nullptr);
|
||||
Void::Testing::expect_eq(j.find("city")->as_string(), std::string{"zion"});
|
||||
Void::Testing::expect(j.find("zip") != nullptr);
|
||||
Void::Testing::expect(j.find("addr") == nullptr);
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test json_annotations_round_trip()
|
||||
{
|
||||
User u{7, 99, "neo", Address{"zion", 100}};
|
||||
const auto j = J::to_json(u);
|
||||
const auto back = J::from_json<User>(j);
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect_eq(back->id, 7);
|
||||
Void::Testing::expect_eq(back->name, std::string{"neo"});
|
||||
Void::Testing::expect_eq(back->addr.city, std::string{"zion"});
|
||||
Void::Testing::expect_eq(back->addr.zip, 100);
|
||||
Void::Testing::expect_eq(back->cache, 99); // Skip keeps default
|
||||
}
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test json_required_missing_is_error()
|
||||
{
|
||||
const auto j = J::parse(R"({"user_id":1,"city":"x","zip":2})");
|
||||
Void::Testing::expect(j.has_value());
|
||||
const auto r = J::from_json<User>(*j);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect_eq(r.error().field, std::string{"name"});
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#ifdef VOID_HAS_JSON_REFLECTION
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
using Void::Json::from_json;
|
||||
using Void::Json::to_json;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct Circle {
|
||||
double radius = 0;
|
||||
};
|
||||
struct Square {
|
||||
double side = 0;
|
||||
};
|
||||
using Shape = std::variant<Circle, Square>;
|
||||
|
||||
struct Sample {
|
||||
std::string name;
|
||||
std::chrono::milliseconds latency{0};
|
||||
std::chrono::seconds ttl{0};
|
||||
std::array<int, 3> rgb{0, 0, 0};
|
||||
std::map<int, std::string> by_id;
|
||||
std::optional<std::chrono::milliseconds> deadline;
|
||||
std::chrono::system_clock::time_point created{};
|
||||
};
|
||||
|
||||
struct ReflectChrono : Void::Testing::Suite<ReflectChrono> {
|
||||
// ── duration as a unit-suffixed string ────────────────────
|
||||
Test duration_emits_unit_string()
|
||||
{
|
||||
const Sample s{.latency = 250ms, .ttl = 30s};
|
||||
const auto j = to_json(s);
|
||||
Void::Testing::expect_eq(j["latency"].as_string(),
|
||||
std::string{"250ms"});
|
||||
Void::Testing::expect_eq(j["ttl"].as_string(),
|
||||
std::string{"30s"});
|
||||
}
|
||||
|
||||
Test duration_round_trips()
|
||||
{
|
||||
const Sample s{.name = "n",
|
||||
.latency = 1500ms,
|
||||
.ttl = 5s,
|
||||
.rgb = {1, 2, 3}};
|
||||
const auto back = from_json<Sample>(to_json(s));
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect(back->latency == 1500ms);
|
||||
Void::Testing::expect(back->ttl == 5s);
|
||||
}
|
||||
|
||||
Test optional_duration_round_trips()
|
||||
{
|
||||
Sample s;
|
||||
s.deadline = 750ms;
|
||||
auto back = from_json<Sample>(to_json(s));
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect(back->deadline.has_value());
|
||||
Void::Testing::expect(*back->deadline == 750ms);
|
||||
|
||||
s.deadline.reset();
|
||||
back = from_json<Sample>(to_json(s));
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect(!back->deadline.has_value());
|
||||
}
|
||||
|
||||
Test invalid_duration_is_error()
|
||||
{
|
||||
auto j = Void::Json::object();
|
||||
j.as_object().emplace_back(
|
||||
"latency", Void::Json::Value{std::string{"nonsense"}});
|
||||
const auto back = from_json<Sample>(j);
|
||||
Void::Testing::expect(!back.has_value());
|
||||
}
|
||||
|
||||
// ── time_point as ms-since-epoch string ───────────────────
|
||||
Test time_point_emits_ms_string()
|
||||
{
|
||||
Sample s;
|
||||
s.created = std::chrono::system_clock::time_point{
|
||||
std::chrono::milliseconds{1750000000123}};
|
||||
const auto j = to_json(s);
|
||||
Void::Testing::expect_eq(j["created"].as_string(),
|
||||
std::string{"1750000000123ms"});
|
||||
}
|
||||
|
||||
Test time_point_round_trips()
|
||||
{
|
||||
Sample s;
|
||||
s.created = std::chrono::system_clock::time_point{
|
||||
std::chrono::milliseconds{1750000000123}};
|
||||
const auto back = from_json<Sample>(to_json(s));
|
||||
Void::Testing::expect(back.has_value());
|
||||
const auto ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
back->created.time_since_epoch())
|
||||
.count();
|
||||
Void::Testing::expect_eq(ms,
|
||||
static_cast<long long>(1750000000123));
|
||||
}
|
||||
|
||||
Test invalid_time_point_is_error()
|
||||
{
|
||||
auto j = Void::Json::object();
|
||||
j.as_object().emplace_back(
|
||||
"created", Void::Json::Value{std::string{"nope"}});
|
||||
const auto back = from_json<Sample>(j);
|
||||
Void::Testing::expect(!back.has_value());
|
||||
}
|
||||
|
||||
// ── std::array ────────────────────────────────────────────
|
||||
Test array_round_trips()
|
||||
{
|
||||
const Sample s{.rgb = {10, 20, 30}};
|
||||
const auto j = to_json(s);
|
||||
Void::Testing::expect(j["rgb"].is_array());
|
||||
Void::Testing::expect_eq(j["rgb"].as_array().size(),
|
||||
std::size_t{3});
|
||||
const auto back = from_json<Sample>(j);
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect_eq(back->rgb[2], 30);
|
||||
}
|
||||
|
||||
Test array_wrong_length_is_error()
|
||||
{
|
||||
auto arr = Void::Json::array();
|
||||
arr.as_array().push_back(Void::Json::Value{1.0});
|
||||
arr.as_array().push_back(Void::Json::Value{2.0});
|
||||
auto j = Void::Json::object();
|
||||
j.as_object().emplace_back("rgb", std::move(arr));
|
||||
const auto back = from_json<Sample>(j);
|
||||
Void::Testing::expect(!back.has_value());
|
||||
}
|
||||
|
||||
// ── non-string-keyed map ──────────────────────────────────
|
||||
Test int_keyed_map_round_trips()
|
||||
{
|
||||
Sample s;
|
||||
s.by_id = {{1, "one"}, {2, "two"}};
|
||||
const auto j = to_json(s);
|
||||
Void::Testing::expect(j["by_id"].is_array());
|
||||
const auto back = from_json<Sample>(j);
|
||||
Void::Testing::expect(back.has_value());
|
||||
Void::Testing::expect_eq(back->by_id.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(back->by_id.at(1), std::string{"one"});
|
||||
Void::Testing::expect_eq(back->by_id.at(2), std::string{"two"});
|
||||
}
|
||||
|
||||
// ── std::variant (type-name tagged) ───────────────────────
|
||||
Test variant_round_trips_each_alternative()
|
||||
{
|
||||
const Shape c = Circle{2.0};
|
||||
const auto jc = to_json(c);
|
||||
Void::Testing::expect_eq(jc["type"].as_string(),
|
||||
std::string{"Circle"});
|
||||
const auto bc = from_json<Shape>(jc);
|
||||
Void::Testing::expect(bc.has_value());
|
||||
Void::Testing::expect(std::holds_alternative<Circle>(*bc));
|
||||
Void::Testing::expect_eq(std::get<Circle>(*bc).radius, 2.0);
|
||||
|
||||
const Shape sq = Square{3.0};
|
||||
const auto bs = from_json<Shape>(to_json(sq));
|
||||
Void::Testing::expect(bs.has_value());
|
||||
Void::Testing::expect(std::holds_alternative<Square>(*bs));
|
||||
Void::Testing::expect_eq(std::get<Square>(*bs).side, 3.0);
|
||||
}
|
||||
|
||||
Test variant_unknown_tag_is_error()
|
||||
{
|
||||
auto j = Void::Json::object();
|
||||
j.as_object().emplace_back(
|
||||
"type", Void::Json::Value{std::string{"Triangle"}});
|
||||
j.as_object().emplace_back("value", Void::Json::object());
|
||||
const auto back = from_json<Shape>(j);
|
||||
Void::Testing::expect(!back.has_value());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
#endif // VOID_HAS_JSON_REFLECTION
|
||||
@@ -7,7 +7,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -21,33 +22,34 @@ namespace
|
||||
int count = 0;
|
||||
std::vector<std::string>* log = nullptr;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
if (self().log) {
|
||||
self().log->push_back("start");
|
||||
}
|
||||
co_return next<Work>();
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct Start : State {
|
||||
Task<StateKey> start()
|
||||
{
|
||||
if (self().log) {
|
||||
self().log->push_back("start");
|
||||
}
|
||||
co_return next<Work>();
|
||||
}
|
||||
};
|
||||
|
||||
struct Work : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
++m.count;
|
||||
if (m.log) {
|
||||
m.log->push_back("work" + std::to_string(m.count));
|
||||
}
|
||||
if (m.count >= 3) {
|
||||
co_return succeed(m.count);
|
||||
}
|
||||
co_return next<Work>();
|
||||
}
|
||||
struct Work : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
++m.count;
|
||||
if (m.log) {
|
||||
m.log->push_back("work" +
|
||||
std::to_string(m.count));
|
||||
}
|
||||
if (m.count >= 3) {
|
||||
co_return succeed(m.count);
|
||||
}
|
||||
co_return next<Work>();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Start, Work>;
|
||||
|
||||
Counter()
|
||||
: Void::Fsm::Machine<Counter>(
|
||||
MachineOptions{.own_worker = false})
|
||||
@@ -62,12 +64,12 @@ namespace
|
||||
using Success = int;
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Boom : State {
|
||||
Task<Step> run() { co_return fail("kaboom"); }
|
||||
struct States {
|
||||
struct Boom : State {
|
||||
Task<StateKey> run() { co_return fail("kaboom"); }
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Boom>;
|
||||
|
||||
Failing()
|
||||
: Void::Fsm::Machine<Failing>(
|
||||
MachineOptions{.own_worker = false})
|
||||
@@ -113,10 +115,11 @@ Void::Testing::Test fsm_pump_drives_to_completion()
|
||||
Void::Testing::Test fsm_void_result_succeeds()
|
||||
{
|
||||
struct Trivial : Void::Fsm::Machine<Trivial> {
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(); }
|
||||
struct States {
|
||||
struct Done : State {
|
||||
Task<StateKey> run() { co_return succeed(); }
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Done>;
|
||||
Trivial()
|
||||
: Void::Fsm::Machine<Trivial>(
|
||||
MachineOptions{.own_worker = false})
|
||||
@@ -137,13 +140,13 @@ Void::Testing::Test fsm_dynamic_state_registration()
|
||||
|
||||
bool express;
|
||||
struct Express : State {
|
||||
Task<Step> run() { co_return succeed(99); }
|
||||
Task<StateKey> run() { co_return succeed(99); }
|
||||
};
|
||||
struct Normal : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
if (self().has_state<Express>()) {
|
||||
co_return next_dynamic<Express>();
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -32,7 +33,7 @@ namespace
|
||||
long long target;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
while (m.total < m.target) {
|
||||
@@ -138,7 +139,7 @@ Void::Testing::Test fsm_resolves_service_through_context()
|
||||
using Success = int;
|
||||
|
||||
struct Go : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(service<IDoubler>().twice(21));
|
||||
}
|
||||
|
||||
@@ -3,15 +3,20 @@
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// Phase-6 reactive DSL: deferred events (held + replayed after a transition),
|
||||
// entry/exit actions (on.enter/on.exit), and internal transitions (handle an
|
||||
// event without leaving the state).
|
||||
// Imperative equivalents of the old reactive extras:
|
||||
// - deferred events : an event a state does not await stays buffered in the
|
||||
// typed mailbox and is consumed by a later state — defer
|
||||
// is automatic, no declaration needed.
|
||||
// - entry/exit actions: the first/last lines of run().
|
||||
// - internal transition: handle an event in a loop without leaving the state.
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -20,8 +25,8 @@ namespace
|
||||
struct Done {
|
||||
};
|
||||
|
||||
// Busy defers Click (held, not dropped) and runs enter/exit actions; on
|
||||
// Done it transitions to Idle, which then handles the replayed Click.
|
||||
// Busy awaits only Done; a Click posted meanwhile stays buffered (deferred)
|
||||
// and is handled by Idle. enter/exit are the first/last lines of run().
|
||||
class Flow : public Fsm::Machine<Flow>
|
||||
{
|
||||
public:
|
||||
@@ -29,29 +34,29 @@ namespace
|
||||
using Success = int;
|
||||
std::vector<std::string> log;
|
||||
|
||||
struct Busy : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.enter([](Flow& m) { m.log.push_back("enter"); });
|
||||
on.exit([](Flow& m) { m.log.push_back("exit"); });
|
||||
on.template defer<Click>();
|
||||
on.template event<Done>().template to<Idle>();
|
||||
}
|
||||
struct States {
|
||||
struct Busy : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
m.log.push_back("enter");
|
||||
co_await await_event<Done>(); // Click buffered
|
||||
m.log.push_back("exit");
|
||||
co_return next<Idle>();
|
||||
}
|
||||
};
|
||||
struct Idle : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Click>(); // buffered Click
|
||||
self().log.push_back("click");
|
||||
co_return next<End>();
|
||||
}
|
||||
};
|
||||
struct End : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
};
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.template event<Click>()
|
||||
.action([](Flow& m, const Click&) {
|
||||
m.log.push_back("click");
|
||||
})
|
||||
.template to<End>();
|
||||
}
|
||||
};
|
||||
struct End : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
using States = Fsm::States<Busy, Idle, End>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -60,12 +65,12 @@ Void::Testing::Test deferred_event_replays_after_transition()
|
||||
{
|
||||
Flow fsm;
|
||||
fsm.start();
|
||||
fsm.send(Click{}); // deferred while in Busy (not dropped)
|
||||
fsm.send(Done{}); // Busy -> Idle; the held Click is replayed -> End
|
||||
fsm.send(Click{}); // not awaited in Busy → stays buffered (not dropped)
|
||||
fsm.send(Done{}); // Busy -> Idle; Idle consumes the buffered Click -> End
|
||||
const auto outcome = fsm.wait();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
Void::Testing::expect_eq(*outcome, 1);
|
||||
// enter/exit actions fired around Busy; the deferred Click was handled.
|
||||
// enter/exit ran around Busy; the buffered Click was handled in Idle.
|
||||
const std::vector<std::string> expected{"enter", "exit", "click"};
|
||||
Void::Testing::expect(fsm.log == expected);
|
||||
}
|
||||
@@ -79,8 +84,8 @@ namespace
|
||||
struct Stop {
|
||||
};
|
||||
|
||||
// Counter handles Tick internally (no exit/enter, no transition); Stop
|
||||
// leaves with the accumulated count.
|
||||
// Counter handles Tick internally (loop, no re-entry); Stop leaves with the
|
||||
// accumulated count.
|
||||
class Counter : public Fsm::Machine<Counter>
|
||||
{
|
||||
public:
|
||||
@@ -89,19 +94,28 @@ namespace
|
||||
int ticks = 0;
|
||||
int enters = 0;
|
||||
|
||||
struct Run : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.enter([](Counter& m) { ++m.enters; });
|
||||
on.template event<Tick>().internal(
|
||||
[](Counter& m, const Tick&) { ++m.ticks; });
|
||||
on.template event<Stop>().template to<Done>();
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
++m.enters; // entered exactly once
|
||||
for (;;) {
|
||||
auto ev = co_await await_any<Tick, Stop>();
|
||||
if (std::holds_alternative<Stop>(ev)) {
|
||||
co_return next<Done>();
|
||||
}
|
||||
++m.ticks; // internal: handled, stay here
|
||||
}
|
||||
}
|
||||
};
|
||||
struct Done : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(self().ticks);
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(self().ticks); }
|
||||
};
|
||||
using States = Fsm::States<Run, Done>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
namespace Fsm = Void::Fsm;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
@@ -28,17 +29,18 @@ namespace
|
||||
|
||||
int total = 0;
|
||||
|
||||
struct Take : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto a = co_await await_event<Add>();
|
||||
self().total += a.n;
|
||||
auto b = co_await await_event<Add>();
|
||||
self().total += b.n;
|
||||
co_return succeed(self().total);
|
||||
}
|
||||
struct States {
|
||||
struct Take : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto a = co_await await_event<Add>();
|
||||
self().total += a.n;
|
||||
auto b = co_await await_event<Add>();
|
||||
self().total += b.n;
|
||||
co_return succeed(self().total);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Take>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -63,16 +65,17 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() { co_return goto_state<C>(); }
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return goto_state<C>(); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<StateKey> run() { co_return succeed(3); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> run() { co_return succeed(3); }
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -98,17 +101,18 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Loop : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return next<Loop>();
|
||||
}
|
||||
struct States {
|
||||
struct Loop : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return next<Loop>();
|
||||
}
|
||||
};
|
||||
struct Done : State {
|
||||
Task<StateKey> run() { co_return succeed(99); }
|
||||
};
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(99); }
|
||||
};
|
||||
using States = Fsm::States<Loop, Done>;
|
||||
|
||||
explicit Jumper(MachineOptions o = {}) : Fsm::Machine<Jumper>(o) {}
|
||||
};
|
||||
@@ -124,7 +128,7 @@ Void::Testing::Test jump_redirects_at_next_boundary()
|
||||
while (fsm.pump() > 0) {
|
||||
} // Loop -> next<Loop> -> park again
|
||||
|
||||
fsm.jump<Jumper::Done>(); // request a jump
|
||||
fsm.jump<Jumper::States::Done>(); // request a jump
|
||||
fsm.send(Tick{});
|
||||
while (fsm.pump() > 0) {
|
||||
} // Loop finishes -> boundary applies the jump -> Done
|
||||
@@ -147,10 +151,14 @@ namespace
|
||||
|
||||
int runs = 0;
|
||||
|
||||
struct Once : State {
|
||||
Task<Step> run() { co_return succeed(++self().runs); }
|
||||
struct States {
|
||||
struct Once : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(++self().runs);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Once>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -173,13 +181,14 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Fsm::States<A, B>; // initial = A
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(2); }
|
||||
};
|
||||
}; // initial = A
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -189,7 +198,7 @@ Void::Testing::Test restart_at_changes_initial_state()
|
||||
Pick fsm;
|
||||
const auto first = fsm.run_blocking();
|
||||
Void::Testing::expect_eq(*first, 1); // A
|
||||
fsm.restart_at<Pick::B>();
|
||||
fsm.restart_at<Pick::States::B>();
|
||||
const auto second = fsm.wait();
|
||||
Void::Testing::expect_eq(*second, 2); // B
|
||||
}
|
||||
@@ -204,32 +213,33 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(2); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<StateKey> run() { co_return succeed(3); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> run() { co_return succeed(3); }
|
||||
};
|
||||
// Not in States<> — added via replace<>.
|
||||
// Not in States — added via replace<>.
|
||||
struct Extra : State {
|
||||
Task<Step> run() { co_return succeed(7); }
|
||||
Task<StateKey> run() { co_return succeed(7); }
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test remove_and_set_initial_before_start()
|
||||
{
|
||||
Mut fsm;
|
||||
Void::Testing::expect(fsm.has_state<Mut::C>());
|
||||
fsm.remove<Mut::C>();
|
||||
Void::Testing::expect(!fsm.has_state<Mut::C>());
|
||||
Void::Testing::expect(fsm.has_state<Mut::States::C>());
|
||||
fsm.remove<Mut::States::C>();
|
||||
Void::Testing::expect(!fsm.has_state<Mut::States::C>());
|
||||
Void::Testing::expect_eq(fsm.describe().size(), std::size_t{2});
|
||||
|
||||
fsm.set_initial<Mut::B>();
|
||||
fsm.set_initial<Mut::States::B>();
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect_eq(*outcome, 2);
|
||||
}
|
||||
@@ -237,8 +247,9 @@ Void::Testing::Test remove_and_set_initial_before_start()
|
||||
Void::Testing::Test replace_swaps_a_state_and_keeps_initial()
|
||||
{
|
||||
Mut fsm;
|
||||
fsm.replace<Mut::A, Mut::Extra>(); // A was initial -> Extra becomes initial
|
||||
Void::Testing::expect(!fsm.has_state<Mut::A>());
|
||||
// A was initial -> Extra becomes initial.
|
||||
fsm.replace<Mut::States::A, Mut::Extra>();
|
||||
Void::Testing::expect(!fsm.has_state<Mut::States::A>());
|
||||
Void::Testing::expect(fsm.has_state<Mut::Extra>());
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect_eq(*outcome, 7);
|
||||
@@ -257,14 +268,15 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Go>();
|
||||
co_return succeed(5);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Go>();
|
||||
co_return succeed(5);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
#include <Void/Fsm/Fsm.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::ChildSuccess;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// A state's entry is inferred by signature (a 0-arg member returning StateKey /
|
||||
// Task<StateKey>). When several members match, one annotated
|
||||
// `[[= Void::Fsm::entry]]` is preferred; otherwise the first-declared wins. A
|
||||
// startup-data overload run(Cfg) is selected when the machine is launched with
|
||||
// data, and the nullary entry otherwise.
|
||||
|
||||
namespace
|
||||
{
|
||||
// Two nullary entry candidates; the annotated one is chosen even though it
|
||||
// is not declared first.
|
||||
class Annotated : public Fsm::Machine<Annotated>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Pick : State {
|
||||
Task<StateKey> first() // declared first
|
||||
{
|
||||
co_return succeed(1);
|
||||
}
|
||||
[[= Fsm::entry]] Task<StateKey> chosen()
|
||||
{
|
||||
co_return succeed(2);
|
||||
}
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
// Two nullary entry candidates, none annotated → first-declared wins.
|
||||
class FirstWins : public Fsm::Machine<FirstWins>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Pick : State {
|
||||
Task<StateKey> first() { co_return succeed(1); }
|
||||
Task<StateKey> second() { co_return succeed(2); }
|
||||
};
|
||||
};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test annotated_entry_beats_first_declared()
|
||||
{
|
||||
Annotated fsm;
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
Void::Testing::expect_eq(*outcome, 2); // the [[= Fsm::entry]] member ran
|
||||
}
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test first_declared_entry_wins_without_annotation()
|
||||
{
|
||||
FirstWins fsm;
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
Void::Testing::expect_eq(*outcome, 1); // first-declared ran
|
||||
}
|
||||
|
||||
// ── startup-data overload selection ─────────────────────────────────────────
|
||||
|
||||
namespace
|
||||
{
|
||||
// Begin has both a nullary entry and a startup-data overload. The right one
|
||||
// is picked by whether the machine was launched with data.
|
||||
class Seeded : public Fsm::Machine<Seeded>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Begin : State {
|
||||
Task<StateKey> run() // no startup data
|
||||
{
|
||||
co_return succeed(0);
|
||||
}
|
||||
Task<StateKey> run(int seed) // with startup data
|
||||
{
|
||||
co_return succeed(seed);
|
||||
}
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
class Launcher : public Fsm::Machine<Launcher>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct States {
|
||||
struct Go : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Seeded, After>(7);
|
||||
}
|
||||
};
|
||||
struct After : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed(s.as<int>());
|
||||
}
|
||||
};
|
||||
};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test startup_entry_used_when_launched_with_data()
|
||||
{
|
||||
Launcher fsm; // Seeded launched via startMachine<Seeded, After>(7)
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
Void::Testing::expect_eq(*outcome, 7); // run(int) selected
|
||||
}
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test nullary_entry_used_without_startup_data()
|
||||
{
|
||||
Seeded fsm; // started normally, no startup data
|
||||
const auto outcome = fsm.run_blocking();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
Void::Testing::expect_eq(*outcome, 0); // run() selected
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -30,7 +31,7 @@ namespace
|
||||
std::vector<int>* order = nullptr;
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
// Two typed mailboxes: pull whichever arrives.
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
// Composite sub-states: a parent state runs a child region (run_region) that
|
||||
// shares the parent's executor, event mailbox and services. The child's
|
||||
@@ -31,17 +32,18 @@ namespace
|
||||
using Success = std::string;
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto ev = co_await await_any<Tick, Cancel>();
|
||||
if (std::holds_alternative<Cancel>(ev)) {
|
||||
co_return fail("cancelled");
|
||||
}
|
||||
co_return succeed(std::string{"ticked"});
|
||||
}
|
||||
struct States {
|
||||
struct Waiting : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto ev = co_await await_any<Tick, Cancel>();
|
||||
if (std::holds_alternative<Cancel>(ev)) {
|
||||
co_return fail("cancelled");
|
||||
}
|
||||
co_return succeed(std::string{"ticked"});
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Waiting>;
|
||||
|
||||
explicit Work(MachineOptions opts = {})
|
||||
: Void::Fsm::Machine<Work>(opts)
|
||||
@@ -57,23 +59,24 @@ namespace
|
||||
|
||||
using Success = std::string;
|
||||
|
||||
struct Running : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto r = co_await run_region<Work>();
|
||||
if (r.has_value()) {
|
||||
co_return succeed(*r);
|
||||
}
|
||||
co_return next<Aborted>();
|
||||
}
|
||||
struct States {
|
||||
struct Running : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto r = co_await run_region<Work>();
|
||||
if (r.has_value()) {
|
||||
co_return succeed(*r);
|
||||
}
|
||||
co_return next<Aborted>();
|
||||
}
|
||||
};
|
||||
struct Aborted : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(std::string{"aborted"});
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Aborted : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return succeed(std::string{"aborted"});
|
||||
}
|
||||
};
|
||||
using States = Void::Fsm::States<Running, Aborted>;
|
||||
|
||||
explicit Job(MachineOptions opts = {})
|
||||
: Void::Fsm::Machine<Job>(opts)
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::Resume;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// run_region<Sub>(Resume::History) re-enters a region at the sub-state it last
|
||||
@@ -23,17 +24,18 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
++g_a_runs;
|
||||
co_return next<B>();
|
||||
}
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
++g_a_runs;
|
||||
co_return next<B>();
|
||||
}
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(2); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Fsm::States<A, B>;
|
||||
};
|
||||
|
||||
class Host : public Fsm::Machine<Host>
|
||||
@@ -42,16 +44,18 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await run_region<Region>(); // Initial: A then B
|
||||
co_await run_region<Region>(
|
||||
Resume::History); // History: B only
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await run_region<Region>(); // Initial: A
|
||||
// then B
|
||||
co_await run_region<Region>(
|
||||
Resume::History); // History: B only
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -73,15 +77,16 @@ Void::Testing::Test initial_reentry_restarts_from_the_top()
|
||||
// Two plain (Initial) entries run A both times.
|
||||
struct H2 : Fsm::Machine<H2> {
|
||||
using Success = int;
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await run_region<Region>();
|
||||
co_await run_region<Region>(); // Initial again
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await run_region<Region>();
|
||||
co_await run_region<Region>(); // Initial again
|
||||
co_return succeed(g_a_runs);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
};
|
||||
H2 fsm;
|
||||
const auto outcome = fsm.run_blocking();
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
using Void::Fsm::Transition;
|
||||
|
||||
namespace
|
||||
@@ -21,44 +22,44 @@ namespace
|
||||
|
||||
std::vector<std::string> log;
|
||||
|
||||
struct A : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter A");
|
||||
co_return;
|
||||
}
|
||||
Task<Step> run()
|
||||
{
|
||||
self().log.push_back("run A");
|
||||
co_return next<B>();
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit A");
|
||||
co_return;
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter A");
|
||||
co_return;
|
||||
}
|
||||
Task<StateKey> run()
|
||||
{
|
||||
self().log.push_back("run A");
|
||||
co_return next<B>();
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit A");
|
||||
co_return;
|
||||
}
|
||||
};
|
||||
|
||||
struct B : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter B");
|
||||
co_return;
|
||||
}
|
||||
Task<Step> run()
|
||||
{
|
||||
self().log.push_back("run B");
|
||||
co_return succeed(1);
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit B");
|
||||
co_return;
|
||||
}
|
||||
struct B : State {
|
||||
Task<void> on_enter() override
|
||||
{
|
||||
self().log.push_back("enter B");
|
||||
co_return;
|
||||
}
|
||||
Task<StateKey> run()
|
||||
{
|
||||
self().log.push_back("run B");
|
||||
co_return succeed(1);
|
||||
}
|
||||
Task<void> on_exit() override
|
||||
{
|
||||
self().log.push_back("exit B");
|
||||
co_return;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<A, B>;
|
||||
|
||||
Lifecycle()
|
||||
: Void::Fsm::Machine<Lifecycle>(
|
||||
MachineOptions{.own_worker = false})
|
||||
@@ -109,11 +110,12 @@ Void::Testing::Test fsm_state_names_and_path()
|
||||
Void::Testing::Test fsm_state_without_run_fails()
|
||||
{
|
||||
struct NoRun : Void::Fsm::Machine<NoRun> {
|
||||
struct Stuck : State {
|
||||
Task<void> on_enter() override { co_return; }
|
||||
// no run() override
|
||||
struct States {
|
||||
struct Stuck : State {
|
||||
Task<void> on_enter() override { co_return; }
|
||||
// no run() override
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Stuck>;
|
||||
NoRun()
|
||||
: Void::Fsm::Machine<NoRun>(MachineOptions{.own_worker = false})
|
||||
{
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -20,7 +21,7 @@ namespace
|
||||
int seed;
|
||||
|
||||
struct Compute : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
co_return succeed(m.seed * 10);
|
||||
@@ -45,7 +46,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Boom : State {
|
||||
Task<Step> run() { co_return fail("child boom"); }
|
||||
Task<StateKey> run() { co_return fail("child boom"); }
|
||||
};
|
||||
FailingChild()
|
||||
: Void::Fsm::Machine<FailingChild>(
|
||||
@@ -64,7 +65,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto a = co_await run_child<Subtotal>(3); // 30
|
||||
auto b = co_await run_child<Subtotal>(4); // 40
|
||||
@@ -91,7 +92,7 @@ namespace
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto r = co_await run_child<FailingChild>();
|
||||
if (!r.has_value()) {
|
||||
@@ -136,7 +137,7 @@ Void::Testing::Test fsm_nesting_with_worker_thread()
|
||||
using Success = int;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto a = co_await run_child<Subtotal>(5); // 50
|
||||
co_return succeed(a.value_or(-1));
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::StateKey;
|
||||
using Void::Fsm::State;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// Orthogonal regions: run_parallel<A, B>() runs both sub-machines concurrently
|
||||
@@ -22,14 +23,15 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<GoLeft>();
|
||||
co_return succeed(1);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<GoLeft>();
|
||||
co_return succeed(1);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
|
||||
class Right : public Fsm::Machine<Right>
|
||||
@@ -37,14 +39,15 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<GoRight>();
|
||||
co_return succeed(2);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<GoRight>();
|
||||
co_return succeed(2);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
|
||||
// Joins both children: their results sum to 3.
|
||||
@@ -53,15 +56,17 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto [a, b] = co_await run_parallel<Left, Right>();
|
||||
co_return succeed((a.has_value() ? *a : 0) +
|
||||
(b.has_value() ? *b : 0));
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto [a, b] =
|
||||
co_await run_parallel<Left, Right>();
|
||||
co_return succeed((a.has_value() ? *a : 0) +
|
||||
(b.has_value() ? *b : 0));
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
|
||||
explicit Both(Fsm::MachineOptions o = {}) : Fsm::Machine<Both>(o) {}
|
||||
};
|
||||
@@ -107,21 +112,25 @@ namespace
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto v = co_await run_parallel_any<Left, Right>();
|
||||
// index 1 == Right (value 2); index 0 == Left (value 1)
|
||||
if (v.index() == 1 && std::get<1>(v).has_value()) {
|
||||
co_return succeed(100 + *std::get<1>(v));
|
||||
}
|
||||
if (v.index() == 0 && std::get<0>(v).has_value()) {
|
||||
co_return succeed(*std::get<0>(v));
|
||||
}
|
||||
co_return succeed(-1);
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto v =
|
||||
co_await run_parallel_any<Left, Right>();
|
||||
// index 1 == Right (2); index 0 == Left (1)
|
||||
if (v.index() == 1 &&
|
||||
std::get<1>(v).has_value()) {
|
||||
co_return succeed(100 + *std::get<1>(v));
|
||||
}
|
||||
if (v.index() == 0 &&
|
||||
std::get<0>(v).has_value()) {
|
||||
co_return succeed(*std::get<0>(v));
|
||||
}
|
||||
co_return succeed(-1);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
|
||||
explicit Race(Fsm::MachineOptions o = {}) : Fsm::Machine<Race>(o) {}
|
||||
};
|
||||
|
||||
@@ -4,11 +4,14 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
using Void::Fsm::Transition;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
@@ -30,30 +33,30 @@ namespace
|
||||
int attempts = 0;
|
||||
int retries; // how many tries with_retry gets
|
||||
|
||||
struct Try : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto& m = self();
|
||||
const bool ok = co_await with_retry(
|
||||
m.retries, 1ms, [&m]() -> Task<bool> {
|
||||
++m.attempts;
|
||||
co_return m.attempts > m.fail_n;
|
||||
});
|
||||
co_return next_or<Fallback>(
|
||||
ok ? succeed(std::string{"ok"})
|
||||
: fail("exhausted"));
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct Try : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
const bool ok = co_await with_retry(
|
||||
m.retries, 1ms, [&m]() -> Task<bool> {
|
||||
++m.attempts;
|
||||
co_return m.attempts > m.fail_n;
|
||||
});
|
||||
co_return next_or<Fallback>(
|
||||
ok ? succeed(std::string{"ok"})
|
||||
: fail("exhausted"));
|
||||
}
|
||||
};
|
||||
|
||||
struct Fallback : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return succeed(std::string{"fallback"});
|
||||
}
|
||||
struct Fallback : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(std::string{"fallback"});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Try, Fallback>;
|
||||
|
||||
explicit Flaky(int fails, int tries) : fail_n(fails), retries(tries)
|
||||
{
|
||||
} // own worker
|
||||
@@ -91,13 +94,14 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run() { co_return next<B>(); }
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run() { co_return next<B>(); }
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
using States = Void::Fsm::States<A, B>;
|
||||
Pipe()
|
||||
: Void::Fsm::Machine<Pipe>(MachineOptions{.own_worker = false})
|
||||
{
|
||||
@@ -149,63 +153,59 @@ namespace
|
||||
struct Cancel {
|
||||
};
|
||||
|
||||
// Imperative event handling: Idle awaits Go or Cancel and routes.
|
||||
class Flow : public Void::Fsm::Machine<Flow>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.event<Go>()
|
||||
.guard([](Flow&, const Go&) { return true; })
|
||||
.template to<Active>();
|
||||
on.event<Cancel>().template to<Done>();
|
||||
on.after(1h).template to<Done>();
|
||||
}
|
||||
struct States {
|
||||
struct Idle : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto ev = co_await await_any<Go, Cancel>();
|
||||
co_return std::holds_alternative<Go>(ev)
|
||||
? next<Active>()
|
||||
: next<Done>();
|
||||
}
|
||||
};
|
||||
struct Active : State {
|
||||
Task<StateKey> run() { co_return next<Done>(); }
|
||||
};
|
||||
struct Done : State {
|
||||
Task<StateKey> run() { co_return succeed(0); }
|
||||
};
|
||||
};
|
||||
struct Active : State {
|
||||
Task<Step> run() { co_return next<Done>(); }
|
||||
};
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(0); }
|
||||
};
|
||||
using States = Void::Fsm::States<Idle, Active, Done>;
|
||||
Flow() {}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test describe_lists_states_and_reactive_edges()
|
||||
// describe() is node-level: behaviour (and therefore transitions) is chosen
|
||||
// imperatively inside each state's entry, so edges are not statically knowable.
|
||||
Void::Testing::Test describe_lists_states_node_level()
|
||||
{
|
||||
Flow fsm;
|
||||
const auto states = fsm.describe();
|
||||
Void::Testing::expect_eq(states.size(), std::size_t{3});
|
||||
|
||||
// Idle is reactive + initial, with Go/Cancel/timeout edges.
|
||||
const auto& idle = states[0];
|
||||
Void::Testing::expect_eq(idle.name, std::string{"Idle"});
|
||||
Void::Testing::expect(idle.reactive);
|
||||
Void::Testing::expect(idle.initial);
|
||||
Void::Testing::expect_eq(idle.edges.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(idle.edges[0].event, std::string{"Go"});
|
||||
Void::Testing::expect_eq(idle.edges[0].target, std::string{"Active"});
|
||||
Void::Testing::expect(idle.edges[0].guarded);
|
||||
Void::Testing::expect_eq(idle.edges[2].event, std::string{"(timeout)"});
|
||||
|
||||
// Active is imperative → no declarable edges.
|
||||
Void::Testing::expect(!states[1].reactive);
|
||||
Void::Testing::expect(states[1].edges.empty());
|
||||
// Registration order; Idle is the initial state.
|
||||
Void::Testing::expect_eq(states[0].name, std::string{"Idle"});
|
||||
Void::Testing::expect(states[0].initial);
|
||||
Void::Testing::expect_eq(states[1].name, std::string{"Active"});
|
||||
Void::Testing::expect(!states[1].initial);
|
||||
Void::Testing::expect_eq(states[2].name, std::string{"Done"});
|
||||
}
|
||||
|
||||
Void::Testing::Test to_mermaid_contains_edges()
|
||||
Void::Testing::Test to_mermaid_lists_nodes_and_initial()
|
||||
{
|
||||
Flow fsm;
|
||||
const auto diagram = fsm.to_mermaid();
|
||||
std::cout << diagram << std::endl;
|
||||
Void::Testing::expect(diagram.find("stateDiagram-v2") != std::string::npos);
|
||||
Void::Testing::expect(diagram.find("[*] --> Idle") != std::string::npos);
|
||||
Void::Testing::expect(diagram.find("Idle --> Active : Go [guard]") !=
|
||||
std::string::npos);
|
||||
Void::Testing::expect(diagram.find("Idle --> Done : Cancel") !=
|
||||
std::string::npos);
|
||||
// One node per registered state.
|
||||
Void::Testing::expect(diagram.find("\n Idle\n") != std::string::npos);
|
||||
Void::Testing::expect(diagram.find("\n Active\n") != std::string::npos);
|
||||
Void::Testing::expect(diagram.find("\n Done\n") != std::string::npos);
|
||||
}
|
||||
@@ -5,11 +5,13 @@
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace
|
||||
@@ -20,8 +22,9 @@ namespace
|
||||
struct Stop {
|
||||
};
|
||||
|
||||
// A declarative machine: Idle reacts to events with guards/actions; on
|
||||
// timeout it bails out.
|
||||
// Imperative event handling: Idle loops, awaiting either Go or Stop. A Go
|
||||
// only advances when positive (the guard, now a plain `if`); Stop leaves to
|
||||
// Done. Internal handling = stay in the loop (no transition).
|
||||
class Gate : public Void::Fsm::Machine<Gate>
|
||||
{
|
||||
public:
|
||||
@@ -32,42 +35,46 @@ namespace
|
||||
int total = 0;
|
||||
std::vector<std::string> trace;
|
||||
|
||||
struct Idle : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
// Guarded: only positive amounts advance.
|
||||
on.event<Go>()
|
||||
.guard(
|
||||
[](Gate&, const Go& g) { return g.amount > 0; })
|
||||
.action([](Gate& m, const Go& g) {
|
||||
m.total += g.amount;
|
||||
m.trace.push_back("go" +
|
||||
std::to_string(g.amount));
|
||||
})
|
||||
.template to<Idle>();
|
||||
on.event<Stop>().template to<Done>();
|
||||
on.after(10s).fail("idle timeout");
|
||||
}
|
||||
};
|
||||
struct States {
|
||||
struct Idle : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
for (;;) {
|
||||
auto ev = co_await await_any<Go, Stop>();
|
||||
if (std::holds_alternative<Stop>(ev)) {
|
||||
co_return next<Done>();
|
||||
}
|
||||
const Go g = std::get<Go>(ev);
|
||||
if (g.amount > 0) { // guard
|
||||
m.total += g.amount;
|
||||
m.trace.push_back(
|
||||
"go" + std::to_string(g.amount));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Imperative terminal state: reports the accumulated total.
|
||||
struct Done : State {
|
||||
Task<Step> run() { co_return succeed(self().total); }
|
||||
// Imperative terminal state: reports the accumulated total.
|
||||
struct Done : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return succeed(self().total);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
using States = Void::Fsm::States<Idle, Done>;
|
||||
|
||||
Gate() {} // own worker
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// Mixes a reactive (declarative, guarded) state with an imperative one.
|
||||
// Imperative event loop with a guard and an accumulating action.
|
||||
Void::Testing::Test reactive_guard_and_action()
|
||||
{
|
||||
Gate fsm;
|
||||
fsm.start();
|
||||
fsm.post(Go{5});
|
||||
fsm.post(Go{-1}); // blocked by guard, dropped
|
||||
fsm.post(Go{-1}); // blocked by the guard, ignored
|
||||
fsm.post(Go{3});
|
||||
fsm.post(Stop{}); // -> Done -> succeed(total)
|
||||
|
||||
@@ -93,17 +100,18 @@ namespace
|
||||
|
||||
using Success = std::string;
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
auto w = co_await await_event_for<Wake>(15ms);
|
||||
if (w.has_value()) {
|
||||
co_return succeed(std::string{"woken"});
|
||||
}
|
||||
co_return succeed(std::string{"timed_out"});
|
||||
}
|
||||
struct States {
|
||||
struct Waiting : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto w = co_await await_event_for<Wake>(15ms);
|
||||
if (w.has_value()) {
|
||||
co_return succeed(std::string{"woken"});
|
||||
}
|
||||
co_return succeed(std::string{"timed_out"});
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Void::Fsm::States<Waiting>;
|
||||
Sleeper() {} // own worker
|
||||
};
|
||||
} // namespace
|
||||
@@ -130,27 +138,29 @@ Void::Testing::Test await_event_for_receives_event()
|
||||
|
||||
namespace
|
||||
{
|
||||
// Reactive timeout transition (on.after().to<>).
|
||||
// Timeout transition expressed imperatively (await_event_for → branch).
|
||||
class Deadline : public Void::Fsm::Machine<Deadline>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Pending : State {
|
||||
void transitions(TransitionBuilder& on)
|
||||
{
|
||||
on.event<Wake>().template to<Resolved>();
|
||||
on.after(15ms).template to<Expired>();
|
||||
}
|
||||
struct States {
|
||||
struct Pending : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto w = co_await await_event_for<Wake>(15ms);
|
||||
co_return w.has_value() ? next<Resolved>()
|
||||
: next<Expired>();
|
||||
}
|
||||
};
|
||||
struct Resolved : State {
|
||||
Task<StateKey> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Expired : State {
|
||||
Task<StateKey> run() { co_return succeed(2); }
|
||||
};
|
||||
};
|
||||
struct Resolved : State {
|
||||
Task<Step> run() { co_return succeed(1); }
|
||||
};
|
||||
struct Expired : State {
|
||||
Task<Step> run() { co_return succeed(2); }
|
||||
};
|
||||
using States = Void::Fsm::States<Pending, Resolved, Expired>;
|
||||
Deadline() {}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -26,14 +27,14 @@ namespace
|
||||
Data data;
|
||||
|
||||
struct Ingest : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<int>(); // park here
|
||||
co_return next<Process>();
|
||||
}
|
||||
};
|
||||
struct Process : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
m.data.processed += 1;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
#include <Void/Fsm/Fsm.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
|
||||
using Void::Coro::Task;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// Demonstrates the header/source split the module is designed for: the machine
|
||||
// declares its states as forward declarations inside `struct States { … };`
|
||||
// (this block is what would live in a header), and the states are *realised*
|
||||
// out-of-line at namespace scope (this is what would live in a .cpp). The base
|
||||
// auto-registers them by reflecting `States`; no behaviour is written outside a
|
||||
// state. The constructor is also defined out-of-line, after the realisations,
|
||||
// so the states are complete when the base registers them.
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Charge {
|
||||
int amount;
|
||||
};
|
||||
struct Dispense {
|
||||
};
|
||||
|
||||
// ── "header" part ──────────────────────────────────────────────────────
|
||||
class Vending : public Fsm::Machine<Vending>
|
||||
{
|
||||
public:
|
||||
|
||||
using Success = int; // dispensed credit
|
||||
|
||||
int credit = 0;
|
||||
|
||||
struct States {
|
||||
struct Idle; // first => initial
|
||||
struct Collecting;
|
||||
struct Done;
|
||||
};
|
||||
|
||||
Vending(); // realised below, after the states
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// ── "source" part: state realisations (namespace scope) ─────────────────────
|
||||
struct Vending::States::Idle : Vending::State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Charge>(); // first coin -> start collecting
|
||||
co_return next<Collecting>();
|
||||
}
|
||||
};
|
||||
|
||||
struct Vending::States::Collecting : Vending::State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
for (;;) {
|
||||
auto ev = co_await await_any<Charge, Dispense>();
|
||||
if (std::holds_alternative<Dispense>(ev)) {
|
||||
co_return next<Done>();
|
||||
}
|
||||
m.credit += std::get<Charge>(ev).amount;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct Vending::States::Done : Vending::State {
|
||||
Task<StateKey> run() { co_return succeed(self().credit); }
|
||||
};
|
||||
|
||||
Vending::Vending() = default; // base registers Idle/Collecting/Done from States
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test split_machine_runs_with_out_of_line_states()
|
||||
{
|
||||
Vending fsm;
|
||||
fsm.start();
|
||||
fsm.send(Charge{10}); // Idle -> Collecting (first coin counted there too?)
|
||||
fsm.send(Charge{5}, Charge{10});
|
||||
fsm.send(Dispense{});
|
||||
const auto outcome = fsm.wait();
|
||||
Void::Testing::expect(outcome.has_value());
|
||||
// Idle consumes the first Charge to leave; Collecting sums 5 + 10 = 15.
|
||||
Void::Testing::expect_eq(*outcome, 15);
|
||||
}
|
||||
|
||||
Void::Testing::Test split_machine_auto_registers_states_in_order()
|
||||
{
|
||||
Vending fsm;
|
||||
const auto& names = fsm.state_names();
|
||||
Void::Testing::expect_eq(names.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(names[0], std::string{"Idle"}); // initial
|
||||
Void::Testing::expect_eq(names[1], std::string{"Collecting"});
|
||||
Void::Testing::expect_eq(names[2], std::string{"Done"});
|
||||
}
|
||||
@@ -8,15 +8,16 @@ using Void::Coro::Task;
|
||||
using Void::Fsm::ChildFailure;
|
||||
using Void::Fsm::ChildSuccess;
|
||||
using Void::Fsm::FsmError;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
namespace Fsm = Void::Fsm;
|
||||
|
||||
// startMachine<Sub, Next>(data) launches a full sub-FSM on the parent's shared
|
||||
// executor/events/services (startup data routed to Sub's initial-state
|
||||
// startup-entry), then enters Next. The engine dispatches the sub's typed
|
||||
// outcome to Next's signature-matched handler — a member taking
|
||||
// `ChildSuccess auto` (success) or `ChildFailure auto` (failure). No override,
|
||||
// no fixed names.
|
||||
// outcome to Next's signature-matched handler — a member taking `ChildSuccess`
|
||||
// (success) or `ChildFailure` (failure); the typed value is read with
|
||||
// `.as<T>()`. No override, no fixed names.
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -29,16 +30,17 @@ namespace
|
||||
using Success = int;
|
||||
using Failure = Void::Fsm::FsmError;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run(int seed)
|
||||
{
|
||||
if (seed < 0) {
|
||||
co_return fail("negative");
|
||||
}
|
||||
co_return succeed(seed * 2);
|
||||
}
|
||||
struct States {
|
||||
struct Run : State {
|
||||
Task<StateKey> run(int seed)
|
||||
{
|
||||
if (seed < 0) {
|
||||
co_return fail("negative");
|
||||
}
|
||||
co_return succeed(seed * 2);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Run>;
|
||||
};
|
||||
|
||||
class Calc : public Fsm::Machine<Calc>
|
||||
@@ -49,24 +51,27 @@ namespace
|
||||
|
||||
int input = 0;
|
||||
|
||||
struct Start : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return startMachine<Doubler, AfterDouble>(
|
||||
self().input);
|
||||
}
|
||||
struct States {
|
||||
struct Start : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Doubler, AfterDouble>(
|
||||
self().input);
|
||||
}
|
||||
};
|
||||
struct AfterDouble : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed("doubled:" +
|
||||
std::to_string(s.as<int>()));
|
||||
}
|
||||
Task<StateKey> no(ChildFailure f)
|
||||
{
|
||||
co_return succeed("failed:" +
|
||||
f.as<FsmError>().message);
|
||||
}
|
||||
};
|
||||
};
|
||||
struct AfterDouble : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed("doubled:" + std::to_string(s.value));
|
||||
}
|
||||
Task<Step> no(ChildFailure auto f)
|
||||
{
|
||||
co_return succeed("failed:" + f.value.message);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<Start, AfterDouble>;
|
||||
|
||||
explicit Calc(int in) : input(in) {}
|
||||
};
|
||||
@@ -98,10 +103,11 @@ namespace
|
||||
{
|
||||
public:
|
||||
|
||||
struct Ping : State {
|
||||
Task<Step> run() { co_return succeed(); }
|
||||
struct States {
|
||||
struct Ping : State {
|
||||
Task<StateKey> run() { co_return succeed(); }
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<Ping>;
|
||||
};
|
||||
|
||||
class Host : public Fsm::Machine<Host>
|
||||
@@ -110,14 +116,21 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Go : State {
|
||||
Task<Step> run() { co_return startMachine<Pinger, Done>(); }
|
||||
struct States {
|
||||
struct Go : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Pinger, Done>();
|
||||
}
|
||||
};
|
||||
struct Done : State {
|
||||
// void-result sub: ChildSuccess box has no value.
|
||||
Task<StateKey> ok(ChildSuccess)
|
||||
{
|
||||
co_return succeed(42);
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Done : State {
|
||||
// void-result sub: ChildSuccess box has no value.
|
||||
Task<Step> ok(ChildSuccess auto) { co_return succeed(42); }
|
||||
};
|
||||
using States = Fsm::States<Go, Done>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -140,25 +153,27 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct A : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_return startMachine<Doubler, B>(3); // 3 -> 6
|
||||
}
|
||||
struct States {
|
||||
struct A : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<Doubler, B>(3); // 3 -> 6
|
||||
}
|
||||
};
|
||||
struct B : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
// 6 -> 12
|
||||
co_return startMachine<Doubler, C>(s.as<int>());
|
||||
}
|
||||
};
|
||||
struct C : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed(s.as<int>());
|
||||
}
|
||||
};
|
||||
};
|
||||
struct B : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return startMachine<Doubler, C>(s.value); // 6 -> 12
|
||||
}
|
||||
};
|
||||
struct C : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed(s.value);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<A, B, C>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@@ -184,14 +199,15 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct W : State {
|
||||
Task<Step> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return succeed(7);
|
||||
}
|
||||
struct States {
|
||||
struct W : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_await await_event<Tick>();
|
||||
co_return succeed(7);
|
||||
}
|
||||
};
|
||||
};
|
||||
using States = Fsm::States<W>;
|
||||
};
|
||||
|
||||
class Outer : public Fsm::Machine<Outer>
|
||||
@@ -200,16 +216,20 @@ namespace
|
||||
|
||||
using Success = int;
|
||||
|
||||
struct Begin : State {
|
||||
Task<Step> run() { co_return startMachine<WaitSub, Fin>(); }
|
||||
struct States {
|
||||
struct Begin : State {
|
||||
Task<StateKey> run()
|
||||
{
|
||||
co_return startMachine<WaitSub, Fin>();
|
||||
}
|
||||
};
|
||||
struct Fin : State {
|
||||
Task<StateKey> ok(ChildSuccess s)
|
||||
{
|
||||
co_return succeed(s.as<int>());
|
||||
}
|
||||
};
|
||||
};
|
||||
struct Fin : State {
|
||||
Task<Step> ok(ChildSuccess auto s)
|
||||
{
|
||||
co_return succeed(s.value);
|
||||
}
|
||||
};
|
||||
using States = Fsm::States<Begin, Fin>;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#include <Void/Functional/Retry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <expected>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Testing::Test;
|
||||
using namespace std::chrono_literals;
|
||||
namespace R = Void::Retry;
|
||||
|
||||
struct RetryJitter : Void::Testing::Suite<RetryJitter> {
|
||||
Test full_jitter_stays_within_bounds()
|
||||
{
|
||||
R::Jittered<R::ConstantDelay> j{R::ConstantDelay{100ms},
|
||||
R::JitterMode::Full};
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const auto d = j.delay(0);
|
||||
Void::Testing::expect(d >= 0ms);
|
||||
Void::Testing::expect(d <= 100ms);
|
||||
}
|
||||
}
|
||||
|
||||
Test equal_jitter_keeps_floor()
|
||||
{
|
||||
R::Jittered<R::ConstantDelay> j{R::ConstantDelay{100ms},
|
||||
R::JitterMode::Equal};
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const auto d = j.delay(0);
|
||||
Void::Testing::expect(d >= 50ms);
|
||||
Void::Testing::expect(d <= 100ms);
|
||||
}
|
||||
}
|
||||
|
||||
Test budget_stops_retries_early()
|
||||
{
|
||||
R::Policy<R::ConstantDelay> policy;
|
||||
policy.max_attempts = 5;
|
||||
policy.backoff = R::ConstantDelay{0ms};
|
||||
policy.max_elapsed = 5ms;
|
||||
|
||||
int calls = 0;
|
||||
auto result =
|
||||
R::retry(policy, [&]() -> std::expected<int, int> {
|
||||
++calls;
|
||||
std::this_thread::sleep_for(
|
||||
10ms); // overruns the budget
|
||||
return std::unexpected{-1};
|
||||
});
|
||||
Void::Testing::expect(!result.has_value());
|
||||
// Budget (5ms) is blown after the first 10ms attempt, so we
|
||||
// stop well short of max_attempts.
|
||||
Void::Testing::expect(calls < 5);
|
||||
}
|
||||
|
||||
Test jittered_retry_still_succeeds()
|
||||
{
|
||||
R::Policy<R::Jittered<R::ConstantDelay>> policy;
|
||||
policy.max_attempts = 3;
|
||||
policy.backoff = {R::ConstantDelay{1ms}, R::JitterMode::Full};
|
||||
|
||||
int calls = 0;
|
||||
auto result =
|
||||
R::retry(policy, [&]() -> std::expected<int, int> {
|
||||
if (++calls < 2) {
|
||||
return std::unexpected{-1};
|
||||
}
|
||||
return 42;
|
||||
});
|
||||
Void::Testing::expect(result.has_value());
|
||||
Void::Testing::expect_eq(result.value(), 42);
|
||||
Void::Testing::expect_eq(calls, 2);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,45 @@
|
||||
#include <Void/Log/Field.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Request {
|
||||
std::string id = "abc";
|
||||
int retries = 0;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test field_scope_from_reflects_struct()
|
||||
{
|
||||
Request r{"xyz", 42};
|
||||
auto scope = Void::Logging::FieldScope::from(r);
|
||||
|
||||
bool has_id = false;
|
||||
bool has_retries = false;
|
||||
for (const auto& [k, v] : Void::Logging::current_fields()) {
|
||||
if (k == "id" && v == "xyz") {
|
||||
has_id = true;
|
||||
}
|
||||
if (k == "retries" && v == "42") {
|
||||
has_retries = true;
|
||||
}
|
||||
}
|
||||
Void::Testing::expect(has_id);
|
||||
Void::Testing::expect(has_retries);
|
||||
}
|
||||
|
||||
Void::Testing::Test field_scope_from_pops_on_exit()
|
||||
{
|
||||
const auto before = Void::Logging::current_fields().size();
|
||||
{
|
||||
Request r{};
|
||||
auto scope = Void::Logging::FieldScope::from(r);
|
||||
Void::Testing::expect_eq(Void::Logging::current_fields().size(),
|
||||
before + 2);
|
||||
}
|
||||
Void::Testing::expect_eq(Void::Logging::current_fields().size(), before);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#include <Void/Log/Field.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Logging::Entry;
|
||||
using Void::Logging::FieldFilter;
|
||||
using Void::Logging::JsonLinesFormatter;
|
||||
using Void::Logging::Level;
|
||||
using Void::Logging::LogfmtFormatter;
|
||||
using Void::Testing::Test;
|
||||
|
||||
Entry make_entry()
|
||||
{
|
||||
Entry e;
|
||||
e.level = Level::Info;
|
||||
e.message = "served";
|
||||
e.fields = {{"service", "ingest"},
|
||||
{"request_id", "abc123"},
|
||||
{"secret", "hunter2"}};
|
||||
return e;
|
||||
}
|
||||
|
||||
bool contains(const std::string& hay, std::string_view needle)
|
||||
{
|
||||
return hay.find(needle) != std::string::npos;
|
||||
}
|
||||
|
||||
struct StructuredFields : Void::Testing::Suite<StructuredFields> {
|
||||
Test exclude_drops_named_fields()
|
||||
{
|
||||
JsonLinesFormatter fmt;
|
||||
fmt.set_field_filter(FieldFilter{.exclude = {"secret"}});
|
||||
const auto out = fmt.format(make_entry());
|
||||
Void::Testing::expect(contains(out, "service"));
|
||||
Void::Testing::expect(contains(out, "request_id"));
|
||||
Void::Testing::expect(!contains(out, "secret"));
|
||||
Void::Testing::expect(!contains(out, "hunter2"));
|
||||
}
|
||||
|
||||
Test include_admits_only_listed_fields()
|
||||
{
|
||||
LogfmtFormatter fmt;
|
||||
fmt.set_field_filter(FieldFilter{.include = {"service"}});
|
||||
const auto out = fmt.format(make_entry());
|
||||
Void::Testing::expect(contains(out, "service=\"ingest\""));
|
||||
Void::Testing::expect(!contains(out, "request_id"));
|
||||
Void::Testing::expect(!contains(out, "secret"));
|
||||
}
|
||||
|
||||
Test no_filter_keeps_all_fields()
|
||||
{
|
||||
JsonLinesFormatter fmt;
|
||||
const auto out = fmt.format(make_entry());
|
||||
Void::Testing::expect(contains(out, "service"));
|
||||
Void::Testing::expect(contains(out, "request_id"));
|
||||
Void::Testing::expect(contains(out, "secret"));
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,89 @@
|
||||
#include <Void/Resilience/CircuitBreaker.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Resilience::CircuitBreaker;
|
||||
using Void::Testing::Test;
|
||||
using State = CircuitBreaker::State;
|
||||
using namespace std::chrono_literals;
|
||||
using TP = std::chrono::steady_clock::time_point;
|
||||
|
||||
struct ManualClock {
|
||||
std::shared_ptr<TP> now =
|
||||
std::make_shared<TP>(std::chrono::steady_clock::now());
|
||||
auto fn() const
|
||||
{
|
||||
auto p = now;
|
||||
return [p] { return *p; };
|
||||
}
|
||||
void advance(std::chrono::nanoseconds d) const { *now += d; }
|
||||
};
|
||||
|
||||
struct CircuitBreakerTests : Void::Testing::Suite<CircuitBreakerTests> {
|
||||
Test trips_open_after_threshold_failures()
|
||||
{
|
||||
ManualClock clk;
|
||||
CircuitBreaker cb{3, 1s, 1, clk.fn()};
|
||||
cb.record_failure();
|
||||
cb.record_failure();
|
||||
Void::Testing::expect(cb.state() == State::Closed);
|
||||
cb.record_failure(); // third -> open
|
||||
Void::Testing::expect(cb.state() == State::Open);
|
||||
Void::Testing::expect(!cb.allow());
|
||||
}
|
||||
|
||||
Test half_opens_after_cooldown_then_closes()
|
||||
{
|
||||
ManualClock clk;
|
||||
CircuitBreaker cb{2, 1s, 1, clk.fn()};
|
||||
cb.record_failure();
|
||||
cb.record_failure(); // open
|
||||
Void::Testing::expect(!cb.allow());
|
||||
clk.advance(1s);
|
||||
Void::Testing::expect(cb.allow()); // probe admitted (half-open)
|
||||
Void::Testing::expect(cb.state() == State::HalfOpen);
|
||||
cb.record_success(); // closes
|
||||
Void::Testing::expect(cb.state() == State::Closed);
|
||||
}
|
||||
|
||||
Test half_open_failure_reopens()
|
||||
{
|
||||
ManualClock clk;
|
||||
CircuitBreaker cb{2, 1s, 1, clk.fn()};
|
||||
cb.record_failure();
|
||||
cb.record_failure();
|
||||
clk.advance(1s);
|
||||
(void)cb.allow(); // -> half-open
|
||||
cb.record_failure();
|
||||
Void::Testing::expect(cb.state() == State::Open);
|
||||
}
|
||||
|
||||
Test execute_gates_and_records()
|
||||
{
|
||||
ManualClock clk;
|
||||
CircuitBreaker cb{2, 1s, 1, clk.fn()};
|
||||
const auto ok = [] { return std::expected<int, int>{42}; };
|
||||
const auto bad = [] {
|
||||
return std::expected<int, int>{std::unexpect, -1};
|
||||
};
|
||||
|
||||
auto r = cb.execute(ok);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect(r->has_value());
|
||||
Void::Testing::expect_eq(r->value(), 42);
|
||||
|
||||
(void)cb.execute(bad);
|
||||
(void)cb.execute(bad); // open now
|
||||
Void::Testing::expect(cb.state() == State::Open);
|
||||
|
||||
auto rejected = cb.execute(ok);
|
||||
Void::Testing::expect(!rejected.has_value()); // circuit refused
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,75 @@
|
||||
#include <Void/Resilience/KeyedRateLimiter.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Resilience::KeyedRateLimiter;
|
||||
using Void::Testing::Test;
|
||||
using namespace std::chrono_literals;
|
||||
using TP = std::chrono::steady_clock::time_point;
|
||||
|
||||
struct ManualClock {
|
||||
std::shared_ptr<TP> now =
|
||||
std::make_shared<TP>(std::chrono::steady_clock::now());
|
||||
auto fn() const
|
||||
{
|
||||
auto p = now;
|
||||
return [p] { return *p; };
|
||||
}
|
||||
void advance(std::chrono::nanoseconds d) const { *now += d; }
|
||||
};
|
||||
|
||||
struct KeyedRateLimiterTests : Void::Testing::Suite<KeyedRateLimiterTests> {
|
||||
// Each key drains its own bucket independently.
|
||||
Test keys_are_independent()
|
||||
{
|
||||
ManualClock clk;
|
||||
KeyedRateLimiter<std::uint64_t> rl{3.0, 1.0, clk.fn()};
|
||||
Void::Testing::expect(rl.allow(1));
|
||||
Void::Testing::expect(rl.allow(1));
|
||||
Void::Testing::expect(rl.allow(1));
|
||||
Void::Testing::expect(!rl.allow(1)); // key 1 exhausted
|
||||
Void::Testing::expect(rl.allow(2)); // key 2 still full
|
||||
}
|
||||
|
||||
Test refills_per_key_over_time()
|
||||
{
|
||||
ManualClock clk;
|
||||
KeyedRateLimiter<std::string> rl{2.0, 2.0, clk.fn()};
|
||||
Void::Testing::expect(rl.allow("a", 2.0));
|
||||
Void::Testing::expect(!rl.allow("a"));
|
||||
clk.advance(1s); // +2 tokens
|
||||
Void::Testing::expect(rl.allow("a"));
|
||||
}
|
||||
|
||||
Test reset_forgets_a_key()
|
||||
{
|
||||
ManualClock clk;
|
||||
KeyedRateLimiter<int> rl{1.0, 0.0, clk.fn()};
|
||||
Void::Testing::expect(rl.allow(7));
|
||||
Void::Testing::expect(!rl.allow(7));
|
||||
rl.reset(7); // next use starts full again
|
||||
Void::Testing::expect(rl.allow(7));
|
||||
}
|
||||
|
||||
Test cleanup_drops_stale_keys()
|
||||
{
|
||||
KeyedRateLimiter<int> rl{1.0, 1.0};
|
||||
(void)rl.allow(1);
|
||||
(void)rl.allow(2);
|
||||
Void::Testing::expect_eq(rl.tracked(), std::size_t{2});
|
||||
// Nothing is older than an hour yet.
|
||||
Void::Testing::expect_eq(rl.cleanup(1h), std::size_t{0});
|
||||
Void::Testing::expect_eq(rl.tracked(), std::size_t{2});
|
||||
// Everything is older than 0ns.
|
||||
Void::Testing::expect_eq(rl.cleanup(0ns), std::size_t{2});
|
||||
Void::Testing::expect_eq(rl.tracked(), std::size_t{0});
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,55 @@
|
||||
#include <Void/Resilience/RateLimiter.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Resilience::TokenBucket;
|
||||
using Void::Testing::Test;
|
||||
using namespace std::chrono_literals;
|
||||
using TP = std::chrono::steady_clock::time_point;
|
||||
|
||||
struct ManualClock {
|
||||
std::shared_ptr<TP> now =
|
||||
std::make_shared<TP>(std::chrono::steady_clock::now());
|
||||
auto fn() const
|
||||
{
|
||||
auto p = now;
|
||||
return [p] { return *p; };
|
||||
}
|
||||
void advance(std::chrono::nanoseconds d) const { *now += d; }
|
||||
};
|
||||
|
||||
struct RateLimiterTests : Void::Testing::Suite<RateLimiterTests> {
|
||||
Test starts_full_and_drains()
|
||||
{
|
||||
ManualClock clk;
|
||||
TokenBucket b{10.0, 5.0, clk.fn()};
|
||||
Void::Testing::expect(b.try_acquire(10.0)); // drains the bucket
|
||||
Void::Testing::expect(!b.try_acquire(1.0)); // now empty
|
||||
}
|
||||
|
||||
Test refills_over_time()
|
||||
{
|
||||
ManualClock clk;
|
||||
TokenBucket b{10.0, 5.0, clk.fn()};
|
||||
Void::Testing::expect(b.try_acquire(10.0));
|
||||
clk.advance(1s); // +5 tokens
|
||||
Void::Testing::expect(b.try_acquire(5.0));
|
||||
Void::Testing::expect(!b.try_acquire(0.5));
|
||||
}
|
||||
|
||||
Test refill_is_clamped_to_capacity()
|
||||
{
|
||||
ManualClock clk;
|
||||
TokenBucket b{10.0, 5.0, clk.fn()};
|
||||
Void::Testing::expect(b.try_acquire(10.0));
|
||||
clk.advance(100s); // would be 500 tokens, clamps to 10
|
||||
Void::Testing::expect(b.available() <= 10.0);
|
||||
Void::Testing::expect(b.available() >= 9.99);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,51 @@
|
||||
#include <Void/Resilience/ResourceMonitor.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Resilience::ResourceMonitor;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ResourceMonitorTests : Void::Testing::Suite<ResourceMonitorTests> {
|
||||
Test acquire_refuses_to_exceed_limit()
|
||||
{
|
||||
ResourceMonitor m{100};
|
||||
Void::Testing::expect(m.try_acquire(80));
|
||||
Void::Testing::expect(!m.try_acquire(30)); // would be 110 > 100
|
||||
Void::Testing::expect_eq(m.usage(), std::uint64_t{80});
|
||||
}
|
||||
|
||||
Test high_watermark_fires_once_on_crossing()
|
||||
{
|
||||
ResourceMonitor m{100, 0.9, 0.7};
|
||||
int highs = 0;
|
||||
m.on_high_watermark([&](std::uint64_t) { ++highs; });
|
||||
Void::Testing::expect(m.try_acquire(80)); // 80 < 90, no fire
|
||||
Void::Testing::expect_eq(highs, 0);
|
||||
Void::Testing::expect(m.try_acquire(15)); // 95 >= 90, fire
|
||||
Void::Testing::expect_eq(highs, 1);
|
||||
Void::Testing::expect(m.try_acquire(3)); // 98, still alarmed
|
||||
Void::Testing::expect_eq(highs, 1); // no re-fire
|
||||
}
|
||||
|
||||
Test low_watermark_fires_on_drop()
|
||||
{
|
||||
ResourceMonitor m{100, 0.9, 0.7};
|
||||
int lows = 0;
|
||||
m.on_low_watermark([&](std::uint64_t) { ++lows; });
|
||||
Void::Testing::expect(m.try_acquire(95)); // alarmed
|
||||
m.release(30); // 65 <= 70 -> fire
|
||||
Void::Testing::expect_eq(lows, 1);
|
||||
Void::Testing::expect_eq(m.usage(), std::uint64_t{65});
|
||||
}
|
||||
|
||||
Test release_clamps_at_zero()
|
||||
{
|
||||
ResourceMonitor m{100};
|
||||
Void::Testing::expect(m.try_acquire(10));
|
||||
m.release(50); // more than held
|
||||
Void::Testing::expect_eq(m.usage(), std::uint64_t{0});
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,19 @@
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct IClock {
|
||||
virtual ~IClock() = default;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// @tag reflection
|
||||
Void::Testing::Test service_interface_name_is_reflected()
|
||||
{
|
||||
Void::Testing::expect_eq(Void::Service::interface_name<IClock>(),
|
||||
std::string{"IClock"});
|
||||
}
|
||||
@@ -15,7 +15,8 @@ using Void::Coro::Task;
|
||||
using Void::Fsm::MachineOptions;
|
||||
using Void::Fsm::Orchestrator;
|
||||
using Void::Fsm::Status;
|
||||
using Void::Fsm::Step;
|
||||
using Void::Fsm::State;
|
||||
using Void::Fsm::StateKey;
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -75,7 +76,7 @@ namespace
|
||||
int times;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
auto& m = self();
|
||||
int last = 0;
|
||||
@@ -116,7 +117,7 @@ Void::Testing::Test orchestrator_launches_and_supervises()
|
||||
using Success = int;
|
||||
|
||||
struct Run : State {
|
||||
Task<Step> run()
|
||||
Task<StateKey> run()
|
||||
{
|
||||
int last = 0;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Service::ServiceRegistry;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct IGreeter {
|
||||
virtual ~IGreeter() = default;
|
||||
virtual int id() const = 0;
|
||||
};
|
||||
struct Greeter : IGreeter {
|
||||
int v;
|
||||
explicit Greeter(int x) : v{x} {}
|
||||
int id() const override { return v; }
|
||||
};
|
||||
|
||||
struct IOther {
|
||||
virtual ~IOther() = default;
|
||||
};
|
||||
struct Other : IOther {
|
||||
};
|
||||
|
||||
struct ScopedRegistry : Void::Testing::Suite<ScopedRegistry> {
|
||||
Test child_falls_through_to_parent()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
parent.provide<IGreeter>(std::make_shared<Greeter>(1));
|
||||
|
||||
ServiceRegistry child{&parent};
|
||||
Void::Testing::expect(child.has<IGreeter>());
|
||||
Void::Testing::expect_eq(child.require<IGreeter>().id(), 1);
|
||||
}
|
||||
|
||||
Test child_shadows_parent()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
parent.provide<IGreeter>(std::make_shared<Greeter>(1));
|
||||
|
||||
ServiceRegistry child{&parent};
|
||||
child.provide<IGreeter>(std::make_shared<Greeter>(2));
|
||||
|
||||
Void::Testing::expect_eq(child.require<IGreeter>().id(), 2);
|
||||
// Parent is untouched.
|
||||
Void::Testing::expect_eq(parent.require<IGreeter>().id(), 1);
|
||||
}
|
||||
|
||||
Test child_local_provide_invisible_to_parent()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
ServiceRegistry child{&parent};
|
||||
child.provide<IOther>(std::make_shared<Other>());
|
||||
|
||||
Void::Testing::expect(child.has<IOther>());
|
||||
Void::Testing::expect(!parent.has<IOther>());
|
||||
}
|
||||
|
||||
Test miss_in_both_returns_nullptr()
|
||||
{
|
||||
ServiceRegistry parent;
|
||||
ServiceRegistry child{&parent};
|
||||
Void::Testing::expect(child.get<IGreeter>() == nullptr);
|
||||
Void::Testing::expect(!child.has<IGreeter>());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,43 @@
|
||||
#include <Void/System/Metrics.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct MetricsTests : Void::Testing::Suite<MetricsTests> {
|
||||
// On Linux these return real values; elsewhere nullopt (skip).
|
||||
Test process_memory_is_plausible()
|
||||
{
|
||||
const auto rss = Void::SystemInfo::process_memory_bytes();
|
||||
if (rss.has_value()) {
|
||||
Void::Testing::expect(*rss > 0);
|
||||
}
|
||||
}
|
||||
|
||||
Test system_memory_total_positive()
|
||||
{
|
||||
const auto mem = Void::SystemInfo::system_memory();
|
||||
if (mem.has_value()) {
|
||||
Void::Testing::expect(mem->total > 0);
|
||||
Void::Testing::expect(mem->available <= mem->total);
|
||||
}
|
||||
}
|
||||
|
||||
Test cpu_sampler_is_non_negative()
|
||||
{
|
||||
Void::SystemInfo::CpuSampler sampler;
|
||||
// Burn a little CPU so a second sample has something to report.
|
||||
volatile double sink = 0.0;
|
||||
for (int i = 0; i < 1'000'000; ++i) {
|
||||
sink += static_cast<double>(i) * 0.5;
|
||||
}
|
||||
(void)sink;
|
||||
const double usage = sampler.usage();
|
||||
Void::Testing::expect(usage >= 0.0);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,66 @@
|
||||
#include <Void/System/Process.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct ProcessStream : Void::Testing::Suite<ProcessStream> {
|
||||
// stdout lines are delivered to the callback as they arrive, and
|
||||
// the full output is still captured.
|
||||
Test streams_stdout_lines()
|
||||
{
|
||||
std::vector<std::string> lines;
|
||||
Void::Process::StreamCallbacks cb;
|
||||
cb.on_stdout = [&](std::string_view l) {
|
||||
lines.emplace_back(l);
|
||||
};
|
||||
|
||||
auto r = Void::Process::run_streaming(
|
||||
"/bin/sh", {"-c", "printf 'a\\nb\\nc\\n'"}, cb);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(r->exit_code, 0);
|
||||
|
||||
const std::vector<std::string> expected{"a", "b", "c"};
|
||||
Void::Testing::expect(lines == expected);
|
||||
Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"});
|
||||
}
|
||||
|
||||
// A trailing partial line (no newline) is flushed at EOF.
|
||||
Test flushes_trailing_partial_line()
|
||||
{
|
||||
std::vector<std::string> lines;
|
||||
Void::Process::StreamCallbacks cb;
|
||||
cb.on_stdout = [&](std::string_view l) {
|
||||
lines.emplace_back(l);
|
||||
};
|
||||
|
||||
auto r = Void::Process::run_streaming(
|
||||
"/bin/sh", {"-c", "printf 'no-newline'"}, cb);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(lines.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(lines.at(0),
|
||||
std::string{"no-newline"});
|
||||
}
|
||||
|
||||
// stderr is routed to its own callback.
|
||||
Test streams_stderr_separately()
|
||||
{
|
||||
std::vector<std::string> errs;
|
||||
Void::Process::StreamCallbacks cb;
|
||||
cb.on_stderr = [&](std::string_view l) {
|
||||
errs.emplace_back(l);
|
||||
};
|
||||
|
||||
auto r = Void::Process::run_streaming(
|
||||
"/bin/sh", {"-c", "printf 'oops\\n' 1>&2"}, cb);
|
||||
Void::Testing::expect(r.has_value());
|
||||
Void::Testing::expect_eq(errs.size(), std::size_t{1});
|
||||
Void::Testing::expect_eq(errs.at(0), std::string{"oops"});
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -1,28 +1,27 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Fixture.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
class VectorFixture : public Void::Testing::Fixture
|
||||
namespace
|
||||
{
|
||||
public:
|
||||
using Void::Testing::Test;
|
||||
|
||||
std::vector<int> vec;
|
||||
// setup()/teardown() run around each test method (a fresh instance per
|
||||
// test), exactly like the old Fixture base — but discovered by reflection.
|
||||
struct ContainerFixture : Void::Testing::Suite<ContainerFixture> {
|
||||
std::vector<int> vec;
|
||||
|
||||
void setup() override { vec = {1, 2, 3}; }
|
||||
void teardown() override { vec.clear(); }
|
||||
void setup() { vec = {1, 2, 3}; }
|
||||
void teardown() { vec.clear(); }
|
||||
|
||||
Void::Testing::Test size()
|
||||
{
|
||||
Void::Testing::expect_eq(vec.size(), 3u);
|
||||
}
|
||||
Test size() { Void::Testing::expect_eq(vec.size(), 3u); }
|
||||
|
||||
// @tag slow
|
||||
Void::Testing::Test push_back()
|
||||
{
|
||||
vec.push_back(4);
|
||||
Void::Testing::expect_eq(vec.size(), 4u);
|
||||
Void::Testing::expect_eq(vec.back(), 4);
|
||||
}
|
||||
};
|
||||
[[= Void::Testing::tag("slow")]] Test push_back()
|
||||
{
|
||||
vec.push_back(4);
|
||||
Void::Testing::expect_eq(vec.size(), 4u);
|
||||
Void::Testing::expect_eq(vec.back(), 4);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
@@ -0,0 +1,46 @@
|
||||
#include <Void/TestingMock/Reflect.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct IDb {
|
||||
virtual ~IDb() = default;
|
||||
virtual int query(std::string_view s) = 0;
|
||||
virtual void close() = 0;
|
||||
int helper() { return 0; } // non-virtual — ignored
|
||||
};
|
||||
struct GoodMock : IDb {
|
||||
int query(std::string_view) override { return 0; }
|
||||
void close() override {}
|
||||
};
|
||||
struct BadMock : IDb {
|
||||
int query(std::string_view) override { return 0; }
|
||||
// missing close() → still abstract
|
||||
};
|
||||
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct MockReflect : Void::Testing::Suite<MockReflect> {
|
||||
Test lists_virtual_methods()
|
||||
{
|
||||
const auto names = Void::TestingMock::method_names<IDb>();
|
||||
Void::Testing::expect_eq(names.size(), std::size_t{2});
|
||||
Void::Testing::expect(names[0] == "query" &&
|
||||
names[1] == "close");
|
||||
static_assert(Void::TestingMock::method_count<IDb>() == 2);
|
||||
}
|
||||
|
||||
Test covers_detects_completeness()
|
||||
{
|
||||
static_assert(Void::TestingMock::covers<GoodMock, IDb>());
|
||||
static_assert(!Void::TestingMock::covers<BadMock, IDb>());
|
||||
Void::Testing::expect(
|
||||
Void::TestingMock::covers<GoodMock, IDb>());
|
||||
Void::Testing::expect(
|
||||
!Void::TestingMock::covers<BadMock, IDb>());
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
Reference in new issue
Block a user