How best to test functions which use

Yuan HOng hongyuan1306 at
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 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
def today_is_2009():
    return == 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
    assert today_is_2009() == True

The first approach of achieving this purpose is to monkey patch the like: = mytoday

But this fails with:

TypeError: can't set attributes of built-in/extension type ''

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

Hong Yuan

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list