From fa4fae6227a0a495ab60191e22dc0af8fe7a8484 Mon Sep 17 00:00:00 2001 From: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz> Date: Tue, 6 May 2025 19:42:59 +0200 Subject: [PATCH] test: Add NodeClockContext This makes it easier to use mock-time in tests. Also, it resets the global mocktime, so that no state is leaked between test cases. --- src/test/util/time.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/test/util/time.h b/src/test/util/time.h index bcb97eb4e14..8cd9a1dafcb 100644 --- a/src/test/util/time.h +++ b/src/test/util/time.h @@ -34,4 +34,32 @@ public: } }; +/// Helper to initialize the global NodeClock, let a duration elapse, +/// and reset it after use in a test. +class NodeClockContext +{ + NodeSeconds m_t{std::chrono::seconds::max()}; + +public: + /// Initialize with the given time. + explicit NodeClockContext(NodeSeconds init_time) { set(init_time); } + explicit NodeClockContext(std::chrono::seconds init_time) { set(init_time); } + /// Initialize with current time, using the next tick to avoid going back by rounding to seconds. + explicit NodeClockContext() { set(++Now().time_since_epoch()); } + + /// Unset mocktime. + ~NodeClockContext() { set(0s); } + + NodeClockContext(const NodeClockContext&) = delete; + NodeClockContext& operator=(const NodeClockContext&) = delete; + + /// Set mocktime. + void set(NodeSeconds t) { SetMockTime(m_t = t); } + void set(std::chrono::seconds t) { set(NodeSeconds{t}); } + + /// Change mocktime by the given duration delta. + void operator+=(std::chrono::seconds d) { set(m_t += d); } + void operator-=(std::chrono::seconds d) { set(m_t -= d); } +}; + #endif // BITCOIN_TEST_UTIL_TIME_H