gpt4 book ai didi

python - 模拟 python 内置日期时间不能作为装饰器工作

转载 作者:行者123 更新时间:2023-11-28 20:42:49 25 4
gpt4 key购买 nike

为什么会失败:

@patch.object(datetime, 'datetime', Mock(wraps=datetime.datetime))
def test(self, dt_mock):
dt_mock.utcnow.return_value = datetime.datetime(2014, 1, 1)
self.assertEqual(datetime.datetime(2014, 1, 1), datetime.datetime.utcnow())

Error
Traceback (most recent call last):
File "/Users/user/.virtualenvs/project/lib/python2.7/site-packages/mock.py", line 1201, in patched
return func(*args, **keywargs)
TypeError: test() takes exactly 2 arguments (1 given)

当它正常工作时:

def test(self):
with patch.object(datetime, 'datetime', Mock(wraps=datetime.datetime)) as dt_mock:
dt_mock.utcnow.return_value = datetime.datetime(2014, 1, 1)
self.assertEqual(datetime.datetime(2014, 1, 1), datetime.datetime.utcnow())

mock.py 中的_patch_object 只调用 _patch 类构造函数,我不知道模拟参数是如何不提供给装饰测试方法的。

最佳答案

问题是 patch.object 的 3 参数形式不会发出正在修补的对象作为正在装饰的函数的参数,我以前从未使用过那个版本;- )

来自relevant documentation :

You can either call patch.object with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with.

When calling with the two argument form you omit the replacement object, and a mock is created for you and passed in as an extra argument to the decorated function...

固定测试:

@patch.object(datetime, 'datetime', Mock(wraps=datetime.datetime))
def test(self):
datetime.datetime.utcnow.return_value = datetime.datetime(2014, 1, 1)
self.assertEqual(datetime.datetime(2014, 1, 1), datetime.datetime.utcnow())

感谢@univerio 告诉我错误的方法...

关于python - 模拟 python 内置日期时间不能作为装饰器工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25456865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com