Skip to content

catch invalid timeunit and throw error #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 25, 2020
Merged
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
13 changes: 9 additions & 4 deletions datemath/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,18 +195,23 @@ 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)
else:
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))
Expand Down
22 changes: 20 additions & 2 deletions tests.py
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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()

Expand Down