問題描述
誰能告訴我為什么這不起作用?
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(),但不工作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!