How best to test functions which use date.today
Lie Ryan
lie.1296 at gmail.com
Sat Feb 28 12:54:05 EST 2009
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
>
> The first approach of achieving this purpose is to monkey patch the
> date.today like:
>
> date.today = mytoday
>
> But this fails with:
>
> TypeError: can't set attributes of built-in/extension type 'datetime.date'
This is because today is an attribute. In python, we can override
attribute access to become a function call. I don't have python right
now, but try this:
del date.today
date.today = mytoday
> A second possibility would be to change the system date (I am running
> Linux). However the standard Python module doesn't provide a method for this
> purpose. I could use os.system to issue a date command. But I am not very
> comfortable with this since changing the system time could break something
> undesirably. Also I will then have to have root privilege to run my test.
> Besides, I will have to stop the ntp daemon so it will not inadvertently
> correct the system clock during the test period.
>
> Is there any suggestion from the community on how best to test such
> functions?
It is a very bad idea to change the system date.
More information about the Python-list
mailing list