Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_utils.py 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. from django.core.files.base import ContentFile
  2. from django.core.exceptions import ValidationError
  3. from django.test import TestCase
  4. from django.test.utils import override_settings
  5. from ..models import Email, STATUS, PRIORITY, EmailTemplate, Attachment
  6. from ..utils import (create_attachments, get_email_template, parse_emails,
  7. parse_priority, send_mail, split_emails)
  8. from ..validators import validate_email_with_name, validate_comma_separated_emails
  9. @override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
  10. class UtilsTest(TestCase):
  11. def test_mail_status(self):
  12. """
  13. Check that send_mail assigns the right status field to Email instances
  14. """
  15. send_mail('subject', 'message', 'from@example.com', ['to@example.com'],
  16. priority=PRIORITY.medium)
  17. email = Email.objects.latest('id')
  18. self.assertEqual(email.status, STATUS.queued)
  19. # Emails sent with "now" priority is sent right away
  20. send_mail('subject', 'message', 'from@example.com', ['to@example.com'],
  21. priority=PRIORITY.now)
  22. email = Email.objects.latest('id')
  23. self.assertEqual(email.status, STATUS.sent)
  24. def test_email_validator(self):
  25. # These should validate
  26. validate_email_with_name('email@example.com')
  27. validate_email_with_name('Alice Bob <email@example.com>')
  28. Email.objects.create(to=['to@example.com'], from_email='Alice <from@example.com>',
  29. subject='Test', message='Message', status=STATUS.sent)
  30. # Should also support international domains
  31. validate_email_with_name('Alice Bob <email@example.co.id>')
  32. # These should raise ValidationError
  33. self.assertRaises(ValidationError, validate_email_with_name, 'invalid')
  34. self.assertRaises(ValidationError, validate_email_with_name, 'Al <ab>')
  35. def test_comma_separated_email_list_validator(self):
  36. # These should validate
  37. validate_comma_separated_emails(['email@example.com'])
  38. validate_comma_separated_emails(
  39. ['email@example.com', 'email2@example.com', 'email3@example.com']
  40. )
  41. validate_comma_separated_emails(['Alice Bob <email@example.com>'])
  42. # Should also support international domains
  43. validate_comma_separated_emails(['email@example.co.id'])
  44. # These should raise ValidationError
  45. self.assertRaises(ValidationError, validate_comma_separated_emails,
  46. ['email@example.com', 'invalid_mail', 'email@example.com'])
  47. def test_get_template_email(self):
  48. # Sanity Check
  49. name = 'customer/happy-holidays'
  50. self.assertRaises(EmailTemplate.DoesNotExist, get_email_template, name)
  51. template = EmailTemplate.objects.create(name=name, content='test')
  52. # First query should hit database
  53. self.assertNumQueries(1, lambda: get_email_template(name))
  54. # Second query should hit cache instead
  55. self.assertNumQueries(0, lambda: get_email_template(name))
  56. # It should return the correct template
  57. self.assertEqual(template, get_email_template(name))
  58. # Repeat with language support
  59. template = EmailTemplate.objects.create(name=name, content='test',
  60. language='en')
  61. # First query should hit database
  62. self.assertNumQueries(1, lambda: get_email_template(name, 'en'))
  63. # Second query should hit cache instead
  64. self.assertNumQueries(0, lambda: get_email_template(name, 'en'))
  65. # It should return the correct template
  66. self.assertEqual(template, get_email_template(name, 'en'))
  67. def test_template_caching_settings(self):
  68. """Check if POST_OFFICE_CACHE and POST_OFFICE_TEMPLATE_CACHE understood
  69. correctly
  70. """
  71. def is_cache_used(suffix='', desired_cache=False):
  72. """Raise exception if real cache usage not equal to desired_cache value
  73. """
  74. # to avoid cache cleaning - just create new template
  75. name = 'can_i/suport_cache_settings%s' % suffix
  76. self.assertRaises(
  77. EmailTemplate.DoesNotExist, get_email_template, name
  78. )
  79. EmailTemplate.objects.create(name=name, content='test')
  80. # First query should hit database anyway
  81. self.assertNumQueries(1, lambda: get_email_template(name))
  82. # Second query should hit cache instead only if we want it
  83. self.assertNumQueries(
  84. 0 if desired_cache else 1,
  85. lambda: get_email_template(name)
  86. )
  87. return
  88. # default - use cache
  89. is_cache_used(suffix='with_default_cache', desired_cache=True)
  90. # disable cache
  91. with self.settings(POST_OFFICE_CACHE=False):
  92. is_cache_used(suffix='cache_disabled_global', desired_cache=False)
  93. with self.settings(POST_OFFICE_TEMPLATE_CACHE=False):
  94. is_cache_used(
  95. suffix='cache_disabled_for_templates', desired_cache=False
  96. )
  97. with self.settings(POST_OFFICE_CACHE=True, POST_OFFICE_TEMPLATE_CACHE=False):
  98. is_cache_used(
  99. suffix='cache_disabled_for_templates_but_enabled_global',
  100. desired_cache=False
  101. )
  102. return
  103. def test_split_emails(self):
  104. """
  105. Check that split emails correctly divide email lists for multiprocessing
  106. """
  107. for i in range(225):
  108. Email.objects.create(from_email='from@example.com', to=['to@example.com'])
  109. expected_size = [57, 56, 56, 56]
  110. email_list = split_emails(Email.objects.all(), 4)
  111. self.assertEqual(expected_size, [len(emails) for emails in email_list])
  112. def test_create_attachments(self):
  113. attachments = create_attachments({
  114. 'attachment_file1.txt': ContentFile('content'),
  115. 'attachment_file2.txt': ContentFile('content'),
  116. })
  117. self.assertEqual(len(attachments), 2)
  118. self.assertIsInstance(attachments[0], Attachment)
  119. self.assertTrue(attachments[0].pk)
  120. self.assertEqual(attachments[0].file.read(), b'content')
  121. self.assertTrue(attachments[0].name.startswith('attachment_file'))
  122. self.assertEquals(attachments[0].mimetype, u'')
  123. def test_create_attachments_with_mimetype(self):
  124. attachments = create_attachments({
  125. 'attachment_file1.txt': {
  126. 'file': ContentFile('content'),
  127. 'mimetype': 'text/plain'
  128. },
  129. 'attachment_file2.jpg': {
  130. 'file': ContentFile('content'),
  131. 'mimetype': 'text/plain'
  132. }
  133. })
  134. self.assertEqual(len(attachments), 2)
  135. self.assertIsInstance(attachments[0], Attachment)
  136. self.assertTrue(attachments[0].pk)
  137. self.assertEquals(attachments[0].file.read(), b'content')
  138. self.assertTrue(attachments[0].name.startswith('attachment_file'))
  139. self.assertEquals(attachments[0].mimetype, 'text/plain')
  140. def test_create_attachments_open_file(self):
  141. attachments = create_attachments({
  142. 'attachment_file.py': __file__,
  143. })
  144. self.assertEqual(len(attachments), 1)
  145. self.assertIsInstance(attachments[0], Attachment)
  146. self.assertTrue(attachments[0].pk)
  147. self.assertTrue(attachments[0].file.read())
  148. self.assertEquals(attachments[0].name, 'attachment_file.py')
  149. self.assertEquals(attachments[0].mimetype, u'')
  150. def test_parse_priority(self):
  151. self.assertEqual(parse_priority('now'), PRIORITY.now)
  152. self.assertEqual(parse_priority('high'), PRIORITY.high)
  153. self.assertEqual(parse_priority('medium'), PRIORITY.medium)
  154. self.assertEqual(parse_priority('low'), PRIORITY.low)
  155. def test_parse_emails(self):
  156. # Converts a single email to list of email
  157. self.assertEqual(
  158. parse_emails('test@example.com'),
  159. ['test@example.com']
  160. )
  161. # None is converted into an empty list
  162. self.assertEqual(parse_emails(None), [])
  163. # Raises ValidationError if email is invalid
  164. self.assertRaises(
  165. ValidationError,
  166. parse_emails, 'invalid_email'
  167. )
  168. self.assertRaises(
  169. ValidationError,
  170. parse_emails, ['invalid_email', 'test@example.com']
  171. )