Skip to content

Commit

Permalink
FakeDate: raise when comparing FakeDate and datetime objects
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaspiatkowski committed Sep 26, 2024
1 parent 5f171db commit ea7f213
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
21 changes: 21 additions & 0 deletions freezegun/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,27 @@ def __sub__(self, other: Any) -> "FakeDate": # type: ignore
else:
return result # type: ignore

def __le__(self, other) -> bool:
if isinstance(other, real_date) and not isinstance(other, real_datetime):
return real_date.__le__(self, other) <= 0
return NotImplemented

def __lt__(self, other) -> bool:
if isinstance(other, real_date) and not isinstance(other, real_datetime):
return real_date.__lt__(self, other) < 0
return NotImplemented

def __ge__(self, other) -> bool:
if isinstance(other, real_date) and not isinstance(other, real_datetime):
return real_date.__ge__(self, other) >= 0
return NotImplemented

def __gt__(self, other) -> bool:
if isinstance(other, real_date) and not isinstance(other, real_datetime):
return real_date.__gt__(self, other) > 0
return NotImplemented


@classmethod
def today(cls: Type["FakeDate"]) -> "FakeDate":
result = cls._date_to_freeze() + cls._tz_offset()
Expand Down
31 changes: 31 additions & 0 deletions tests/test_datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import calendar
import datetime
import fractions
import itertools
import unittest
import locale
import sys
Expand Down Expand Up @@ -826,3 +827,33 @@ def test_datetime_in_timezone(monkeypatch: pytest.MonkeyPatch) -> None:
assert datetime.datetime.now() == datetime.datetime(1970, 1, 1, 1, 0, 0)
finally:
time.tzset() # set the timezone back to what is was before


def test_cannot_compare_date_and_datetime() -> None:
std_date = datetime.date(2012, 1, 14)
std_datetime = datetime.datetime(2012, 1, 14, 12, 0, 0)
fake_date = FakeDate(2012, 1, 14)
fake_datetime = FakeDatetime(2012, 1, 14, 12, 0, 0)

d_objs = (std_date, fake_date)
dt_objs = (std_datetime, fake_datetime)

for base, diff in itertools.chain(
itertools.product(d_objs, dt_objs), itertools.product(dt_objs, d_objs)
):
with pytest.raises(TypeError):
_ = base < diff
with pytest.raises(TypeError):
_ = base <= diff
with pytest.raises(TypeError):
_ = base > diff
with pytest.raises(TypeError):
_ = base >= diff

for base, same in itertools.chain(
itertools.product(d_objs, d_objs), itertools.product(dt_objs, dt_objs)
):
_ = base < same
_ = base <= same
_ = base > same
_ = base >= same

0 comments on commit ea7f213

Please sign in to comment.