如何模拟"+" python中的运算符(特别是datetime.date + datetime.timedelta) [英] How to mock the "+" operator in python (specifically datetime.date + datetime.timedelta)
问题描述
我在Django中解决了一些日期模拟问题,并且遇到了以下最后一个障碍(我希望).我有一个FakeDate类,它从datetime.date
派生而来,它是模拟出来的.
I have working through some date mocking issues in Django, and have the final hurdle (I hope) is the following situation. I have a FakeDate class, which derives from datetime.date
, which it mocks out.
FakeDate类按预期工作,但是在向FakeDate添加datetime.timedelta
时遇到问题,因为它返回的是真正的datetime.date
,而不是模拟对象.这很重要,因为第三方库中的其他地方都有isinstance(value, datetime.date)
检查,使用timedelta时该检查总是会失败.
The FakeDate class works as expected, however I get a problem when adding a datetime.timedelta
to the FakeDate, in that it returns a genuine datetime.date
, rather than the mock. This is important as elsewhere in a third party library there is an isinstance(value, datetime.date)
check, which will always fail when using timedelta.
>>> import mock
>>> import datetime
>>>
>>> class FakeDate(datetime.date):
... @classmethod
... def today(cls):
... return cls(1999, 12, 31)
...
>>> FakeDate.today()
FakeDate(1999, 12, 31)
>>> FakeDate(2000, 1, 1)
FakeDate(2000, 1, 1)
>>> FakeDate(1999, 12, 31) + datetime.timedelta(days=1)
datetime.date(2000, 1, 1)
我希望FakeDate + timedelta附加项返回FakeDate对象而不是datetime.date对象-我想这涉及以某种方式修补timedelta-但是如何/在哪里可以做到这一点?
I want the FakeDate + timedelta addition to return a FakeDate object rather than a datetime.date object - which I imagine involves patching the timedelta somehow - but how / where can I do this?
推荐答案
在FakeDate()
类中添加__add__
方法:
class FakeDate(datetime.date):
@classmethod
def today(cls):
return cls(1999, 12, 31)
def __add__(self, other):
res = super(FakeDate, self).__add__(other)
return type(self)(res.year, res.month, res.day)
演示:
>>> class FakeDate(datetime.date):
... @classmethod
... def today(cls):
... return cls(1999, 12, 31)
... def __add__(self, other):
... res = super(FakeDate, self).__add__(other)
... return type(self)(res.year, res.month, res.day)
...
>>> FakeDate.today() + datetime.timedelta(days=1)
FakeDate(2000, 1, 1)
请注意,您可以在此处将实际添加的内容简单地委派给datetime.date
类.我们要做的就是将结果转换回FakeDate()
实例.
Note that you can simply delegate the actual adding to the datetime.date
class here; all we need to do is convert the result back to a FakeDate()
instance.
这篇关于如何模拟"+" python中的运算符(特别是datetime.date + datetime.timedelta)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!