From 96b8f35df2ed6f7db0c7c8ffa8234e2925e8756c Mon Sep 17 00:00:00 2001 From: Christian Heller Date: Sun, 17 Mar 2024 02:00:33 +0100 Subject: [PATCH] Add date validation for Days. --- plomtask/days.py | 14 +++++++++++++- tests/test_days.py | 9 +++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) 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') -- 2.30.2