Suppose I have a 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 is 25th then the function should return 28.
Is there a way somehow I can force the datetime object to return current date as 25 ?
freezegun makes mocking datetime very easy.
from freezegun import freeze_time
@freeze_time("2015-02-25")
def test_third_day_from_now():
assert third_day_from_now() == datetime.datetime(2015, 2, 28)
Update function to get input date as argument(default value in None)
Then test function by calling with argument i.e. Custom Date and without 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With