]> git-server-git.apps.pok.os.sepia.ceph.com Git - teuthology.git/commitdiff
util.time: Add new submodule with parse_offset()
authorZack Cerza <zack@redhat.com>
Mon, 8 Jul 2024 22:24:10 +0000 (16:24 -0600)
committerZack Cerza <zack@redhat.com>
Thu, 8 Aug 2024 00:05:15 +0000 (18:05 -0600)
Signed-off-by: Zack Cerza <zack@redhat.com>
teuthology/util/test/test_time.py [new file with mode: 0644]
teuthology/util/time.py [new file with mode: 0644]

diff --git a/teuthology/util/test/test_time.py b/teuthology/util/test/test_time.py
new file mode 100644 (file)
index 0000000..3395850
--- /dev/null
@@ -0,0 +1,30 @@
+import pytest
+
+from datetime import timedelta
+from typing import Type
+
+from teuthology.util import time
+
+
+@pytest.mark.parametrize(
+    ["offset", "result"],
+    [
+        ["1s", timedelta(seconds=1)],
+        ["1m", timedelta(minutes=1)],
+        ["1h", timedelta(hours=1)],
+        ["1d", timedelta(days=1)],
+        ["1w", timedelta(weeks=1)],
+        ["365d", timedelta(days=365)],
+        ["1x", ValueError],
+        ["-1m", ValueError],
+        ["0xde", ValueError],
+        ["frog", ValueError],
+        ["7dwarfs", ValueError],
+    ]
+)
+def test_parse_offset(offset: str, result: timedelta | Type[Exception]):
+    if isinstance(result, timedelta):
+        assert time.parse_offset(offset) == result
+    else:
+        with pytest.raises(result):
+            time.parse_offset(offset)
diff --git a/teuthology/util/time.py b/teuthology/util/time.py
new file mode 100644 (file)
index 0000000..4fbafe8
--- /dev/null
@@ -0,0 +1,34 @@
+import re
+
+from datetime import timedelta
+
+def parse_offset(offset: str) -> timedelta:
+    """
+    offset: A string consisting of digits followed by one of the following
+            characters:
+                s: seconds
+                m: minutes
+                h: hours
+                d: days
+                w: weeks
+    """
+    err_msg = "Offsets must either be an ISO 8601-formatted timestamp or " \
+        f"a relative value like '2w', '1d', '7h', '45m', '90s'. Got: {offset}"
+    match = re.match(r'(\d+)(s|m|h|d|w)$', offset)
+    if match is None:
+        raise ValueError(err_msg)
+    num = int(match.groups()[0])
+    unit = match.groups()[1]
+    match unit:
+        case 's':
+            return timedelta(seconds=num)
+        case 'm':
+            return timedelta(minutes=num)
+        case 'h':
+            return timedelta(hours=num)
+        case 'd':
+            return timedelta(days=num)
+        case 'w':
+            return timedelta(weeks=num)
+        case _:
+            raise ValueError(err_msg)