Merge bitcoin/bitcoin#34432: test: Turn ElapseSteady into SteadyClockContext

facb2aab26 test: Turn ElapseSteady into SteadyClockContext (MarcoFalke)

Pull request description:

  `ElapseSteady` was introduced a while back, but is only used in one place. It makes more sense if this were a context manager, so that mocktime does not leak from one test into the next.

  So turn it into a context manager, rename it and allow easy time advancement via e.g. `steady_ctx += 1h`.

ACKs for top commit:
  l0rinc:
    ACK facb2aab26
  ismaelsadeeq:
    utACK facb2aab26
  sedited:
    ACK facb2aab26

Tree-SHA512: 1df9cc9685d9be4d3ab8deafd99ac1a5ff752064ae54b83bacd6f44ba2c198b091558a306d49d8b1e2200ac669e95915cc792d589fb3a63b2bef7891d325a1e0
This commit is contained in:
merge-script
2026-02-02 10:44:55 +01:00
2 changed files with 21 additions and 7 deletions

View File

@@ -172,7 +172,7 @@ FUZZ_TARGET(p2p_headers_presync, .init = initialize)
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
// The steady clock is currently only used for logging, so a constant
// time-point seems acceptable for now.
ElapseSteady elapse_steady{};
SteadyClockContext steady_ctx{};
ChainstateManager& chainman = *g_testing_setup->m_node.chainman;
CBlockHeader base{chainman.GetParams().GenesisBlock()};

View File

@@ -5,16 +5,30 @@
#ifndef BITCOIN_TEST_UTIL_TIME_H
#define BITCOIN_TEST_UTIL_TIME_H
#include <util/check.h>
#include <util/time.h>
struct ElapseSteady {
/// Helper to initialize the global MockableSteadyClock, let a duration elapse,
/// and reset it after use in a test.
class SteadyClockContext
{
MockableSteadyClock::mock_time_point::duration t{MockableSteadyClock::INITIAL_MOCK_TIME};
ElapseSteady()
{
(*this)(0s); // init
}
void operator()(std::chrono::milliseconds d)
public:
/** Initialize with INITIAL_MOCK_TIME. */
explicit SteadyClockContext() { (*this) += 0s; }
/** Unset mocktime */
~SteadyClockContext() { MockableSteadyClock::ClearMockTime(); }
SteadyClockContext(const SteadyClockContext&) = delete;
SteadyClockContext& operator=(const SteadyClockContext&) = delete;
/** Change mocktime by the given duration delta */
void operator+=(std::chrono::milliseconds d)
{
Assert(d >= 0s); // Steady time can only increase monotonically.
t += d;
MockableSteadyClock::SetMockTime(t);
}