From 5655e44118e4a226c4091f72fb87015dc718bf0b Mon Sep 17 00:00:00 2001 From: Tom Booth Date: Tue, 29 Apr 2014 18:21:56 +0100 Subject: [PATCH] Backdrop read api should always return UTC Consumers of backdrop will always want datetimes to be represented as UTC. Previously they had no timezone attached, which was rather confusing as the ISODate in mongo had a timezone. This commit will force all datetime objects coming out of backdrop into UTC before writing them out to JSON. --- backdrop/read/api.py | 3 ++- tests/read/test_read_api_json_encoder.py | 28 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 tests/read/test_read_api_json_encoder.py diff --git a/backdrop/read/api.py b/backdrop/read/api.py index fcae0a8a..dd15b50a 100644 --- a/backdrop/read/api.py +++ b/backdrop/read/api.py @@ -12,6 +12,7 @@ from ..core.data_set import DataSet from ..core.database import InvalidOperationError from ..core.repository import DataSetConfigRepository +from ..core.timeutils import as_utc GOVUK_ENV = getenv("GOVUK_ENV", "development") @@ -43,7 +44,7 @@ def default(self, obj): if isinstance(obj, ObjectId): return str(obj) if isinstance(obj, datetime.datetime): - return obj.isoformat() + return as_utc(obj).isoformat() return json.JSONEncoder.default(self, obj) app.json_encoder = JsonEncoder diff --git a/tests/read/test_read_api_json_encoder.py b/tests/read/test_read_api_json_encoder.py new file mode 100644 index 00000000..78d3a9cb --- /dev/null +++ b/tests/read/test_read_api_json_encoder.py @@ -0,0 +1,28 @@ +import unittest +import pytz + +from hamcrest import * +from datetime import datetime +from backdrop.read.api import JsonEncoder + + +class TestReadAPIJSONEcoder(unittest.TestCase): + + def test_with_utc_date(self): + obj = {'date': datetime(2014, 4, 29, 1, 0, 0, 0, pytz.utc)} + assert_that( + JsonEncoder().encode(obj), + is_('{"date": "2014-04-29T01:00:00+00:00"}')) + + def test_with_est_date(self): + est = pytz.timezone('US/Eastern') + obj = {'date': datetime(2014, 4, 29, 1, 0, 0, 0, est)} + assert_that( + JsonEncoder().encode(obj), + is_('{"date": "2014-04-29T06:00:00+00:00"}')) + + def test_with_no_tz_date(self): + obj = {'date': datetime(2014, 4, 29, 1, 0)} + assert_that( + JsonEncoder().encode(obj), + is_('{"date": "2014-04-29T01:00:00+00:00"}'))