Make time comparison functions accept strings

This patch makes is_older_than() and is_newer_than() accept
timestamps in string format, as returned from strtime().

Change-Id: I1dbf453cc08bd8aaeb4fee2491a1e8aa74f8bee3
This commit is contained in:
Dan Smith 2013-01-03 11:23:30 -08:00
parent 0ccb03b37a
commit 09b341db79
2 changed files with 34 additions and 8 deletions

View File

@ -71,11 +71,15 @@ def normalize_time(timestamp):
def is_older_than(before, seconds):
"""Return True if before is older than seconds."""
if isinstance(before, str):
before = parse_strtime(before).replace(tzinfo=None)
return utcnow() - before > datetime.timedelta(seconds=seconds)
def is_newer_than(after, seconds):
"""Return True if after is newer than seconds."""
if isinstance(after, str):
after = parse_strtime(after).replace(tzinfo=None)
return after - utcnow() > datetime.timedelta(seconds=seconds)

View File

@ -65,26 +65,48 @@ class TimeUtilsTest(unittest.TestCase):
t = timeutils.parse_strtime(s)
self.assertEqual(orig_t, t)
def test_is_older_than(self):
def _test_is_older_than(self, fn):
strptime = datetime.datetime.strptime
with mock.patch('datetime.datetime') as datetime_mock:
datetime_mock.utcnow.return_value = self.skynet_self_aware_time
expect_true = timeutils.is_older_than(self.one_minute_before, 59)
datetime_mock.strptime = strptime
expect_true = timeutils.is_older_than(fn(self.one_minute_before),
59)
self.assertTrue(expect_true)
expect_false = timeutils.is_older_than(self.one_minute_before, 60)
expect_false = timeutils.is_older_than(fn(self.one_minute_before),
60)
self.assertFalse(expect_false)
expect_false = timeutils.is_older_than(self.one_minute_before, 61)
expect_false = timeutils.is_older_than(fn(self.one_minute_before),
61)
self.assertFalse(expect_false)
def test_is_newer_than(self):
def test_is_older_than_datetime(self):
self._test_is_older_than(lambda x: x)
def test_is_older_than_str(self):
self._test_is_older_than(timeutils.strtime)
def _test_is_newer_than(self, fn):
strptime = datetime.datetime.strptime
with mock.patch('datetime.datetime') as datetime_mock:
datetime_mock.utcnow.return_value = self.skynet_self_aware_time
expect_true = timeutils.is_newer_than(self.one_minute_after, 59)
datetime_mock.strptime = strptime
expect_true = timeutils.is_newer_than(fn(self.one_minute_after),
59)
self.assertTrue(expect_true)
expect_false = timeutils.is_newer_than(self.one_minute_after, 60)
expect_false = timeutils.is_newer_than(fn(self.one_minute_after),
60)
self.assertFalse(expect_false)
expect_false = timeutils.is_newer_than(self.one_minute_after, 61)
expect_false = timeutils.is_newer_than(fn(self.one_minute_after),
61)
self.assertFalse(expect_false)
def test_is_newer_than_datetime(self):
self._test_is_newer_than(lambda x: x)
def test_is_newer_than_str(self):
self._test_is_newer_than(timeutils.strtime)
def test_utcnow_ts(self):
skynet_self_aware_timestamp = 872835240
dt = datetime.datetime.utcfromtimestamp(skynet_self_aware_timestamp)