```python # duration_parser.py """Parse compact duration strings like '1w2d3h4m5s' into total seconds.""" from __future__ import annotations import re from typing import Dict UNIT_SECONDS: Dict[str, int] = { "w": 7 * 24 * 60 * 60, # weeks "d": 24 * 60 * 60, # days "h": 60 * 60, # hours "m": 60, # minutes "s": 1, # seconds } _TOKEN_RE = re.compile(r"(\d+)([wdhms])") _UNIT_RE = re.compile(r"[wdhms]") def parse_duration(s: str) -> int: """Convert a duration string to an integer number of seconds. Accepted units (case-insensitive): w, d, h, m, s. Components may appear in any order and may repeat (e.g. '90m' == '1h30m'). Raises: ValueError: if the input is empty, malformed, or contains unknown characters/units. """ if not isinstance(s, str): raise ValueError(f"duration must be a string, got {type(s).__name__}") candidate = s.strip().lower() if not candidate: raise ValueError("duration string is empty") # Reject anything that isn't digits or a known unit up front. if any(ch not in "0123456789wdhms" for ch in candidate): raise ValueError(f"invalid characters in duration: {s!r}") # Every character must be consumed by a well-formed number+unit token. total = 0 consumed = 0 for match in _TOKEN_RE.finditer(candidate): start, end = match.span() if start != consumed: raise ValueError(f"malformed duration: {s!r}") consumed = end total += int(match.group(1)) * UNIT_SECONDS[match.group(2)] if consumed != len(candidate): raise ValueError(f"malformed duration: {s!r}") return total ``` ```python # test_duration_parser.py import pytest from duration_parser import parse_duration @pytest.mark.parametrize( "text, expected", [ ("1h30m", 5400), ("2d", 172800), ("45s", 45), ("1w2d3h4m5s", 615845), ("1w", 604800), ("1h", 3600), ("1m", 60), ("90m", 5400), # equivalent to 1h30m ("60s", 60), # equivalent to 1m ("1s1s", 2), # repeated units sum ("3h3h", 21600), ("5s4m3h2d1w", 615845), # order-independent ("0s", 0), ("0d0h0m0s", 0), (" 2h ", 7200), # surrounding whitespace ignored ("2H30M", 9000), # case-insensitive ], ) def test_valid_durations(text, expected): assert parse_duration(text) == expected @pytest.mark.parametrize( "bad", [ "", # empty " ", # whitespace only "abc", # no digits/units "1x", # unknown unit "1h30", # missing unit "h30m", # missing number "1.5h", # float not supported "-1h", # negative not supported "1h 30m", # internal space "1h30m5", # trailing bare number "1hh", # doubled unit char ], ) def test_invalid_durations(bad): with pytest.raises(ValueError): parse_duration(bad) def test_rejects_non_string(): with pytest.raises(ValueError): parse_duration(3600) ```