Skip to content

Commit b8c0b74

Browse files
Merge pull request #17 from nickmaccarthy/issue_15
catch invalid timeunit and throw error
2 parents adef51a + bb46d92 commit b8c0b74

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

datemath/helpers.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -195,18 +195,23 @@ def evaluate(expression, now, timeZone='UTC', roundDown=True):
195195

196196
try:
197197
m = re.match('(\d*[.]?\d+)[\w+-/]', expression[i+1:])
198-
num = m.group(1)
199-
val = val * 10 + float(num)
200-
i = i + len(num)
198+
if m:
199+
num = m.group(1)
200+
val = val * 10 + float(num)
201+
i = i + len(num)
202+
else:
203+
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.''')
201204
except Exception as e:
202-
raise DateMathException("Invalid numerical datematch: What I got was - match: {0}, expression: {1}, error: {2}".format(expression[i+1:], expression, e))
205+
raise DateMathException("Invalid datematch: What I got was - re.match: {0}, expression: {1}, error: {2}".format(expression[i+1:], expression, e))
203206

204207
if char == '+':
205208
val = float(val)
206209
else:
207210
val = float(-val)
208211
elif re.match('[a-zA-Z]+', char):
209212
now = calculate(now, val, unitMap(char))
213+
else:
214+
raise DateMathException(''''{}' is not a valid timeunit for expression: '{}' '''.format(char, expression))
210215

211216
i += 1
212217
if debug: print("Fin: {0}".format(now))

tests.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1+
# !/usr/bin/python
2+
# coding=utf-8
3+
4+
15
import unittest2 as unittest
26
import arrow
37
from datetime import datetime as pydatetime
4-
from datemath import dm
5-
from datemath import datemath
8+
from datemath import dm, datemath
9+
from datemath.helpers import DateMathException as DateMathException
610
from dateutil import tz
711

812
iso8601 = 'YYYY-MM-DDTHH:mm:ssZZ'
@@ -124,6 +128,20 @@ def testParse(self):
124128
self.assertEqual(dm('now-2.5d').format(iso8601), arrow.utcnow().shift(days=-2.5).format(iso8601))
125129

126130

131+
# Catch invalid timeunits
132+
self.assertRaises(DateMathException, dm, '+1,')
133+
self.assertRaises(DateMathException, dm, '+1.')
134+
self.assertRaises(DateMathException, dm, '+1ö')
135+
self.assertRaises(DateMathException, dm, '+1ä')
136+
self.assertRaises(DateMathException, dm, '+1ü')
137+
self.assertRaises(DateMathException, dm, '+1ß')
138+
139+
try:
140+
dm('+1,')
141+
except DateMathException as e:
142+
self.assertTrue('is not a valid timeunit' in str(e))
143+
144+
127145
if __name__ == "__main__":
128146
unittest.main()
129147

0 commit comments

Comments
 (0)