Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/celpy/celtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1347,7 +1347,10 @@ def __new__(
raise ValueError("range error: {seconds}")
return super().__new__(cls, seconds=seconds, microseconds=nanos // 1000)
elif isinstance(seconds, str):
duration_pat = re.compile(r"^[-+]?([0-9]*(\.[0-9]*)?[a-z]+)+$")
valid_units = sorted(cls.scale.keys(), key=len, reverse=True)
units_pattern = r"(?:" + r"|".join(map(re.escape, valid_units)) + r")"

duration_pat = re.compile(rf"^[-+]?([0-9]*(\.[0-9]*)?{units_pattern})+$")

duration_match = duration_pat.match(seconds)
if not duration_match:
Expand All @@ -1369,7 +1372,7 @@ def __new__(
seconds = sign * fsum(
map(
lambda n_u: float(n_u.group(1)) * cls.scale[n_u.group(3)],
re.finditer(r"([0-9]*(\.[0-9]*)?)([a-z]+)", seconds),
re.finditer(rf"([0-9]*(\.[0-9]*)?)({units_pattern})", seconds),
)
)
except KeyError:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_celtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,17 @@ def test_duration_type():
assert DurationType("-2m30s").getSeconds() == IntType(-150)
with pytest.raises(ValueError):
DurationType("-2w30z")
assert int(DurationType("1.5h").total_seconds()) == 5400
assert DurationType("300ms").getMilliseconds() == IntType(300)
assert DurationType("2ms").total_seconds() == 0.002
with pytest.raises(ValueError):
DurationType("300msec")
with pytest.raises(ValueError):
DurationType("2hours")
with pytest.raises(ValueError):
DurationType("15sec")
with pytest.raises(ValueError):
DurationType("2m30sx")


def test_function_type():
Expand Down