From ec2796a0fc0bb69b2d18dc084fc8cbe542ffde90 Mon Sep 17 00:00:00 2001 From: Dimitrios Siganos Date: Wed, 30 Mar 2022 11:42:49 +0100 Subject: [PATCH] Delay function for unit tests (#3767) Sometimes, it is useful it useful to be able to delay a unit test and have the back async processing running too. This function continuously calls io_ctx.run_one_for in system class for the specified amount of time. --- nano/test_common/system.cpp | 16 ++++++++++++++++ nano/test_common/system.hpp | 1 + 2 files changed, 17 insertions(+) diff --git a/nano/test_common/system.cpp b/nano/test_common/system.cpp index 170ba9d3..081591fe 100644 --- a/nano/test_common/system.cpp +++ b/nano/test_common/system.cpp @@ -307,6 +307,22 @@ std::error_code nano::system::poll_until_true (std::chrono::nanoseconds deadline return ec; } +/** + * This function repetitively calls io_ctx.run_one_for until delay number of milliseconds elapse. + * It can be used to sleep for a duration in unit tests whilst allowing the background io contexts to continue processing. + * @param delay milliseconds of delay + */ +void nano::system::delay_ms (std::chrono::milliseconds const & delay) +{ + auto now = std::chrono::steady_clock::now (); + auto endtime = now + delay; + while (now <= endtime) + { + io_ctx.run_one_for (endtime - now); + now = std::chrono::steady_clock::now (); + } +} + namespace { class traffic_generator : public std::enable_shared_from_this diff --git a/nano/test_common/system.hpp b/nano/test_common/system.hpp index 93ca39f4..8db2b92d 100644 --- a/nano/test_common/system.hpp +++ b/nano/test_common/system.hpp @@ -43,6 +43,7 @@ public: */ std::error_code poll (std::chrono::nanoseconds const & sleep_time = std::chrono::milliseconds (50)); std::error_code poll_until_true (std::chrono::nanoseconds deadline, std::function); + void delay_ms (std::chrono::milliseconds const & delay); void stop (); void deadline_set (std::chrono::duration const & delta); std::shared_ptr add_node (nano::node_flags = nano::node_flags (), nano::transport::transport_type = nano::transport::transport_type::tcp);