From f8e1b34fb1d751915cd5f24a45880ec8dda5ad75 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 14:09:27 +0000 Subject: [PATCH] test: add helpers for timed waits, threads, configs and addresses - Sync.h: WaitUntil() polls a condition with a deadline; Semaphore waits with a deadline; JoiningThread joins on destruction - ControlDevice.h: Shutdown() drives a device to Exiting from any state; StateMachineThread runs the state machine and shuts it down on destruction - Transport.h: Configure() sets the session and shm properties of a test config; IpcAddress makes a unique ipc address in /tmp and removes the socket file Co-Authored-By: Claude Opus 5.5 --- test/helper/ControlDevice.h | 78 +++++++++++++++++++++++++ test/helper/Sync.h | 113 ++++++++++++++++++++++++++++++++++++ test/helper/Transport.h | 68 ++++++++++++++++++++++ 3 files changed, 259 insertions(+) create mode 100644 test/helper/Sync.h create mode 100644 test/helper/Transport.h diff --git a/test/helper/ControlDevice.h b/test/helper/ControlDevice.h index 250a94c6..cfba1267 100644 --- a/test/helper/ControlDevice.h +++ b/test/helper/ControlDevice.h @@ -9,8 +9,12 @@ #ifndef FAIR_MQ_TEST_CONTROL_H #define FAIR_MQ_TEST_CONTROL_H +#include "Sync.h" + #include +#include + namespace fair::mq::test { @@ -61,6 +65,80 @@ inline auto Control(Device& device, Cycle cycle = Cycle::FullNoStop) } } + +/// Drive the device to Exiting from any state. Use it in cleanup code: a test +/// that fails in the middle of a cycle must not leave the state machine thread +/// waiting forever. +inline auto Shutdown(Device& device) +{ + auto changeAndWait = [&](Transition transition, State from) { + if (device.ChangeState(transition)) { + WaitUntil([&] { return device.GetCurrentState() != from; }); + } + }; + + while (true) { + auto const state = device.GetCurrentState(); + switch (state) { + case State::Exiting: + case State::Error: + return; + case State::Idle: + static_cast(device.ChangeState(Transition::End)); + return; + case State::InitializingDevice: + changeAndWait(Transition::CompleteInit, state); + break; + case State::Initialized: + case State::Bound: + case State::DeviceReady: + changeAndWait(Transition::ResetDevice, state); + break; + case State::Ready: + changeAndWait(Transition::ResetTask, state); + break; + case State::Running: + changeAndWait(Transition::Stop, state); + break; + default: // a transitional state, wait for the next one + if (!WaitUntil([&] { return device.GetCurrentState() != state; })) { + return; + } + break; + } + } +} + +/// Runs Device::RunStateMachine() in a thread. On destruction, drives the +/// device to Exiting and joins the thread. +class StateMachineThread +{ + public: + explicit StateMachineThread(Device& device) + : fDevice(device) + , fThread(&Device::RunStateMachine, &device) + {} + + StateMachineThread(const StateMachineThread&) = delete; + StateMachineThread(StateMachineThread&&) = delete; + StateMachineThread& operator=(const StateMachineThread&) = delete; + StateMachineThread& operator=(StateMachineThread&&) = delete; + + ~StateMachineThread() { Join(); } + + void Join() + { + if (fThread.joinable()) { + Shutdown(fDevice); + fThread.join(); + } + } + + private: + Device& fDevice; + std::thread fThread; +}; + } #endif // FAIR_MQ_TEST_CONTROL_H diff --git a/test/helper/Sync.h b/test/helper/Sync.h new file mode 100644 index 00000000..f54beb4a --- /dev/null +++ b/test/helper/Sync.h @@ -0,0 +1,113 @@ +/******************************************************************************** + * Copyright (C) 2026 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * + * * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * + * copied verbatim in the file "LICENSE" * + ********************************************************************************/ + +#ifndef FAIR_MQ_TEST_SYNC_H +#define FAIR_MQ_TEST_SYNC_H + +#include +#include +#include +#include +#include +#include + +namespace fair::mq::test +{ + +/// Default deadline for a test to wait for an event. Long enough for slow +/// (e.g. sanitizer) builds, short enough to fail well before the ctest timeout. +constexpr auto kDefaultTimeout = std::chrono::seconds(10); + +/// Poll pred until it returns true or the timeout expires. +/// Returns the last result of pred. +template +bool WaitUntil(Pred&& pred, std::chrono::duration timeout) +{ + auto const deadline = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() >= deadline) { + return pred(); + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return true; +} + +template +bool WaitUntil(Pred&& pred) +{ + return WaitUntil(std::forward(pred), kDefaultTimeout); +} + +/// Counting semaphore with a deadline on Wait(). +/// Use it to wait for callbacks: a failing check in the callback must not +/// turn into a hang of the test. +class Semaphore +{ + public: + void Signal() + { + { + std::lock_guard lock(fMtx); + ++fCount; + } + fCv.notify_one(); + } + + /// Returns false if the timeout expires before a Signal(). + template + [[nodiscard]] bool Wait(std::chrono::duration timeout) + { + std::unique_lock lock(fMtx); + if (!fCv.wait_for(lock, timeout, [this] { return fCount > 0; })) { + return false; + } + --fCount; + return true; + } + + [[nodiscard]] bool Wait() { return Wait(kDefaultTimeout); } + + private: + std::mutex fMtx; + std::condition_variable fCv; + std::size_t fCount = 0; +}; + +/// std::thread that joins on destruction (C++17 has no std::jthread). +/// An early return from a test (e.g. a failed ASSERT_*) then does not call +/// std::terminate(). +class JoiningThread +{ + public: + template + explicit JoiningThread(F&& f, Args&&... args) + : fThread(std::forward(f), std::forward(args)...) + {} + + JoiningThread(const JoiningThread&) = delete; + JoiningThread(JoiningThread&&) = delete; + JoiningThread& operator=(const JoiningThread&) = delete; + JoiningThread& operator=(JoiningThread&&) = delete; + + ~JoiningThread() { Join(); } + + void Join() + { + if (fThread.joinable()) { + fThread.join(); + } + } + + private: + std::thread fThread; +}; + +} // namespace fair::mq::test + +#endif /* FAIR_MQ_TEST_SYNC_H */ diff --git a/test/helper/Transport.h b/test/helper/Transport.h new file mode 100644 index 00000000..ff5bc93d --- /dev/null +++ b/test/helper/Transport.h @@ -0,0 +1,68 @@ +/******************************************************************************** + * Copyright (C) 2026 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * + * * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * + * copied verbatim in the file "LICENSE" * + ********************************************************************************/ + +#ifndef FAIR_MQ_TEST_TRANSPORT_H +#define FAIR_MQ_TEST_TRANSPORT_H + +#include +#include + +#include +#include // std::remove +#include +#include + +namespace fair::mq::test +{ + +constexpr std::size_t kShmSegmentSize = 100000000; + +/// Set the properties that a transport factory in a test needs: the session, +/// the shm segment size, the shm monitor and (optionally) the expanded shm +/// metadata. Returns the session id. Set other properties after this call. +inline auto Configure(ProgOptions& config, + std::string session = tools::Uuid(), + bool expandedShmMetadata = false) -> std::string +{ + config.SetProperty("session", session); + config.SetProperty("shm-segment-size", kShmSegmentSize); + config.SetProperty("shm-monitor", true); + if (expandedShmMetadata) { + config.SetProperty("shm-metadata-msg-size", 2048); + } + return session; +} + +/// A unique ipc address. The socket file is in /tmp, and the destructor +/// removes it. +class IpcAddress +{ + public: + explicit IpcAddress(std::string_view name) + : fPath(std::string("/tmp/fmq_test_").append(name).append("_").append(std::to_string(tools::UuidHash()))) + , fAddress("ipc://" + fPath) + {} + + IpcAddress(const IpcAddress&) = delete; + IpcAddress(IpcAddress&&) = delete; + IpcAddress& operator=(const IpcAddress&) = delete; + IpcAddress& operator=(IpcAddress&&) = delete; + + ~IpcAddress() { std::remove(fPath.c_str()); } + + auto str() const -> std::string const& { return fAddress; } + operator std::string const&() const { return fAddress; } // NOLINT(google-explicit-constructor) + + private: + std::string fPath; + std::string fAddress; +}; + +} // namespace fair::mq::test + +#endif /* FAIR_MQ_TEST_TRANSPORT_H */