试图模拟 datetime.date.today(),但不工作

Trying to mock datetime.date.today(), but not working(试图模拟 datetime.date.today(),但不工作)
本文介绍了试图模拟 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(),但不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)