diff --git a/datemath/helpers.py b/datemath/helpers.py index d16192b..de1616d 100644 --- a/datemath/helpers.py +++ b/datemath/helpers.py @@ -195,11 +195,14 @@ def evaluate(expression, now, timeZone='UTC', roundDown=True): try: m = re.match('(\d*[.]?\d+)[\w+-/]', expression[i+1:]) - num = m.group(1) - val = val * 10 + float(num) - i = i + len(num) + if m: + num = m.group(1) + val = val * 10 + float(num) + i = i + len(num) + else: + raise DateMathException('''Unable to determine a proper time qualifier. Do you have a proper numerical number followed by a valid time unit? i.e. '+1d', '-3d/d', etc.''') except Exception as e: - raise DateMathException("Invalid numerical datematch: What I got was - match: {0}, expression: {1}, error: {2}".format(expression[i+1:], expression, e)) + raise DateMathException("Invalid datematch: What I got was - re.match: {0}, expression: {1}, error: {2}".format(expression[i+1:], expression, e)) if char == '+': val = float(val) @@ -207,6 +210,8 @@ def evaluate(expression, now, timeZone='UTC', roundDown=True): val = float(-val) elif re.match('[a-zA-Z]+', char): now = calculate(now, val, unitMap(char)) + else: + raise DateMathException(''''{}' is not a valid timeunit for expression: '{}' '''.format(char, expression)) i += 1 if debug: print("Fin: {0}".format(now)) diff --git a/tests.py b/tests.py index 9dfd1c3..48f77ce 100644 --- a/tests.py +++ b/tests.py @@ -1,8 +1,12 @@ +# !/usr/bin/python +# coding=utf-8 + + import unittest2 as unittest import arrow from datetime import datetime as pydatetime -from datemath import dm -from datemath import datemath +from datemath import dm, datemath +from datemath.helpers import DateMathException as DateMathException from dateutil import tz iso8601 = 'YYYY-MM-DDTHH:mm:ssZZ' @@ -124,6 +128,20 @@ def testParse(self): self.assertEqual(dm('now-2.5d').format(iso8601), arrow.utcnow().shift(days=-2.5).format(iso8601)) + # Catch invalid timeunits + self.assertRaises(DateMathException, dm, '+1,') + self.assertRaises(DateMathException, dm, '+1.') + self.assertRaises(DateMathException, dm, '+1ö') + self.assertRaises(DateMathException, dm, '+1ä') + self.assertRaises(DateMathException, dm, '+1ü') + self.assertRaises(DateMathException, dm, '+1ß') + + try: + dm('+1,') + except DateMathException as e: + self.assertTrue('is not a valid timeunit' in str(e)) + + if __name__ == "__main__": unittest.main()