Another way to tackle this issue is to have the updated_at constant and change the two_days_ago.

I usually achieve this by making the current date a parameter, for example rewrite the notify function like this:

def check_pending_invoices(asof):
invoices = Invoice.objects.filter(
paid=False,
updated_at__lt=asof - datetime.timedelta(days=2),
)

Or better yet, remove the number of days from the function all together:

def check_pending_invoices(since):
invoices = Invoice.objects.filter(
paid=False,
updated_at__lt=since,
)

Now the test can create a notification and test by changing the asof date:

def test_should_notify(self):
self.assertTrue(check_pending_invoices(two_days_ago))
def test_should_not_notify(self):
self.assertTrue(check_pending_invoices(three_days_ago))

I usually try to avoid importing timezone at low level modules and pass the “current time” from higher level modules such as API’s and management commands. Makes testing a lot easier.

Written by

Full Stack Developer, Team Leader, Independent. More from me at https://hakibenita.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store