Instead of the API, you could add a KernelMockTime for the tests, same as we do with the other clock mocks in the unit tests:
index a6184be4a6..5702508e37 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -1387,6 +1387,21 @@ BOOST_AUTO_TEST_CASE(btck_transaction_check_tests)
"00000000000000ffffffff010000000000000000015100000000");
}
+class KernelMockTime
+{
+public:
+ explicit KernelMockTime(std::chrono::seconds timestamp) { set(timestamp); }
+ ~KernelMockTime()
+ {
+ set_mock_time(std::chrono::seconds{0});
+ }
+
+ KernelMockTime(const KernelMockTime&) = delete;
+ KernelMockTime& operator=(const KernelMockTime&) = delete;
+
+ void set(std::chrono::seconds timestamp) { set_mock_time(timestamp); }
+};
+
BOOST_AUTO_TEST_CASE(btck_set_mock_time_tests)
{
// Out-of-range timestamps throw
@@ -1407,18 +1422,15 @@ BOOST_AUTO_TEST_CASE(btck_set_mock_time_tests)
const std::chrono::seconds block_time{header.Timestamp()};
// With the time set 3h before the header, the kernel must see the header as >2h in the future and reject it
- set_mock_time(block_time - std::chrono::hours{3});
+ KernelMockTime mock_time{block_time - std::chrono::hours{3}};
BlockValidationState future_state{chainman->ProcessBlockHeader(header)};
BOOST_CHECK(future_state.GetValidationMode() == ValidationMode::INVALID);
BOOST_CHECK(future_state.GetBlockValidationResult() == BlockValidationResult::TIME_FUTURE);
// At the upper bound the header is far in the past and must be accepted; this also
// confirms the future-time check's "now + 2h" computation doesn't overflow when now is at its max.
- set_mock_time(max_time);
+ mock_time.set(max_time);
BlockValidationState ok_state{chainman->ProcessBlockHeader(header)};
BOOST_CHECK(ok_state.GetValidationMode() == ValidationMode::VALID);
BOOST_CHECK(ok_state.GetBlockValidationResult() == BlockValidationResult::UNSET);
-
- // Restore the system clock so later tests aren't affected
- set_mock_time(std::chrono::seconds{0});
}
I believe this would address the concern of time bleeding from one test to the next, especially in the case of exceptions. I also believe this is much more resilient than expecting test writers and reviewers remembering that the clock needs to be manually reset.