From: Christian Heller Date: Sun, 17 Mar 2024 01:00:33 +0000 (+0100) Subject: Add date validation for Days. X-Git-Url: https://plomlompom.com/repos/%7B%7Bprefix%7D%7D/static/%7B%7B%20web_path%20%7D%7D/add_task?a=commitdiff_plain;h=96b8f35df2ed6f7db0c7c8ffa8234e2925e8756c;p=plomtask Add date validation for Days. --- diff --git a/plomtask/days.py b/plomtask/days.py index 071b0b1..4e0c474 100644 --- a/plomtask/days.py +++ b/plomtask/days.py @@ -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): diff --git a/tests/test_days.py b/tests/test_days.py index c799f06..ba627e9 100644 --- a/tests/test_days.py +++ b/tests/test_days.py @@ -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')