有一些问题。
首先,您使用mock.patch 的方式不太正确。当用作装饰器时,它会将给定的函数/类(在本例中为datetime.date.today)替换为Mock 对象仅在装饰函数内。因此,只有在您的 today() 中,datetime.date.today 才会是一个不同的功能,这似乎不是您想要的。
你真正想要的似乎更像是这样的:
@mock.patch('datetime.date.today')
def test():
datetime.date.today.return_value = date(2010, 1, 1)
print datetime.date.today()
很遗憾,这行不通:
>>> 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'
这会失败,因为 Python 内置类型是不可变的 - 请参阅 this answer 了解更多详细信息。
在这种情况下,我将自己继承 datetime.date 并创建正确的函数:
import datetime
class NewDate(datetime.date):
@classmethod
def today(cls):
return cls(2010, 1, 1)
datetime.date = NewDate
现在你可以这样做了:
>>> datetime.date.today()
NewDate(2010, 1, 1)