Skip to content

Commit aebf31e

Browse files
committed
Add unit test for datetimes.
1 parent 111872e commit aebf31e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

plotly/tests/test_optional/test_utils/test_utils.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from unittest import TestCase
66

77
import math
8+
import pytz
89
from datetime import datetime as dt
910
import datetime
1011
import numpy as np
@@ -88,6 +89,39 @@ def test_encode_as_numpy(self):
8889
res = utils.PlotlyJSONEncoder.encode_as_numpy(np.ma.core.masked)
8990
self.assertTrue(math.isnan(res))
9091

92+
def test_encode_as_datetime(self):
93+
94+
# should *fail* without 'utcoffset' and 'isoformat' and '__sub__' attrs
95+
non_datetimes = [datetime.date(2013, 10, 1), 'noon', 56, '00:00:00']
96+
for obj in non_datetimes:
97+
self.assertRaises(utils.NotEncodable,
98+
utils.PlotlyJSONEncoder.encode_as_datetime, obj)
99+
100+
# should succeed with 'utcoffset', 'isoformat' and '__sub__' attrs
101+
res = utils.PlotlyJSONEncoder.encode_as_datetime(
102+
datetime.datetime(2013, 10, 1)
103+
)
104+
self.assertEqual(res, '2013-10-01')
105+
106+
# should not include extraneous microsecond info if DNE
107+
res = utils.PlotlyJSONEncoder.encode_as_datetime(
108+
datetime.datetime(2013, 10, 1, microsecond=0)
109+
)
110+
self.assertEqual(res, '2013-10-01')
111+
112+
# should include microsecond info if present
113+
res = utils.PlotlyJSONEncoder.encode_as_datetime(
114+
datetime.datetime(2013, 10, 1, microsecond=10)
115+
)
116+
self.assertEqual(res, '2013-10-01 00:00:00.000010')
117+
118+
# should convert tzinfo to utc. Note that in october, we're in EDT!
119+
# therefore the 4 hour difference is correct.
120+
naive_datetime = datetime.datetime(2013, 10, 1)
121+
aware_datetime = pytz.timezone('US/Eastern').localize(naive_datetime)
122+
123+
res = utils.PlotlyJSONEncoder.encode_as_datetime(aware_datetime)
124+
self.assertEqual(res, '2013-10-01 04:00:00')
91125

92126
## JSON encoding
93127
numeric_list = [1, 2, 3]

0 commit comments

Comments
 (0)