Add SealedDate class for globally-stable, maybe-incomplete dates

This commit is contained in:
Adeodato Simó 2023-10-20 22:36:06 -03:00
parent 52a979da2d
commit a9c605ea97
No known key found for this signature in database
GPG key ID: CDF447845F1A986F
2 changed files with 66 additions and 0 deletions

View file

@ -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))

View file

@ -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")