HI,<br><br>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.<br>
<br>For illustration lets say I have a function:<br><br><br>from datetime import date<br>def today_is_2009():<br>    return date.today().year == 2009<br><br>To test this I would like to write test function like:<br><br>def test_today_is_2009():<br>
    set_today(date(2008, 12, 31))<br>    assert today_is_2009() == False<br>    set_today(date(2009,1,1))<br>    assert today_is_2009() == True<br><br>The first approach of achieving this purpose is to monkey patch the date.today like:<br>
<br>date.today = mytoday<br><br>But this fails with:<br><br>TypeError: can't set attributes of built-in/extension type 'datetime.date'<br clear="all"><br>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.<br>
<br>Is there any suggestion from the community on how best to test such functions?<br><br>-- <br>Hong Yuan<br><br>大管家网上建材超市<br>装修装潢建材一站式购物<br><a href="http://www.homemaster.cn">http://www.homemaster.cn</a><br>