Python:试图模拟datetime.date.today()但不工作 [英] Python: Trying to mock datetime.date.today() but not working

查看:368
本文介绍了Python:试图模拟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 ) $ c> object 仅在装饰功能中。所以,只有你的 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)

这篇关于Python:试图模拟datetime.date.today()但不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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