There are several issues.
First of all, the way to use mock.patch not quite right. When used as a decorator, it replaces the given function / class (in this case, datetime.date.today ) with a Mock object only inside the decorated function. Thus, only in your today() will datetime.date.today be another function that does not seem necessary to you.
What you really want seems more like this:
@mock.patch('datetime.date.today') def test(): datetime.date.today.return_value = date(2010, 1, 1) print datetime.date.today()
Unfortunately this will not work:
>>> test() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.macosx-10.6-universal/egg/mock.py", line 557, in patched File "build/bdist.macosx-10.6-universal/egg/mock.py", line 620, in __enter__ TypeError: can't set attributes of built-in/extension type 'datetime.date'
This fails because the Python built-in types are immutable - see this answer for more details.
In this case, I will subclass datetime.date myself and create the correct function:
import datetime class NewDate(datetime.date): @classmethod def today(cls): return cls(2010, 1, 1) datetime.date = NewDate
And now you can do:
>>> datetime.date.today() NewDate(2010, 1, 1)
Daniel G Dec 19 '10 at 7:49 2010-12-19 07:49
source share