问题描述
谁能告诉我为什么这不起作用?
Can anyone tell me why this isn't working?
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
也许有人可以提出更好的方法?
Perhaps someone could suggest a better way?
推荐答案
有几个问题.
首先,您使用 mock.patch
的方式不太正确.当用作装饰器时,它仅在装饰函数内将给定的函数/类(在本例中为 datetime.date.today
)替换为 Mock
对象.所以,只有在你的 today()
中,datetime.date.today
才会是一个不同的函数,这似乎不是你想要的.
First of all, the way you're using mock.patch
isn't quite right. When used as a decorator, it replaces the given function/class (in this case, datetime.date.today
) with a Mock
object only within the decorated function. So, only within your today()
will datetime.date.today
be a different function, which doesn't appear to be what you want.
你真正想要的似乎更像是这样的:
What you really want seems to be more like this:
@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 fails because Python built-in types are immutable - see this answer for more details.
在这种情况下,我将自己继承 datetime.date 并创建正确的函数:
In this case, I would subclass datetime.date myself and create the right function:
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)
这篇关于试图模拟 datetime.date.today(),但不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!