diff --git a/oslo_messaging/_drivers/common.py b/oslo_messaging/_drivers/common.py index 89ad0660e..1dda9fe85 100644 --- a/oslo_messaging/_drivers/common.py +++ b/oslo_messaging/_drivers/common.py @@ -18,10 +18,10 @@ import copy import logging import sys -import time import traceback from oslo_serialization import jsonutils +from oslo_utils import timeutils import six import oslo_messaging @@ -334,24 +334,16 @@ def deserialize_msg(msg): class DecayingTimer(object): def __init__(self, duration=None): - self._duration = duration - self._ends_at = None + self._watch = timeutils.StopWatch(duration=duration) def start(self): - if self._duration is not None: - self._ends_at = time.time() + max(0, self._duration) + self._watch.start() def check_return(self, timeout_callback=None, *args, **kwargs): maximum = kwargs.pop('maximum', None) - - if self._duration is None: + left = self._watch.leftover(return_none=True) + if left is None: return maximum - if self._ends_at is None: - raise RuntimeError(_("Can not check/return a timeout from a timer" - " that has not been started.")) - - left = self._ends_at - time.time() if left <= 0 and timeout_callback is not None: timeout_callback(*args, **kwargs) - return left if maximum is None else min(left, maximum) diff --git a/oslo_messaging/tests/test_utils.py b/oslo_messaging/tests/test_utils.py index 84b677a64..16ea682b6 100644 --- a/oslo_messaging/tests/test_utils.py +++ b/oslo_messaging/tests/test_utils.py @@ -13,8 +13,6 @@ # License for the specific language governing permissions and limitations # under the License. -import time - import mock from oslo_messaging._drivers import common @@ -67,16 +65,24 @@ class TimerTestCase(test_utils.BaseTestCase): remaining = t.check_return(maximum=2) self.assertEqual(2, remaining) - def test_duration_expired_no_callback(self): + @mock.patch('oslo_utils.timeutils.now') + def test_duration_expired_no_callback(self, now): + now.return_value = 0 t = common.DecayingTimer(2) - t._ends_at = time.time() - 10 - remaining = t.check_return() - self.assertAlmostEqual(-10, remaining, 0) + t.start() - def test_duration_callback(self): + now.return_value = 3 + remaining = t.check_return() + self.assertEqual(0, remaining) + + @mock.patch('oslo_utils.timeutils.now') + def test_duration_callback(self, now): + now.return_value = 0 t = common.DecayingTimer(2) - t._ends_at = time.time() - 10 + t.start() + + now.return_value = 3 callback = mock.Mock() remaining = t.check_return(callback) - self.assertAlmostEqual(-10, remaining, 0) + self.assertEqual(0, remaining) callback.assert_called_once