Trying to mock datetime.date.today(), but not working(试图模拟 datetime.date.today(),但不工作)
问题描述
谁能告诉我为什么这不起作用?
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(),但不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:试图模拟 datetime.date.today(),但不工作
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
