How best to test functions which use date.today

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Feb 28 15:38:01 EST 2009


En Sat, 28 Feb 2009 15:35:47 -0200, Yuan HOng <hongyuan1306 at gmail.com>  
escribió:

> In my project I have several date related methods which I want tested for
> correctness. The functions use date.today() in several places. Since this
> could change every time I run the test, I hope to find someway to fake a
> date.today.
>
> For illustration lets say I have a function:
>
>
> from datetime import date
> def today_is_2009():
>     return date.today().year == 2009
>
> To test this I would like to write test function like:
>
> def test_today_is_2009():
>     set_today(date(2008, 12, 31))
>     assert today_is_2009() == False
>     set_today(date(2009,1,1))
>     assert today_is_2009() == True
>

Instead of trying to inject a fake date, you could rewrite the function to
take a date argument:

def today_is_2009(today=None):
    if today is None:
      today = date.today()
    return today.year == 2009

Then, tests should pass a known date. This approach has a drawback -- you
don't test the case when no argument is given.

Another way is to use a fake date class, or a fake datetime module. Google  
"python mock object"

-- 
Gabriel Genellina




More information about the Python-list mailing list