I have a Django test where I need to mock datetime.now(), because the view that it tests uses datetime.now()
I'm using Michael Foord's mock library, version 1.0.1.
I'm looking for a solution without using other libraries such as freezegun.
Most examples like this and this import datetime and override it, but I'm importing datetime.datetime and im trying to override it, and for some reason this doesn't work.
Overriding datetime works:
import mock
import datetime
class FixedDate(datetime.datetime):
@classmethod
def now(cls):
return cls(2010, 1, 1)
@mock.patch('datetime.datetime', FixedDate)
def myTest():
print(datetime.datetime.now())
myTest()
But I want to import datetime.datetime and do something like this:
import mock
from datetime import datetime
class FixedDate(datetime):
@classmethod
def now(cls):
return cls(2010, 1, 1)
@mock.patch('datetime', FixedDate)
def myTest():
print(datetime.now())
myTest()
This causes the TypeError: Need a valid target to patch. You supplied: 'datetime'.
The Mock library also states:
target should be a string in the form ‘package.module.ClassName’. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling patch from.
Is there any way to path only the datetime and not the datetime.datetime?
Nb. I saw also this example, but it won't work for me, cause I dont have one function that returns the datetime, but my view uses datetime.now()