util: Add mockable steady_clock

This adds a NodeSteadyClock, which is a steady_clock that can be mocked
with millisecond precision.
This commit is contained in:
laanwj 2024-10-02 22:24:58 +02:00
parent ab1d3ece02
commit 03648321ec
2 changed files with 50 additions and 0 deletions

View file

@ -21,6 +21,7 @@ void UninterruptibleSleep(const std::chrono::microseconds& n) { std::this_thread
static std::atomic<std::chrono::seconds> g_mock_time{}; //!< For testing
std::atomic<bool> g_used_system_time{false};
static std::atomic<std::chrono::milliseconds> g_mock_steady_time{}; //!< For testing
NodeClock::time_point NodeClock::now() noexcept
{
@ -48,6 +49,30 @@ std::chrono::seconds GetMockTime()
return g_mock_time.load(std::memory_order_relaxed);
}
MockableSteadyClock::time_point MockableSteadyClock::now() noexcept
{
const auto mocktime{g_mock_steady_time.load(std::memory_order_relaxed)};
if (!mocktime.count()) {
g_used_system_time = true;
}
const auto ret{
mocktime.count() ?
mocktime :
std::chrono::steady_clock::now().time_since_epoch()};
return time_point{ret};
};
void MockableSteadyClock::SetMockTime(std::chrono::milliseconds mock_time_in)
{
Assert(mock_time_in >= 0s);
g_mock_steady_time.store(mock_time_in, std::memory_order_relaxed);
}
void MockableSteadyClock::ClearMockTime()
{
g_mock_steady_time.store(0ms, std::memory_order_relaxed);
}
int64_t GetTime() { return GetTime<std::chrono::seconds>().count(); }
std::string FormatISO8601DateTime(int64_t nTime)

View file

@ -31,6 +31,31 @@ using SteadyMicroseconds = std::chrono::time_point<std::chrono::steady_clock, st
using SystemClock = std::chrono::system_clock;
/**
* Version of SteadyClock that is mockable in the context of tests (set the
* current value with SetMockTime), otherwise the system steady clock.
*/
struct MockableSteadyClock : public std::chrono::steady_clock {
using time_point = std::chrono::time_point<MockableSteadyClock>;
static constexpr std::chrono::milliseconds INITIAL_MOCK_TIME{1};
/** Return current system time or mocked time, if set */
static time_point now() noexcept;
static std::time_t to_time_t(const time_point&) = delete; // unused
static time_point from_time_t(std::time_t) = delete; // unused
/** Set mock time for testing.
* When mocking the steady clock, start at INITIAL_MOCK_TIME and add durations to elapse time as necessary
* for testing.
* To stop mocking, call ClearMockTime().
*/
static void SetMockTime(std::chrono::milliseconds mock_time_in);
/** Clear mock time, go back to system steady clock. */
static void ClearMockTime();
};
void UninterruptibleSleep(const std::chrono::microseconds& n);
/**