How to write Python time sensitive tests
Suppose I have function
:
def third_day_from_now():
return datetime.date.today() + datetime.timedelta(days=3)
I want to write tests for this function? I know that if today 25th
, the function should return 28
. Is there a way to somehow make the object datetime
return current date
like 25
?
+3
source to share
3 answers
Update function to get the input date as an argument (default to None)
Then test the function by calling with the ie Custom Date argument and no argument.
Demo
>>> def third_day_from_now(input_date=None):
... if input_date:
... return input_date + datetime.timedelta(days=3)
... else:
... return datetime.date.today() + datetime.timedelta(days=3)
...
>>> print "Today + 3:", third_day_from_now()
Today + 3: 2015-07-12
>>> input_date = datetime.datetime.strptime('25-05-2015', "%d-%m-%Y").date()
>>> print "Custom Date:", input_date
Custom Date: 2015-05-25
>>> print "Custom Date + 3:", third_day_from_now(input_date)
Custom Date + 3: 2015-05-28
+1
source to share
No, you won't try to change the system clock, rather, you can change the function to something you can check:
def third_day_from(someday):
"""Returns the day three days after someday
:param someday: a datetime to start counting from
"""
return someday + datetime.timedelta(days=3)
def test_third_day(...)
today = datetime(25, 5, 2005)
thirdday = datetime(28, 5, 2005)
self.assertEqual(third_day_from(today), thirdday)
0
source to share