0

In employing that answer, I've created a cron job on a Django project. In fact, I've implemented a code that will allow to send an automatic email to each client for their birthday. My problem is located when I want to test out the code.

Could anyone be able to tell me what I have to do to test this code? What sort of tools are there to do that kind of testing?

Does Freezegun is a good solution? If so, how could I use it?

Community
  • 1
  • 1

1 Answers1

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.

MagicLAMP
  • 1,032
  • 11
  • 26
  • I think there's no need to use the `return` keyword in each method. – slackmart Jan 27 '17 at 09:28
  • Also there's an `override_settings` decorator that can be applied to override the suggested settings. https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.override_settings – slackmart Jan 27 '17 at 09:31
  • 1
    You don't need return at the end of a function that does not return anything, but its use is conventional in my case, and allows me to easily identify the end of a function. Python people are very fussy about not using anything (but indentation) to indicate where code blocks terminate, but it helps me. I will check out the override_settings. That would be handy – MagicLAMP Jan 27 '17 at 22:03