tests/watchdog: Add a helper for counting down with the watchdog

This reduces a bunch of duplicate code that loops through an event loop
to try and guage how long it took for the watchdog to expire.

Change-Id: Ib3b33e250b157df02eff39751277c564ea40705c
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/test/watchdog_test.cpp b/test/watchdog_test.cpp
index cb22a83..72347aa 100644
--- a/test/watchdog_test.cpp
+++ b/test/watchdog_test.cpp
@@ -1,7 +1,30 @@
-#include <watchdog_test.hpp>
+#include <chrono>
+
+#include "watchdog_test.hpp"
 
 using namespace phosphor::watchdog;
 
+seconds WdogTest::waitForWatchdog(seconds timeLimit)
+{
+    auto previousTimeRemaining = wdog->timeRemaining();
+    auto ret = 0s;
+    while (ret < timeLimit &&
+           previousTimeRemaining >= wdog->timeRemaining() &&
+           wdog->timerEnabled())
+    {
+        previousTimeRemaining = wdog->timeRemaining();
+
+        // Returns -0- on timeout and positive number on dispatch
+        auto sleepTime = 1s;
+        if(!sd_event_run(eventP.get(), microseconds(sleepTime).count()))
+        {
+            ret += sleepTime;
+        }
+    }
+
+    return ret;
+}
+
 /** @brief Make sure that watchdog is started and not enabled */
 TEST_F(WdogTest, createWdogAndDontEnable)
 {
@@ -91,19 +114,9 @@
     wdog->timeRemaining(newTime.count());
 
     // Waiting for expiration
-    int count = 0;
-    while(count < expireTime.count() && !wdog->timerExpired())
-    {
-        // Returns -0- on timeout and positive number on dispatch
-        auto sleepTime = duration_cast<microseconds>(seconds(1s));
-        if(!sd_event_run(eventP.get(), sleepTime.count()))
-        {
-            count++;
-        }
-    }
+    EXPECT_EQ(expireTime - 1s, waitForWatchdog(expireTime));
     EXPECT_TRUE(wdog->timerExpired());
     EXPECT_FALSE(wdog->timerEnabled());
-    EXPECT_EQ(expireTime.count() - 1, count);
 
     // Make sure secondary callback was not called.
     EXPECT_FALSE(expired);
@@ -132,19 +145,10 @@
                         milliseconds(defaultInterval));
 
     // Waiting default expiration
-    int count = 0;
-    while(count < expireTime.count() && !wdog->timerExpired())
-    {
-        // Returns -0- on timeout and positive number on dispatch
-        auto sleepTime = duration_cast<microseconds>(seconds(1s));
-        if(!sd_event_run(eventP.get(), sleepTime.count()))
-        {
-            count++;
-        }
-    }
+    EXPECT_EQ(expireTime - 1s, waitForWatchdog(expireTime));
+
     EXPECT_TRUE(wdog->enabled());
     EXPECT_EQ(0, wdog->timeRemaining());
     EXPECT_TRUE(wdog->timerExpired());
     EXPECT_FALSE(wdog->timerEnabled());
-    EXPECT_EQ(expireTime.count() - 1, count);
 }