"""Tests for date and time utilities.""" from datetime import date, datetime from dateutil import tz from royalty_common.constants.constants import ( OPERATING_TIMEZONE, SYSTEM_TIMEZONE) from royalty_common.utils import dates def test_safe_format_date(): """Test safe_format_date method.""" date_obj = date(year=2020, month=1, day=21) assert dates.safe_format_date(date_obj) == '2020-01-21' assert dates.safe_format_date(date_obj, '%d.%m.%y') == '21.01.20' def test_parse_date(): """Test parse_date method.""" date_obj = date(year=2020, month=1, day=21) assert dates.parse_date('2020-01-21') == date_obj assert dates.parse_date('21.01.20', '%d.%m.%y') == date_obj def test_current_timestamp(): """Test current_timestamp method.""" est_timestamp = dates.current_timestamp( timezone=tz.gettz('America/New_York')) utc_timestamp = dates.current_timestamp() assert est_timestamp.isoformat().endswith(('-04:00', '-05:00')) assert utc_timestamp.isoformat().endswith('+00:00') assert int((utc_timestamp - est_timestamp).total_seconds()) == 0 def test_operating_date_on_naive_datetime(): """A naive datetime is assumed to be in UTC.""" assert dates.operating_date( datetime(2020, 1, 1, 1)) == date(2019, 12, 31) assert dates.operating_date( datetime(2020, 1, 1, 4, 59)) == date(2019, 12, 31) assert dates.operating_date( datetime(2020, 1, 1, 5)) == date(2020, 1, 1) def test_operating_date_on_aware_datetime(): """A timezone-aware datetime's timezone is taken into account.""" assert dates.operating_date( datetime(2019, 12, 31, 23, 59, tzinfo=OPERATING_TIMEZONE) ) == date(2019, 12, 31) assert dates.operating_date( datetime(2020, 1, 1, tzinfo=OPERATING_TIMEZONE) ) == date(2020, 1, 1) def test_safe_format_datetime(): """Test safe_format_datetime util.""" dtime = datetime( year=2020, month=5, day=10, hour=5, minute=25, second=36, microsecond=123456, tzinfo=OPERATING_TIMEZONE ) assert dates.safe_format_datetime(dtime) in ( '2020-05-10T05:25:36.123456-0400', '2020-05-10T05:25:36.123456-0500' ) def test_parse_datetime(): """Test parse_datetime util.""" str_dtime = '2020-05-10T05:25:36.123456-0000' assert dates.parse_datetime(str_dtime) == datetime( year=2020, month=5, day=10, hour=5, minute=25, second=36, microsecond=123456, tzinfo=SYSTEM_TIMEZONE ) def test_is_iso_datetime(): """Test is_iso_datetime util.""" assert dates.is_iso_datetime('2020-01-01T20:56:41.091124+00:00') is True assert dates.is_iso_datetime('2020-01-01T20:56:41.091124') is True assert dates.is_iso_datetime('2020-01-01T20:56:41.091124-0000') is False