diff --git a/CHANGELOG.md b/CHANGELOG.md index f90c9f7..c600d27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Fixed + +- model: `Edm.DateTime` accepts UTC datetimes whose tzinfo is `zoneinfo.ZoneInfo('UTC')`, `pytz.utc` or `dateutil.tz.UTC` instead of raising "Edm.DateTime accepts only UTC" - Vitor Coelho + ## [1.12.2] diff --git a/pyodata/v2/model.py b/pyodata/v2/model.py index 14a9756..3213f5d 100644 --- a/pyodata/v2/model.py +++ b/pyodata/v2/model.py @@ -389,6 +389,22 @@ def ms_since_epoch_to_datetime(value, tzinfo): f' or `FIX_SCREWED_UP_MAXIMUM_DATETIME_VALUE` as a workaround.') +def is_utc_datetime(value): + """Return True when value is an aware datetime in UTC + + Besides datetime.timezone.utc (and fixed zero offsets equal to it), accept + the UTC objects of other time zone libraries, e.g. zoneinfo.ZoneInfo('UTC'), + pytz.utc or dateutil.tz.UTC, which do not compare equal to datetime.timezone.utc. + Zones that only happen to have a zero offset at the given moment (e.g. Europe/London + in winter) are still rejected, so the result does not depend on the season. + """ + + if value.tzinfo == datetime.timezone.utc: + return True + + return value.utcoffset() == datetime.timedelta(0) and value.tzname() == 'UTC' + + def parse_datetime_literal(value): try: # fromisoformat on Python < 3.11 requires fractional seconds to be exactly @@ -431,7 +447,7 @@ def to_literal(self, value): raise PyODataModelError( f'Cannot convert value of type {type(value)} to literal. Datetime format is required.') - if value.tzinfo != datetime.timezone.utc: + if not is_utc_datetime(value): raise PyODataModelError('Edm.DateTime accepts only UTC') # Sets timezone to none to avoid including timezone information in the literal form. @@ -441,7 +457,7 @@ def to_json(self, value): if isinstance(value, str): return value - if value.tzinfo != datetime.timezone.utc: + if not is_utc_datetime(value): raise PyODataModelError('Edm.DateTime accepts only UTC') # Converts datetime into timestamp in milliseconds in UTC timezone as defined in ODATA specification diff --git a/tests/test_model_v2.py b/tests/test_model_v2.py index 87c669b..54b0a28 100644 --- a/tests/test_model_v2.py +++ b/tests/test_model_v2.py @@ -1,7 +1,8 @@ """Tests for OData Model module""" # pylint: disable=line-too-long,too-many-locals,too-many-statements,invalid-name, too-many-lines, no-name-in-module, expression-not-assigned, pointless-statement import os -from datetime import datetime, timezone, timedelta +from datetime import datetime, timezone, timedelta, tzinfo +from zoneinfo import ZoneInfo from unittest.mock import patch import pytest from pyodata.v2.model import Schema, Typ, StructTypeProperty, Types, EntityType, EdmStructTypeSerializer, \ @@ -720,6 +721,57 @@ def test_traits_datetime_with_offset_to_json(type_date_time, python_datetime, ex assert type_date_time.traits.to_json(python_datetime) == expected, comment +class FixedUTCOffsetTimezone(tzinfo): + """tzinfo with a fixed offset, used like the UTC objects of pytz or dateutil""" + + def __init__(self, offset, name): + self.offset = offset + self.name = name + + def utcoffset(self, dt): + return self.offset + + def tzname(self, dt): + return self.name + + def dst(self, dt): + return timedelta(0) + + +@pytest.mark.parametrize('utc_tzinfo,comment', [ + (timezone.utc, 'datetime.timezone.utc'), + (timezone(timedelta(0)), 'zero offset equal to timezone.utc'), + (ZoneInfo('UTC'), 'zoneinfo UTC'), + (ZoneInfo('Etc/UTC'), 'zoneinfo Etc/UTC'), + (FixedUTCOffsetTimezone(timedelta(0), 'UTC'), 'third-party UTC object, e.g. pytz.utc or dateutil.tz.UTC'), + ]) +def test_traits_datetime_accepts_any_utc_tzinfo(type_date_time, utc_tzinfo, comment): + """Edm.DateTime accepts UTC datetimes regardless of the tzinfo implementation""" + + testdate = datetime(1976, 11, 23, 3, 33, 6, microsecond=123000, tzinfo=utc_tzinfo) + assert type_date_time.traits.to_literal(testdate) == "datetime'1976-11-23T03:33:06.123000'", comment + assert type_date_time.traits.to_json(testdate) == '/Date(217567986123)/', comment + + +@pytest.mark.parametrize('non_utc_datetime,comment', [ + (datetime(1976, 11, 23, 3, 33, 6), 'naive datetime'), + (datetime(1976, 11, 23, 3, 33, 6, tzinfo=timezone(timedelta(hours=1))), 'fixed non-zero offset'), + (datetime(1976, 11, 23, 3, 33, 6, tzinfo=FixedUTCOffsetTimezone(timedelta(hours=1), 'UTC')), 'named UTC but with an offset'), + (datetime(1976, 7, 23, 3, 33, 6, tzinfo=ZoneInfo('Europe/London')), 'Europe/London in summer'), + (datetime(1976, 11, 23, 3, 33, 6, tzinfo=ZoneInfo('Europe/London')), 'Europe/London in winter (zero offset, but not UTC)'), + ]) +def test_traits_datetime_rejects_non_utc(type_date_time, non_utc_datetime, comment): + """Edm.DateTime still rejects naive and non-UTC datetimes""" + + with pytest.raises(PyODataModelError) as e_info: + type_date_time.traits.to_literal(non_utc_datetime) + assert str(e_info.value).startswith('Edm.DateTime accepts only UTC'), comment + + with pytest.raises(PyODataModelError) as e_info: + type_date_time.traits.to_json(non_utc_datetime) + assert str(e_info.value).startswith('Edm.DateTime accepts only UTC'), comment + + def test_traits_datetimeoffset(type_date_time_offset): """Test Edm.DateTimeOffset traits"""