尝试模拟datetime.date.today(),但无法正常工作 [英] Trying to mock datetime.date.today(), but not working

查看:172
本文介绍了尝试模拟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的方式不太正确.当用作装饰器时,它仅在装饰的函数中用Mock对象替换给定的函数/类(在本例中为datetime.date.today).因此,仅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()

不幸的是,这不起作用:

Unfortunately, this won't 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'

此操作失败,因为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(),但无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆