Branch data Line data Source code
1 : : // Copyright (c) The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #ifndef BITCOIN_TEST_UTIL_TIME_H
6 : : #define BITCOIN_TEST_UTIL_TIME_H
7 : :
8 : : #include <util/check.h>
9 : : #include <util/time.h>
10 : :
11 : :
12 : : /// Helper to initialize the global MockableSteadyClock, let a duration elapse,
13 : : /// and reset it after use in a test.
14 : : class SteadyClockContext
15 : : {
16 : : MockableSteadyClock::mock_time_point::duration t{MockableSteadyClock::INITIAL_MOCK_TIME};
17 : :
18 : : public:
19 : : /** Initialize with INITIAL_MOCK_TIME. */
20 : 445 : explicit SteadyClockContext() { (*this) += 0s; }
21 : :
22 : : /** Unset mocktime */
23 : 445 : ~SteadyClockContext() { MockableSteadyClock::ClearMockTime(); }
24 : :
25 : : SteadyClockContext(const SteadyClockContext&) = delete;
26 : : SteadyClockContext& operator=(const SteadyClockContext&) = delete;
27 : :
28 : : /** Change mocktime by the given duration delta */
29 : 445 : void operator+=(std::chrono::milliseconds d)
30 : : {
31 [ - + ]: 445 : Assert(d >= 0s); // Steady time can only increase monotonically.
32 : 445 : t += d;
33 : 445 : MockableSteadyClock::SetMockTime(t);
34 : 445 : }
35 : : };
36 : :
37 : : /// Helper to initialize the global NodeClock, let a duration elapse,
38 : : /// and reset it after use in a test.
39 : : class NodeClockContext
40 : : {
41 : : NodeSeconds m_t{std::chrono::seconds::max()};
42 : :
43 : : public:
44 : : /// Initialize with the given time.
45 : 60744 : explicit NodeClockContext(NodeSeconds init_time) { set(init_time); }
46 : 4234 : explicit NodeClockContext(std::chrono::seconds init_time) { set(init_time); }
47 : : /// Initialize with current time, using the next tick to avoid going back by rounding to seconds.
48 : : explicit NodeClockContext() { set(++Now<NodeSeconds>().time_since_epoch()); }
49 : :
50 : : /// Unset mocktime.
51 : 34650 : ~NodeClockContext() { set(0s); }
52 : :
53 : : NodeClockContext(const NodeClockContext&) = delete;
54 : : NodeClockContext& operator=(const NodeClockContext&) = delete;
55 : :
56 : : /// Set mocktime.
57 [ + - ]: 105788 : void set(NodeSeconds t) { SetMockTime(m_t = t); }
58 : 38840 : void set(std::chrono::seconds t) { set(NodeSeconds{t}); }
59 : :
60 : : /// Change mocktime by the given duration delta.
61 : 8106 : void operator+=(std::chrono::seconds d) { set(m_t += d); }
62 : : void operator-=(std::chrono::seconds d) { set(m_t -= d); }
63 : : };
64 : :
65 : : #endif // BITCOIN_TEST_UTIL_TIME_H
|