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.
This commit is contained in:
MarcoFalke
2025-05-06 19:42:59 +02:00
parent d3056bc149
commit fa4fae6227

View File

@@ -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<NodeSeconds>().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