I'm trying to write tests for a class that has methods like:
import datetime
import pytz
class MyClass:
def get_now(self, timezone):
return datetime.datetime.now(timezone)
def do_many_things(self, tz_string='Europe/London'):
tz = pytz.timezone(tz_string)
localtime_now = self.get_now(tz)
...
return things
I want to test it, and to do so I need to make sure that the datetime.datetime.now()
call returns something predictable.
I've been reading lots of examples of using Mock in tests, but haven't found anything quite like what I need, and I can't work out how to use it in my tests.
I separated the get_now()
method out in case it's easier to mock that, instead of datetime.datetime.now()
, but I'm still stumped. Any thoughts on how to write UnitTests for this using Mock? (This is all in Django, fwiw; I'm not sure if this makes a difference in this case.)
localize
instead.datetime.datetime.now(timezone)
I should dotimezone.localize(datetime.datetime.now())
? Any particular reason it's better?localize()
is only used for naivedatetimes
. So ifnow()
is 2012-10-26 15:00:00 (with no timezone) then it simply applies the specified timezone to it; it doesn't convert the time. As I want to get the actual time in a timezone, I think I need to do:datetime.datetime.now(pytz.utc).astimezone(timezone)
.