Skip to content

Commit

Permalink
Parse datetime propeties
Browse files Browse the repository at this point in the history
- Add unit tests
  • Loading branch information
oyvindwe committed Jul 10, 2024
1 parent 61c03d1 commit f6972b5
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/python-publish.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Run tests
run: python3 -m unittest
- name: Install pypa/build
run: >-
python3 -m
Expand Down
22 changes: 20 additions & 2 deletions connectlife/appliance.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime as dt
import re
from enum import StrEnum
from typing import Dict

Expand Down Expand Up @@ -36,6 +37,10 @@ class DeviceType(StrEnum):
}


RE_DATETIME = re.compile(r"^(\d{4,5})/(\d{2})/(\d{2})T(\d{2}):(\d{2}):(\d{2})$")
MAX_DATETIME = dt.datetime(dt.MAXYEAR, 12, 31, 23, 59, 59, tzinfo=dt.UTC)


class ConnectLifeAppliance:
"""Class representing a single appliance."""

Expand Down Expand Up @@ -135,8 +140,21 @@ def device_type(self) -> DeviceType:
return self._device_type


def convert(value: str) -> int | str:
def convert(value: str) -> int | str | dt.datetime:
try:
return int(value)
except ValueError:
return value
pass
try:
# Unknown if timezone depends on property or appliance. Some properties include UTC in the name.
# Extreme values observed:
# "0002/11/30T00:00:00" (probably represents no value)
# "16679/02/18T23:47:45" (probably represents no value)
if match := RE_DATETIME.match(value):
(year, month, day, hour, minute, seconds) = map(int, match.groups())
if year > dt.MAXYEAR:
return MAX_DATETIME
return dt.datetime(year, month, day, hour, minute, seconds, tzinfo=dt.UTC)
except ValueError:
pass
return value
Empty file added connectlife/tests/__init__.py
Empty file.
29 changes: 29 additions & 0 deletions connectlife/tests/test_appliance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import datetime as dt
import unittest

from connectlife.appliance import convert


class TestAppliance(unittest.TestCase):

def test_convert_int(self):
self.assertEqual(1, convert("1"))
self.assertEqual(0, convert("0"))
self.assertEqual(-1, convert("-1"))

def test_convert_datetime(self):
self.assertEqual(
dt.datetime(2024, 9, 12, 21, 25, 33, tzinfo=dt.UTC),
convert("2024/09/12T21:25:33")
)
self.assertEqual(
dt.datetime(2, 11, 30, 00, 00, 00, tzinfo=dt.UTC),
convert("0002/11/30T00:00:00")
)
self.assertEqual(
dt.datetime(dt.MAXYEAR, 12, 31, 23, 59, 59, tzinfo=dt.UTC),
convert("16679/02/18T23:47:45")
)

def test_convert_str(self):
self.assertEqual("string", convert("string"))

0 comments on commit f6972b5

Please sign in to comment.