Reputation: 71
I'm trying to mock the output of datetime.now() to simulate the passage of time. Here is what I'm trying to do:
from datetime import datetime, timedelta
from mock import Mock, patch
from other_module import some_code
tomorrow = Mock(spec=datetime)
tomorrow.now = Mock(return_value=datetime.now() + timedelta(days=1))
with patch('other_module.datetime', tomorrow):
some_code()
This would work fine, except some_code()
is using a library, croniter, that specifically takes the datetime.datetime
class as input and checks that it is a subclass of datetime.datetime
. This is the problem I'm running into; while datetime.datetime is a class, my mock is not; it's not recognized as a class type by the issubclass
method.
How can I make sure that my mock object is recognized as a class?
Upvotes: 2
Views: 474
Reputation: 681
I'm not familiar with croniter, but freezegun may help with this— it patches all references to datetime.datetime
with instances of freezegun.api.FakeDatetime
, so within some_code()
, any datetime.datetimes
should use instances of freezegun.api.FakeDatetime
. Speaking from experience, you'll also save yourself lots of headaches with intermittent test failures when trying to simulate the passage of time if you use freezegun.
from datetime import datetime, timedelta
from freeze_gun import freeze_time
from other_module import some_code
fake_today = datetime.datetime(2017, 7, 11)
with_freeze_time(fake_today):
some_code()
# simulate passage of time to tomorrow
with_freeze_time(fake_today + timedelta(days=1))
some_code()
Upvotes: 3