240
240
def string_to_delta(interval):
241
241
"""Parse a string and return a datetime.timedelta
243
>>> string_to_delta('7d')
244
datetime.timedelta(7)
245
>>> string_to_delta('60s')
246
datetime.timedelta(0, 60)
247
>>> string_to_delta('60m')
248
datetime.timedelta(0, 3600)
249
>>> string_to_delta('24h')
250
datetime.timedelta(1)
251
>>> string_to_delta('1w')
252
datetime.timedelta(7)
253
>>> string_to_delta('5m 30s')
254
datetime.timedelta(0, 330)
245
258
return rfc3339_duration_to_delta(interval)
246
except ValueError as e:
247
log.warning("%s - Parsing as pre-1.6.1 interval instead",
249
return parse_pre_1_6_1_interval(interval)
252
def parse_pre_1_6_1_interval(interval):
253
"""Parse an interval string as documented by Mandos before 1.6.1, and
254
return a datetime.timedelta
255
>>> parse_pre_1_6_1_interval('7d')
256
datetime.timedelta(7)
257
>>> parse_pre_1_6_1_interval('60s')
258
datetime.timedelta(0, 60)
259
>>> parse_pre_1_6_1_interval('60m')
260
datetime.timedelta(0, 3600)
261
>>> parse_pre_1_6_1_interval('24h')
262
datetime.timedelta(1)
263
>>> parse_pre_1_6_1_interval('1w')
264
datetime.timedelta(7)
265
>>> parse_pre_1_6_1_interval('5m 30s')
266
datetime.timedelta(0, 330)
267
>>> parse_pre_1_6_1_interval('')
268
datetime.timedelta(0)
269
>>> # Ignore unknown characters, allow any order and repetitions
270
>>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m')
271
datetime.timedelta(2, 480, 18000)
275
262
value = datetime.timedelta(0)
276
263
regexp = re.compile(r"(\d+)([dsmhw]?)")
557
544
self.assertEqual(milliseconds_to_string(900), "00:00:00")
558
545
self.assertEqual(milliseconds_to_string(1900), "00:00:01")
560
class Test_string_to_delta(unittest.TestCase):
561
def test_handles_basic_rfc3339(self):
562
self.assertEqual(string_to_delta("PT2H"),
563
datetime.timedelta(0, 7200))
564
def test_falls_back_to_pre_1_6_1_with_warning(self):
565
# assertLogs only exists in Python 3.4
566
if hasattr(self, "assertLogs"):
567
with self.assertLogs(log, logging.WARNING):
568
value = string_to_delta("2h")
570
value = string_to_delta("2h")
571
self.assertEqual(value, datetime.timedelta(0, 7200))
574
548
def should_only_run_tests():
575
549
parser = argparse.ArgumentParser(add_help=False)