auto_now model field arguments provide an easy way
to create dates when an entity is created and/or last updated.
To give you more precise overview let’s assume that I have a Post
And this is my
Above I used
TimeStampedModel as an
Abstract Model and I always recommend to
move your common fields into
Abstract Model aligned with clean architecture
and DRY method.
In a more common way you could write the model like below;
auto_now_add make writing unit tests which
depend on creation or modification times difficult, since there is no simple way
to set these fields to a specific time for testing.
For an example, assume you have a business rule; you’re giving 7 days to authors to be able publish a blog post after creation. Maybe you want them to re-read their posts to eliminate typo or logic errors — yes, it makes no sense, I’m just making some company policy.
As you can see we’re making
True if a post created 7 days
before or more.
In order to test this behavior, let’s write some unittest;
FactoryBoy library to create an
User instance, however you can use
default methods like
Above test will fail since the
created_at field of the created
instance will always be equal to the time you run the tests. So there is no way to
True in a test.
Solution comes from Python’s
unittest.mock library: Mock;
We are patching the method with
mock.patch decorator to return a specific time
when the factory creates the object for testing. So with
mock in this method
current now will be 60 days before actual now.
When you run the test you’ll see the test will pass.
Instead of decorator you can also use
context manager —I don’t usually use
this method since it creates hard-to-read, nested methods when you
mock/patch multiple stuff:
When you run the test you will see same successful result.
If you are enjoying my content, maybe you would enjoy buying me a coffee as well.
Just a food for thought.