/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-02-28 21:45:13 UTC
  • Revision ID: teddy@recompile.se-20190228214513-58glsld2x80fq684
mandos-ctl: Refactor and add more tests

* mandos-ctl (string_to_delta): Factor out old-style parsing to its
                                own function.  Log a warning if
                                old-style parsing is invoked.
  (parse_pre_1_6_1_interval): New; factored out of string_to_delta.
                              Also added more tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
239
239
 
240
240
def string_to_delta(interval):
241
241
    """Parse a string and return a datetime.timedelta
242
 
 
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)
255
242
    """
256
243
 
257
244
    try:
258
245
        return rfc3339_duration_to_delta(interval)
259
 
    except ValueError:
260
 
        pass
 
246
    except ValueError as e:
 
247
        log.warning("%s - Parsing as pre-1.6.1 interval instead",
 
248
                    ' '.join(e.args))
 
249
    return parse_pre_1_6_1_interval(interval)
 
250
 
 
251
 
 
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)
 
272
 
 
273
    """
261
274
 
262
275
    value = datetime.timedelta(0)
263
276
    regexp = re.compile(r"(\d+)([dsmhw]?)")