For a uni project we have to create a program conforming to some tests that we have been given. The tests use magic numbers as inputs for the functions. I know how to get it to return a datetime object. Just dont know how to raise the error!
my code:
import datetime
def time_to_datetime(datetimeSTR):
datetime_obj = datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M')
if datetimeSTR != datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M'):
raise ValueError('The time must have the format YYYY/MM/DD HH:MM')
else:
return datetime_obj
Test Code:
import datetime
import os
import unittest # Standard unittest framework.
import utils # The module implementing JourneyOptions class.
class TestTimeToDatetime(unittest.TestCase):
"""Tests for the time_to_datetime function."""
def test_invalid_time_is_rejected(self):
with self.assertRaises(ValueError) as cm:
utils.time_to_datetime('2019/06/09 12:60')
self.assertEqual(
'The time must have the format YYYY/MM/DD HH:MM',
str(cm.exception))
def test_valid_time_yields_a_dattime_object(self):
d = utils.time_to_datetime('2019/06/09 12:59')
self.assertTrue(isinstance(d, datetime.datetime))
these are the results i get:
======================================================================
ERROR: test_valid_time_yields_a_dattime_object (__main__.TestTimeToDatetime)
Traceback (most recent call last):
File "C:/Users/s5115426/Desktop/tests/test_utils.py", line 21, in test_valid_time_yields_a_dattime_object
d = utils.time_to_datetime('2019/06/09 12:59')
File "C:\Users\s5115426\Desktop\tests\utils.py", line 25, in time_to_datetime
raise ValueError('The time must have the format YYYY/MM/DD HH:MM')
ValueError: The time must have the format YYYY/MM/DD HH:MM
======================================================================
FAIL: test_invalid_time_is_rejected (__main__.TestTimeToDatetime)
Traceback (most recent call last):
File "C:/Users/s5115426/Desktop/tests/test_utils.py", line 18, in test_invalid_time_is_rejected
str(cm.exception))
AssertionError: 'The time must have the format YYYY/MM/DD HH:MM' != 'unconverted data remains: 0'
- The time must have the format YYYY/MM/DD HH:MM
+ unconverted data remains: 0
Any help would be much appreciated!
The error that you are making is that strptime raises a value error if the date string does not match the given format. for example:
date_str = '2019/06/09 12:60'
datetime_obj = datetime.datetime.strptime(date_str, '%Y/%m/%d %H:%M')
.
.
ValueError: unconverted data remains: 0
datetime_obj never gets set because strptime never returns a value.
Also, as noted, you are comparing the response from strptime to the inout string -- that will never work.
Try a simpler approach:
import datetime
def time_to_datetime(datetimeSTR):
datetime_obj = datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M')
return datetime_obj
Or you can catch any exception and reraise (imo, bad practice, but might be worth doing to illustrate.
import datetime
def time_to_datetime(datetimeSTR):
try:
datetime_obj = datetime.datetime.strptime(datetimeSTR, '%Y/%m/%d %H:%M')
except ValueErr as err:
print(err)
raise ValueError('The time must have the format YYYY/MM/DD HH:MM')
else:
return datetime_obj
This way, you see how strptime behaves for various inputs in your test and you have error handling in your function .... though, as I indicated, reraising an error is (imo) bad practice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.