How best to test functions which use date.today

Ed Singleton singletoned at gmail.com
Tue Mar 3 11:41:36 EST 2009


On Feb 28, 5:54 pm, Lie Ryan <lie.1... at gmail.com> wrote:
> Yuan HOng wrote:
> > HI,
>
> > 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

Although you can't override today, you should be able to do something
along the lines of:

class MyDate(object):
    def __init__(self, today):
        self.today = today

my_date = MyDate(date(2009, 11, 12))

date = my_date

This assumes you aren't using anything else from date.  If you are
you'll either have to add that to MyDate or use a proper Mock Object.

Ed




More information about the Python-list mailing list