home · contact · privacy
Add date validation for Days.
authorChristian Heller <c.heller@plomlompom.de>
Sun, 17 Mar 2024 01:00:33 +0000 (02:00 +0100)
committerChristian Heller <c.heller@plomlompom.de>
Sun, 17 Mar 2024 01:00:33 +0000 (02:00 +0100)
plomtask/days.py
tests/test_days.py

index 071b0b1b27d76b676d02ee4d4530563a5ba547b5..4e0c4747809bc1e352e492cf619fafb41f3f0bbb 100644 (file)
@@ -1,15 +1,27 @@
 """Collecting Day and date-related items."""
 from datetime import datetime
+from plomtask.misc import HandledException
 
 DATE_FORMAT = '%Y-%m-%d'
 
 
+def date_valid(date: str):
+    """Validate date against DATE_FORMAT, return Datetime or None."""
+    try:
+        result = datetime.strptime(date, DATE_FORMAT)
+    except (ValueError, TypeError):
+        return None
+    return result
+
+
 class Day:
     """Individual days defined by their dates."""
 
     def __init__(self, date: str):
         self.date = date
-        self.datetime = datetime.strptime(date, DATE_FORMAT)
+        self.datetime = date_valid(self.date)
+        if not self.datetime:
+            raise HandledException(f'Given date of wrong format: {self.date}')
 
     @property
     def weekday(self):
index c799f066c7628737afb42a6041786a7af8f1228a..ba627e98cfbfb2c010510f828e965678ba8e783f 100644 (file)
@@ -1,11 +1,20 @@
 """Test days module."""
 from unittest import TestCase
 from plomtask.days import Day
+from plomtask.misc import HandledException
 
 
 class DayTests(TestCase):
     """Tests for testing the days module."""
 
+    def test_Day_dates(self):
+        """Test Day's date format.."""
+        with self.assertRaises(HandledException):
+            Day('foo')
+            Day(None)
+            Day(3)
+            Day('2024-02-30')
+
     def test_Day_weekday(self):
         """Test Day.weekday."""
         self.assertEqual(Day('2024-03-17').weekday, 'Sunday')