How best to test functions which use date.today
hongyuan1306 at gmail.com
Sat Feb 28 18:35:47 CET 2009
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
For illustration lets say I have a function:
from datetime import date
return date.today().year == 2009
To test this I would like to write test function like:
set_today(date(2008, 12, 31))
assert today_is_2009() == False
assert today_is_2009() == True
The first approach of achieving this purpose is to monkey patch the
date.today = mytoday
But this fails with:
TypeError: can't set attributes of built-in/extension type 'datetime.date'
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
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list