diff --git a/aamva/card/date.py b/aamva/card/date.py new file mode 100644 index 0000000..ad17b2b --- /dev/null +++ b/aamva/card/date.py @@ -0,0 +1,27 @@ +from __future__ import annotations +import datetime + + +COUNTRY_FORMAT = { + "Canada": "YYYYMMDD", + "Mexico": "YYYYMMDD", # Assuming this format for Mexico, is untested + "USA": "MMDDYYYY"} + + +class Date(datetime.date): + @classmethod + def parse_country_date(cls, date:str, country:str) -> Date: + date_format = COUNTRY_FORMAT[country] + year_index = date_format.index("YYYY") + month_index = date_format.index("MM") + day_index = date_format.index("DD") + year = int(date[year_index:year_index + 4]) + month = int(date[month_index:month_index + 2]) + day = int(date[day_index:day_index + 2]) + return Date(year, month, day) + + def unparse_country_date(self, country: str) -> str: + return COUNTRY_FORMAT[country] \ + .replace("YYYY", str(self.year).rjust(4, "0")) \ + .replace("MM", str(self.month).rjust(2, "0")) \ + .replace("DD", str(self.day).rjust(2, "0")) diff --git a/tests/card/test_date.py b/tests/card/test_date.py new file mode 100644 index 0000000..db59b81 --- /dev/null +++ b/tests/card/test_date.py @@ -0,0 +1,27 @@ +import pytest +import datetime + +from aamva.card.date import Date + + +testdata_ids = ("Canada's date format", "Mexico's date format", "USA's date format") +testdata = ( + # ((unparsed, country, parsed), ...) + ("20240512", "Canada", (2024, 5, 12)), + ("20240512", "Mexico", (2024, 5, 12)), + ("05122024", "USA", (2024, 5, 12))) + + +@pytest.mark.parametrize("unparsed, country, parsed", testdata, ids=testdata_ids) +def test_can_parse_country_date(unparsed, country, parsed): + assert Date.parse_country_date(unparsed, country) == datetime.date(*parsed) + + +@pytest.mark.parametrize("unparsed, country, parsed", testdata, ids=testdata_ids) +def test_can_unparse_country_date(unparsed, country, parsed): + assert Date(*parsed).unparse_country_date(country) == unparsed + + +@pytest.mark.parametrize("unparsed, country, parsed", testdata, ids=testdata_ids) +def test_can_unparse_country_datetime(unparsed, country, parsed): + assert Date.unparse_country_date(datetime.date(*parsed), country) == unparsed