Avoid TypeError in is_older_than, is_newer_than

datetime doesn't like to subtract offset-naive and
offset-aware datetimes. To fix this we convert all
datetimes that are passed in to offset-naive objects.

Change-Id: Ib01568c9d287e319750b6bef3656fdcfc992a1b1
Closes-Bug: #1259383
This commit is contained in:
Michael Wilson 2013-12-09 21:26:34 -07:00
parent 8c77b4bb1b
commit ae931a937e
2 changed files with 16 additions and 0 deletions

View File

@ -77,6 +77,9 @@ def is_older_than(before, seconds):
"""Return True if before is older than seconds."""
if isinstance(before, six.string_types):
before = parse_strtime(before).replace(tzinfo=None)
else:
before = before.replace(tzinfo=None)
return utcnow() - before > datetime.timedelta(seconds=seconds)
@ -84,6 +87,9 @@ def is_newer_than(after, seconds):
"""Return True if after is newer than seconds."""
if isinstance(after, six.string_types):
after = parse_strtime(after).replace(tzinfo=None)
else:
after = after.replace(tzinfo=None)
return after - utcnow() > datetime.timedelta(seconds=seconds)

View File

@ -101,6 +101,11 @@ class TimeUtilsTest(test.BaseTestCase):
def test_is_older_than_str(self):
self._test_is_older_than(timeutils.strtime)
def test_is_older_than_aware(self):
"""Tests sending is_older_than an 'aware' datetime."""
self._test_is_older_than(lambda x: x.replace(
tzinfo=iso8601.iso8601.UTC))
def _test_is_newer_than(self, fn):
strptime = datetime.datetime.strptime
with mock.patch('datetime.datetime') as datetime_mock:
@ -122,6 +127,11 @@ class TimeUtilsTest(test.BaseTestCase):
def test_is_newer_than_str(self):
self._test_is_newer_than(timeutils.strtime)
def test_is_newer_than_aware(self):
"""Tests sending is_newer_than an 'aware' datetime."""
self._test_is_newer_than(lambda x: x.replace(
tzinfo=iso8601.iso8601.UTC))
def test_set_time_override_using_default(self):
now = timeutils.utcnow_ts()