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' 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? -- Hong Yuan 大管家网上建材超市 装修装潢建材一站式购物 http://www.homemaster.cn
-- http://mail.python.org/mailman/listinfo/python-list