试图模拟 datetime.date.today(),但不起作用 [英] Trying to mock datetime.date.today(), but not working

查看:28
本文介绍了试图模拟 datetime.date.today(),但不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么这不起作用?

<预><代码>>>>进口模拟>>>@mock.patch('datetime.date.today')... 今天定义(cls):...返回日期(2010, 1, 1)...>>>从日期时间导入日期>>>日期.今天()datetime.date(2010, 12, 19)

也许有人可以提出更好的方法?

解决方案

有几个问题.

首先,您使用 mock.patch 的方式不太正确.当用作装饰器时,它仅在被装饰的函数内用 Mock 对象替换给定的函数/类(在本例中为 datetime.date.today).因此,只有在您的 today() 中,datetime.date.today 才会成为不同的函数,这似乎不是您想要的.

你真正想要的似乎更像这样:

@mock.patch('datetime.date.today')定义测试():datetime.date.today.return_value = date(2010, 1, 1)打印 datetime.date.today()

不幸的是,这行不通:

<预><代码>>>>测试()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件build/bdist.macosx-10.6-universal/egg/mock.py",第 557 行,已打补丁文件build/bdist.macosx-10.6-universal/egg/mock.py",第 620 行,在 __enter__类型错误:无法设置内置/扩展类型datetime.date"的属性

这会失败,因为 Python 内置类型是不可变的 - 请参阅 这个答案 了解更多详情.

在这种情况下,我会自己继承 datetime.date 并创建正确的函数:

导入日期时间类 NewDate(datetime.date):@类方法今天定义(cls):返回 cls(2010, 1, 1)日期时间.日期 = 新日期

现在你可以这样做:

<预><代码>>>>日期时间.日期.今天()新日期(2010, 1, 1)

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?

解决方案

There are a few problems.

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'

This fails because Python built-in types are immutable - see this answer for more details.

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

And now you could do:

>>> datetime.date.today()
NewDate(2010, 1, 1)

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

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