From 3c1889fbd0d7b96aae16f3479ac8aae70a7e15f7 Mon Sep 17 00:00:00 2001 From: Florent Le Coz Date: Wed, 28 Oct 2015 19:13:53 +0100 Subject: Use Catch for our test suite `make check` is also added to compile and run the tests Catch is fetched with cmake automatically into the build directory when needed --- tests/timed_events.cpp | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 tests/timed_events.cpp (limited to 'tests/timed_events.cpp') diff --git a/tests/timed_events.cpp b/tests/timed_events.cpp new file mode 100644 index 0000000..3844f3d --- /dev/null +++ b/tests/timed_events.cpp @@ -0,0 +1,62 @@ +#include "catch.hpp" + +#include + +/** + * Let Catch know how to display std::chrono::duration values + */ +namespace Catch +{ + template struct StringMaker> + { + static std::string convert(const std::chrono::duration& value) + { + return std::to_string(std::chrono::duration_cast(value).count()) + "ms"; + } + }; +} + +/** + * TODO, use a mock clock instead of relying on the real time with a sleep: + * it’s unreliable on heavy load. + */ +#include + +TEST_CASE("Test timed event expiration") +{ + SECTION("Check what happens when there is no events") + { + CHECK(TimedEventsManager::instance().get_timeout() == utils::no_timeout); + CHECK(TimedEventsManager::instance().execute_expired_events() == 0); + } + + // Add a single event + TimedEventsManager::instance().add_event(TimedEvent(std::chrono::steady_clock::now() + 50ms, [](){})); + + // The event should not yet be expired + CHECK(TimedEventsManager::instance().get_timeout() > 0ms); + CHECK(TimedEventsManager::instance().execute_expired_events() == 0); + + std::chrono::milliseconds timoute = TimedEventsManager::instance().get_timeout(); + INFO("Sleeping for " << timoute.count() << "ms"); + std::this_thread::sleep_for(timoute); + + // Event is now expired + CHECK(TimedEventsManager::instance().execute_expired_events() == 1); + CHECK(TimedEventsManager::instance().get_timeout() == utils::no_timeout); +} + +TEST_CASE("Test timed event cancellation") +{ + auto now = std::chrono::steady_clock::now(); + TimedEventsManager::instance().add_event(TimedEvent(now + 100ms, [](){ }, "un")); + TimedEventsManager::instance().add_event(TimedEvent(now + 200ms, [](){ }, "deux")); + TimedEventsManager::instance().add_event(TimedEvent(now + 300ms, [](){ }, "deux")); + + CHECK(TimedEventsManager::instance().get_timeout() > 0ms); + CHECK(TimedEventsManager::instance().size() == 3); + CHECK(TimedEventsManager::instance().cancel("un") == 1); + CHECK(TimedEventsManager::instance().size() == 2); + CHECK(TimedEventsManager::instance().cancel("deux") == 2); + CHECK(TimedEventsManager::instance().get_timeout() == utils::no_timeout); +} -- cgit v1.2.3