From 2df800d0fc5928d2b5d3bf1b5e3a3923e0574166 Mon Sep 17 00:00:00 2001 From: Dan Rose Date: Tue, 8 Sep 2020 11:09:06 -0500 Subject: [PATCH] Revert "Remove test that breaks the build" This reverts commit 7fe3be8d5f24db9837fff7e5b2fc45dcb464eef0. --- tests/CMakeLists.txt | 5 +++ tests/unit/unix_timer_tests.cc | 63 ++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 tests/unit/unix_timer_tests.cc diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c935252..964f27c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,4 +7,9 @@ if(UNIX) if(NOT APPLE) target_link_libraries(${PROJECT_NAME}-test util) endif() + + if(NOT APPLE) # these tests are unreliable on macOS + ament_add_gtest(${PROJECT_NAME}-test-timer unit/unix_timer_tests.cc) + target_link_libraries(${PROJECT_NAME}-test-timer ${PROJECT_NAME}) + endif() endif() diff --git a/tests/unit/unix_timer_tests.cc b/tests/unit/unix_timer_tests.cc new file mode 100644 index 0000000..5bbd1ed --- /dev/null +++ b/tests/unit/unix_timer_tests.cc @@ -0,0 +1,63 @@ +#include "gtest/gtest.h" +#include "serial/impl/unix.h" + +#include +#include + +using serial::MillisecondTimer; + +namespace { + +/** + * Do 100 trials of timing gaps between 0 and 19 milliseconds. + * Expect accuracy within one millisecond. + */ +TEST(timer_tests, short_intervals) { + for (int trial = 0; trial < 100; trial++) + { + uint32_t ms = rand() % 20; + MillisecondTimer mt(ms); + usleep(1000 * ms); + int32_t r = mt.remaining(); + + // 1ms slush, for the cost of calling usleep. + EXPECT_NEAR(r+1, 0, 1); + } +} + +TEST(timer_tests, overlapping_long_intervals) { + MillisecondTimer* timers[10]; + + // Experimentally determined. Corresponds to the extra time taken by the loops, + // the big usleep, and the test infrastructure itself. + const int slush_factor = 14; + + // Set up the timers to each time one second, 1ms apart. + for (int t = 0; t < 10; t++) + { + timers[t] = new MillisecondTimer(1000); + usleep(1000); + } + + // Check in on them after 500ms. + usleep(500000); + for (int t = 0; t < 10; t++) + { + EXPECT_NEAR(timers[t]->remaining(), 500 - slush_factor + t, 5); + } + + // Check in on them again after another 500ms and free them. + usleep(500000); + for (int t = 0; t < 10; t++) + { + EXPECT_NEAR(timers[t]->remaining(), -slush_factor + t, 5); + delete timers[t]; + } +} + +} // namespace + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}