How to mock the “+” operator in python (specifically datetime.date + datetime.timedelta)
我已经在Django中完成了一些日期模拟问题,并且最后的障碍(我希望)是以下情况。 我有一个FakeDate类,它派生自
FakeDate类按预期工作,但是在向FakeDate添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> 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 - 但是我如何/在哪里可以做到这一点?
将
1 2 3 4 5 6 7 | 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) |
演示:
1 2 3 4 5 6 7 8 9 10 | >>> 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) |
请注意,您可以在此处简单地将实际添加委托给
您只需要在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import datetime class FakeDate(datetime.date): @classmethod def today(cls): return cls(1999, 12, 31) def __add__(self, delta): # Create a datetime.date object so we don't need to do any calculations new_date = super(FakeDate, self).__add__(delta) # Then convert it to FakeDate. return FakeDate(new_date.year, new_date.month, new_date.day) # Returns a FakeDate for 2000-01-01 FakeDate.today() + datetime.timedelta(days=1) |
请注意,这只处理
有关与运算符关联的