|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import datetime as datetime_ |
| 4 | +import importlib |
3 | 5 | import pickle |
| 6 | +import types |
4 | 7 | import zoneinfo |
5 | 8 |
|
6 | 9 | from copy import deepcopy |
@@ -107,6 +110,52 @@ def test_utcfromtimestamp(): |
107 | 110 | assert p == dt |
108 | 111 |
|
109 | 112 |
|
| 113 | +def test_fromtimestamp_falls_back_for_negative_timestamp(monkeypatch): |
| 114 | + pendulum_datetime_module = importlib.import_module("pendulum.datetime") |
| 115 | + |
| 116 | + class FakeDateTime(datetime_.datetime): |
| 117 | + @classmethod |
| 118 | + def fromtimestamp(cls, t: float, tz: datetime_.tzinfo | None = None): |
| 119 | + if t == -43201: |
| 120 | + raise OSError("Invalid argument") |
| 121 | + |
| 122 | + return super().fromtimestamp(t, tz=tz) |
| 123 | + |
| 124 | + monkeypatch.setattr( |
| 125 | + pendulum_datetime_module, |
| 126 | + "datetime", |
| 127 | + types.SimpleNamespace(datetime=FakeDateTime, timedelta=datetime_.timedelta), |
| 128 | + ) |
| 129 | + |
| 130 | + p = pendulum.DateTime.fromtimestamp(-43201, pendulum.UTC) |
| 131 | + |
| 132 | + assert p == pendulum.datetime(1969, 12, 31, 11, 59, 59) |
| 133 | + assert p.timezone_name == "UTC" |
| 134 | + |
| 135 | + |
| 136 | +def test_utcfromtimestamp_falls_back_for_negative_timestamp(monkeypatch): |
| 137 | + pendulum_datetime_module = importlib.import_module("pendulum.datetime") |
| 138 | + |
| 139 | + class FakeDateTime(datetime_.datetime): |
| 140 | + @classmethod |
| 141 | + def utcfromtimestamp(cls, t: float): |
| 142 | + if t == -43201: |
| 143 | + raise OSError("Invalid argument") |
| 144 | + |
| 145 | + return super().utcfromtimestamp(t) |
| 146 | + |
| 147 | + monkeypatch.setattr( |
| 148 | + pendulum_datetime_module, |
| 149 | + "datetime", |
| 150 | + types.SimpleNamespace(datetime=FakeDateTime, timedelta=datetime_.timedelta), |
| 151 | + ) |
| 152 | + |
| 153 | + p = pendulum.DateTime.utcfromtimestamp(-43201) |
| 154 | + |
| 155 | + assert p == pendulum.naive(1969, 12, 31, 11, 59, 59) |
| 156 | + assert p.tzinfo is None |
| 157 | + |
| 158 | + |
110 | 159 | def test_fromordinal(): |
111 | 160 | assert datetime.fromordinal(730120) == pendulum.DateTime.fromordinal(730120) |
112 | 161 |
|
|
0 commit comments