#include #include #include #include #include namespace { using Void::EventBus::EventBus; using Void::EventBus::Mode; using Void::Testing::Test; struct Tick { int n = 0; }; struct EventBusAsync : Void::Testing::Suite { // Async handlers run on the bus worker, not the publisher thread. Test handler_runs_off_publisher_thread() { EventBus bus{Mode::Async}; std::atomic handler_thread{}; bus.subscribe([&](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 total{0}; bus.subscribe([&](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 count{0}; const auto id = bus.subscribe( [&](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([&](const Tick& t) { seen = t.n; }); bus.publish(Tick{7}); Void::Testing::expect_eq(seen, 7); // no flush needed } }; } // namespace