From a9c605ea975731d66bb2ee3da73e8d13592e5a18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adeodato=20Sim=C3=B3?= Date: Fri, 20 Oct 2023 22:36:06 -0300 Subject: [PATCH] Add SealedDate class for globally-stable, maybe-incomplete dates --- bookwyrm/tests/test_sealed_date.py | 27 +++++++++++++++++++++ bookwyrm/utils/sealed_date.py | 39 ++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 bookwyrm/tests/test_sealed_date.py create mode 100644 bookwyrm/utils/sealed_date.py diff --git a/bookwyrm/tests/test_sealed_date.py b/bookwyrm/tests/test_sealed_date.py new file mode 100644 index 000000000..c01625078 --- /dev/null +++ b/bookwyrm/tests/test_sealed_date.py @@ -0,0 +1,27 @@ +""" test sealed_date module """ + +import datetime +import unittest + +from django.utils import timezone +from bookwyrm.utils import sealed_date + + +class SealedDateTest(unittest.TestCase): + def setUp(self): + self.dt = datetime.datetime(2023, 10, 20, 17, 33, 10, tzinfo=timezone.utc) + + def test_day_seal(self): + sealed = sealed_date.SealedDate.from_datetime(self.dt) + self.assertEqual(self.dt, sealed) + self.assertEqual("2023-10-20", str(sealed)) + + def test_month_seal(self): + sealed = sealed_date.MonthSeal.from_datetime(self.dt) + self.assertEqual(self.dt, sealed) + self.assertEqual("2023-10", str(sealed)) + + def test_year_seal(self): + sealed = sealed_date.YearSeal.from_datetime(self.dt) + self.assertEqual(self.dt, sealed) + self.assertEqual("2023", str(sealed)) diff --git a/bookwyrm/utils/sealed_date.py b/bookwyrm/utils/sealed_date.py new file mode 100644 index 000000000..18a0bea68 --- /dev/null +++ b/bookwyrm/utils/sealed_date.py @@ -0,0 +1,39 @@ +"""Implementation of the SealedDate class.""" + +from datetime import datetime + + +class SealedDate(datetime): # TODO: migrate from DateTimeField to DateField + @property + def has_day(self) -> bool: + return self.has_month + + @property + def has_month(self) -> bool: + return True + + def __str__(self): + return self.strftime("%Y-%m-%d") + + @classmethod + def from_datetime(cls, dt): + # pylint: disable=invalid-name + return cls.combine(dt.date(), dt.time(), tzinfo=dt.tzinfo) + + +class MonthSeal(SealedDate): + @property + def has_day(self) -> bool: + return False + + def __str__(self): + return self.strftime("%Y-%m") + + +class YearSeal(SealedDate): + @property + def has_month(self) -> bool: + return False + + def __str__(self): + return self.strftime("%Y")