4

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 ?

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

No, you wouldn't attempt to alter the system clock, rather you might change the function to something you can test:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.