2020-06-05 06:55:20 +02:00
|
|
|
from datetime import timedelta, timezone
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2017-02-28 18:39:36 +01:00
|
|
|
from dateutil import parser
|
|
|
|
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.test_classes import ZulipTestCase
|
|
|
|
from zerver.lib.timestamp import (
|
|
|
|
TimezoneNotUTCException,
|
|
|
|
ceiling_to_hour,
|
|
|
|
convert_to_UTC,
|
|
|
|
datetime_to_timestamp,
|
|
|
|
floor_to_day,
|
|
|
|
floor_to_hour,
|
|
|
|
timestamp_to_datetime,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-02-28 18:39:36 +01:00
|
|
|
class TestTimestamp(ZulipTestCase):
|
2017-11-05 10:51:25 +01:00
|
|
|
def test_datetime_and_timestamp_conversions(self) -> None:
|
2017-02-28 18:39:36 +01:00
|
|
|
timestamp = 1483228800
|
|
|
|
for dt in [
|
2021-02-12 08:20:45 +01:00
|
|
|
parser.parse("2017-01-01 00:00:00.123 UTC"),
|
|
|
|
parser.parse("2017-01-01 00:00:00.123").replace(tzinfo=timezone.utc),
|
2021-02-12 08:19:30 +01:00
|
|
|
]:
|
|
|
|
self.assertEqual(timestamp_to_datetime(timestamp), dt - timedelta(microseconds=123000))
|
2017-02-28 18:39:36 +01:00
|
|
|
self.assertEqual(datetime_to_timestamp(dt), timestamp)
|
|
|
|
|
|
|
|
for dt in [
|
2021-02-12 08:20:45 +01:00
|
|
|
parser.parse("2017-01-01 00:00:00.123+01:00"),
|
|
|
|
parser.parse("2017-01-01 00:00:00.123"),
|
2021-02-12 08:19:30 +01:00
|
|
|
]:
|
2017-02-28 18:39:36 +01:00
|
|
|
with self.assertRaises(TimezoneNotUTCException):
|
|
|
|
datetime_to_timestamp(dt)
|
2017-10-05 01:18:18 +02:00
|
|
|
|
2017-11-05 10:51:25 +01:00
|
|
|
def test_convert_to_UTC(self) -> None:
|
2021-02-12 08:20:45 +01:00
|
|
|
utc_datetime = parser.parse("2017-01-01 00:00:00.123 UTC")
|
2017-10-05 01:18:18 +02:00
|
|
|
for dt in [
|
2021-02-12 08:20:45 +01:00
|
|
|
parser.parse("2017-01-01 00:00:00.123").replace(tzinfo=timezone.utc),
|
|
|
|
parser.parse("2017-01-01 00:00:00.123"),
|
|
|
|
parser.parse("2017-01-01 05:00:00.123+05"),
|
2021-02-12 08:19:30 +01:00
|
|
|
]:
|
2017-10-05 01:18:18 +02:00
|
|
|
self.assertEqual(convert_to_UTC(dt), utc_datetime)
|
2017-10-05 01:51:49 +02:00
|
|
|
|
2017-11-05 10:51:25 +01:00
|
|
|
def test_enforce_UTC(self) -> None:
|
2021-02-12 08:20:45 +01:00
|
|
|
non_utc_datetime = parser.parse("2017-01-01 00:00:00.123")
|
2017-10-05 01:51:49 +02:00
|
|
|
for function in [floor_to_hour, floor_to_day, ceiling_to_hour, ceiling_to_hour]:
|
|
|
|
with self.assertRaises(TimezoneNotUTCException):
|
|
|
|
function(non_utc_datetime)
|