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
29 changes: 13 additions & 16 deletions tornado/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,22 +640,19 @@ def _parse_datetime(self, value: str) -> datetime.datetime:
)

def _parse_timedelta(self, value: str) -> datetime.timedelta:
try:
sum = datetime.timedelta()
start = 0
while start < len(value):
m = self._TIMEDELTA_PATTERN.match(value, start)
if not m:
raise Exception()
num = float(m.group(1))
units = m.group(2) or "seconds"
units = self._TIMEDELTA_ABBREV_DICT.get(units, units)

sum += datetime.timedelta(**{units: num})
start = m.end()
return sum
except Exception:
raise
sum = datetime.timedelta()
start = 0
while start < len(value):
m = self._TIMEDELTA_PATTERN.match(value, start)
if not m:
raise Error("Invalid time delta: %r" % value)
num = float(m.group(1))
units = m.group(2) or "seconds"
units = self._TIMEDELTA_ABBREV_DICT.get(units, units)

sum += datetime.timedelta(**{units: num})
start = m.end()
return sum

def _parse_bool(self, value: str) -> bool:
return value.lower() not in ("false", "0", "f")
Expand Down
9 changes: 9 additions & 0 deletions tornado/test/options_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,15 @@ def test_multiple_int(self):
options.parse_command_line(["main.py", "--foo=1,3,5:7"])
self.assertEqual(options.foo, [1, 3, 5, 6, 7])

def test_parse_timedelta_invalid_raises_options_error(self):
# Malformed timedelta input should raise options.Error with a
# human-readable message, not a bare Exception with no context.
options = OptionParser()
options.define("foo", type=datetime.timedelta)
with self.assertRaises(Error) as cm:
options.parse_command_line(["main.py", "--foo=xyz"])
self.assertIn("xyz", str(cm.exception))

def test_error_redefine(self):
options = OptionParser()
options.define("foo")
Expand Down