Mock timing in a context to create models with a field DateTimeField with auto_now_add=True
Okay, I have found a solution, it is based on mock:
def mock_now():
return <mock time>
class TestMyModel(TestCase):
...
@mock.patch('django.utils.timezone.now', mock_now)
def test_as_decorator(self):
...
my_obj = MyModel.objects.create(<whatever>)
...
# here the created_at field has the mocked time :)
def test_as_context_manager(self):
mocked_dt = datetime.datetime(2015, 9, 3, 11, 15, 0)
with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked_dt)):
my_obj = MyModel.objects.create(<whatever>)
# here the created_at field has the mocking time :)