Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Lib/test/test_zoneinfo/test_zoneinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,37 @@ def __add__(self, other):
self.assertEqual(dt_fromutc.fold, 1)
self.assertEqual(dt.fold, 0)

def test_datetime_subclass_negative_components(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this to ZoneInfoTest? Then it verifies both the C and Python behavior.

"""Regression test for gh-154892.

Datetime subclasses may return -1 for time components. The C
accelerator should treat -1 as a valid PyLong_AsLong() result unless
an exception is set, matching the pure-Python implementation.
"""
class MinusOneDateTime(datetime):
@property
def hour(self):
return -1

@property
def minute(self):
return -1

@property
def second(self):
return -1

zi = self.zone_from_key("UTC")
dt = MinusOneDateTime(2024, 1, 1, tzinfo=zi)

self.assertEqual(dt.utcoffset(), ZERO)
self.assertEqual(dt.dst(), ZERO)
self.assertEqual(dt.tzname(), "UTC")
self.assertEqual(
zi.fromutc(dt),
datetime(2024, 1, 1, tzinfo=zi),
)


class ZoneInfoDatetimeSubclassTest(DatetimeSubclassMixin, ZoneInfoTest):
pass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fixed a bug in the C accelerator for :mod:`zoneinfo` where ``datetime``
subclasses returning ``-1`` for ``hour``, ``minute``, or ``second`` could
incorrectly raise an error due to ``PyLong_AsLong()`` sentinel handling.
6 changes: 3 additions & 3 deletions Modules/_zoneinfo.c
Original file line number Diff line number Diff line change
Expand Up @@ -2311,7 +2311,7 @@ get_local_timestamp(PyObject *dt, int64_t *local_ts)
}
hour = PyLong_AsLong(num);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not exactly the issue, but related. What if a subclass returns 2**40? Maybe PyLong_AsInt can be used.

Py_DECREF(num);
if (hour == -1) {
if (hour == -1 && PyErr_Occurred()) {
return -1;
}

Expand All @@ -2321,7 +2321,7 @@ get_local_timestamp(PyObject *dt, int64_t *local_ts)
}
minute = PyLong_AsLong(num);
Py_DECREF(num);
if (minute == -1) {
if (minute == -1 && PyErr_Occurred()) {
return -1;
}

Expand All @@ -2331,7 +2331,7 @@ get_local_timestamp(PyObject *dt, int64_t *local_ts)
}
second = PyLong_AsLong(num);
Py_DECREF(num);
if (second == -1) {
if (second == -1 && PyErr_Occurred()) {
return -1;
}
}
Expand Down
Loading