[Fixed]-Tools to test out a cron job on a Django project

1👍

First in your settings file, set emails to be output to a file

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location

Then set up unit tests to call your management command and check the email address is in the file. Something like this

from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone


class BirthdayTests(TestCase):
    def setUp(self):
        self.owner_first_name = "Gumdrop"
        self.owner_last_name = "Goodie"
        self.bb_email = "goodie@gumdrop.com"
        my_birthday_boy_user = User(username=self.owner_first_name.lower(),
                                    first_name=self.owner_first_name,
                                    last_name=self.owner_last_name,
                                    email=self.bb_email)

        my_birthday_boy_person = Person(user=my_birthday_boy_user, birthday=timezone.now().date())
        my_birthday_boy_person.save()


    def test_brithday_boy_emailed():
        call_command('your_management_command')

        mail_file = open('/tmp/app-messages', 'r')
        self.assertTrue(self.bb_email in mail_file.read())

then run the tests with

$ ./manage.py test <YOUR APP NAME>

Remember to set the email back in your settings file, or use a special settings file for testing, and use the –settings switch when testing.

Leave a comment