I'd like to mock timing so that be able to set certain time to a field of type DateTimeField with auto_now_add=True during my tests e.g:
class MyModel:
...
created_at = models.DateTimeField(auto_now_add=True)
...
class TestMyModel(TestCase):
...
def test_something(self):
# mock current time so that `created_at` be something like 1800-02-09T020000
my_obj = MyModel.objects.create(<whatever>)
# and here my_obj.created_at == 1800-02-09T000000
I'm aware the current date is always used for this type of fields, that is why i'm looking for an alternative to mock somehow the system timing, but just in a context.
I've tried some approaches, for instance, creating a context with freeze_time but didn't work:
with freeze_now("1800-02-09"):
MyModel.objects.create(<whatever>)
# here the created_at doesn't fit 1800-02-09
Ofc I guess, this due to the machinery behind how it is created the object with auto_now_add=True
Is there a way we can mock the timing so that we can do that this kind of field get the time i want in certain context?
Aucun commentaire:
Enregistrer un commentaire