| 1 |
import json |
| 2 |
import os.path |
| 3 |
from email.mime.image import MIMEImage |
| 4 |
|
| 5 |
from django.core import mail |
| 6 |
from django.core.mail.backends.base import BaseEmailBackend |
| 7 |
from django.core.mail.backends import locmem |
| 8 |
from django.core.mail import EmailMultiAlternatives |
| 9 |
from django.test import TestCase |
| 10 |
from django.test.utils import override_settings |
| 11 |
|
| 12 |
import celery |
| 13 |
from djcelery_email import tasks |
| 14 |
from djcelery_email.utils import email_to_dict, dict_to_email |
| 15 |
|
| 16 |
|
| 17 |
def even(n): |
| 18 |
return n % 2 == 0 |
| 19 |
|
| 20 |
|
| 21 |
def celery_queue_pop(): |
| 22 |
""" Pops a single task from Celery's 'memory://' queue. """ |
| 23 |
with celery.current_app.connection() as conn: |
| 24 |
queue = conn.SimpleQueue('django_email', no_ack=True) |
| 25 |
return queue.get().payload |
| 26 |
|
| 27 |
|
| 28 |
class TracingBackend(BaseEmailBackend): |
| 29 |
def __init__(self, **kwargs): |
| 30 |
self.__class__.kwargs = kwargs |
| 31 |
|
| 32 |
def send_messages(self, messages): |
| 33 |
self.__class__.called = True |
| 34 |
|
| 35 |
|
| 36 |
class UtilTests(TestCase): |
| 37 |
@override_settings(CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES=['extra_attribute']) |
| 38 |
def test_email_to_dict_extra_attrs(self): |
| 39 |
msg = mail.EmailMessage() |
| 40 |
msg.extra_attribute = {'name': 'val'} |
| 41 |
|
| 42 |
self.assertEqual(email_to_dict(msg)['extra_attribute'], msg.extra_attribute) |
| 43 |
|
| 44 |
@override_settings(CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES=['extra_attribute']) |
| 45 |
def test_dict_to_email_extra_attrs(self): |
| 46 |
msg_dict = email_to_dict(mail.EmailMessage()) |
| 47 |
msg_dict['extra_attribute'] = {'name': 'val'} |
| 48 |
|
| 49 |
self.assertEqual(email_to_dict(dict_to_email(msg_dict)), msg_dict) |
| 50 |
|
| 51 |
def check_json_of_msg(self, msg): |
| 52 |
serialized = json.dumps(email_to_dict(msg)) |
| 53 |
self.assertEqual( |
| 54 |
email_to_dict(dict_to_email(json.loads(serialized))), |
| 55 |
email_to_dict(msg)) |
| 56 |
|
| 57 |
def test_email_with_attachment(self): |
| 58 |
file_path = os.path.join(os.path.dirname(__file__), 'image.png') |
| 59 |
with open(file_path, 'rb') as file: |
| 60 |
file_contents = file.read() |
| 61 |
msg = mail.EmailMessage( |
| 62 |
'test', 'Testing with Celery! w00t!!', '[email protected]', |
| 63 |
['[email protected]']) |
| 64 |
msg.attach('image.png', file_contents) |
| 65 |
self.check_json_of_msg(msg) |
| 66 |
|
| 67 |
def test_email_with_mime_attachment(self): |
| 68 |
file_path = os.path.join(os.path.dirname(__file__), 'image.png') |
| 69 |
with open(file_path, 'rb') as file: |
| 70 |
file_contents = file.read() |
| 71 |
mimg = MIMEImage(file_contents) |
| 72 |
msg = mail.EmailMessage( |
| 73 |
'test', 'Testing with Celery! w00t!!', '[email protected]', |
| 74 |
['[email protected]']) |
| 75 |
msg.attach(mimg) |
| 76 |
self.check_json_of_msg(msg) |
| 77 |
|
| 78 |
def test_email_with_attachment_from_file(self): |
| 79 |
file_path = os.path.join(os.path.dirname(__file__), 'image.png') |
| 80 |
msg = mail.EmailMessage( |
| 81 |
'test', 'Testing with Celery! w00t!!', '[email protected]', |
| 82 |
['[email protected]']) |
| 83 |
msg.attach_file(file_path) |
| 84 |
self.check_json_of_msg(msg) |
| 85 |
|
| 86 |
|
| 87 |
class TaskTests(TestCase): |
| 88 |
""" |
| 89 |
Tests that the 'tasks.send_email(s)' task works correctly: |
| 90 |
- should accept a single or multiple messages (as dicts) |
| 91 |
- should send all these messages |
| 92 |
- should use the backend set in CELERY_EMAIL_BACKEND |
| 93 |
- should pass the given kwargs to that backend |
| 94 |
- should retry sending failed messages (see TaskErrorTests) |
| 95 |
""" |
| 96 |
def test_send_single_email_object(self): |
| 97 |
""" It should accept and send a single EmailMessage object. """ |
| 98 |
msg = mail.EmailMessage() |
| 99 |
tasks.send_email(msg, backend_kwargs={}) |
| 100 |
self.assertEqual(len(mail.outbox), 1) |
| 101 |
# we can't compare them directly as it's converted into a dict |
| 102 |
# for JSONification and then back. Compare dicts instead. |
| 103 |
self.assertEqual(email_to_dict(msg), email_to_dict(mail.outbox[0])) |
| 104 |
|
| 105 |
def test_send_single_email_object_no_backend_kwargs(self): |
| 106 |
""" It should send email with backend_kwargs not provided. """ |
| 107 |
msg = mail.EmailMessage() |
| 108 |
tasks.send_email(msg) |
| 109 |
self.assertEqual(len(mail.outbox), 1) |
| 110 |
# we can't compare them directly as it's converted into a dict |
| 111 |
# for JSONification and then back. Compare dicts instead. |
| 112 |
self.assertEqual(email_to_dict(msg), email_to_dict(mail.outbox[0])) |
| 113 |
|
| 114 |
def test_send_single_email_object_response(self): |
| 115 |
""" It should return the number of messages sent, 1 here. """ |
| 116 |
msg = mail.EmailMessage() |
| 117 |
messages_sent = tasks.send_email(msg) |
| 118 |
self.assertEqual(messages_sent, 1) |
| 119 |
self.assertEqual(len(mail.outbox), 1) |
| 120 |
|
| 121 |
def test_send_single_email_dict(self): |
| 122 |
""" It should accept and send a single EmailMessage dict. """ |
| 123 |
msg = mail.EmailMessage() |
| 124 |
tasks.send_email(email_to_dict(msg), backend_kwargs={}) |
| 125 |
self.assertEqual(len(mail.outbox), 1) |
| 126 |
# we can't compare them directly as it's converted into a dict |
| 127 |
# for JSONification and then back. Compare dicts instead. |
| 128 |
self.assertEqual(email_to_dict(msg), email_to_dict(mail.outbox[0])) |
| 129 |
|
| 130 |
def test_send_multiple_email_objects(self): |
| 131 |
""" It should accept and send a list of EmailMessage objects. """ |
| 132 |
N = 10 |
| 133 |
msgs = [mail.EmailMessage() for i in range(N)] |
| 134 |
tasks.send_emails([email_to_dict(msg) for msg in msgs], |
| 135 |
backend_kwargs={}) |
| 136 |
|
| 137 |
self.assertEqual(len(mail.outbox), N) |
| 138 |
for i in range(N): |
| 139 |
self.assertEqual(email_to_dict(msgs[i]), email_to_dict(mail.outbox[i])) |
| 140 |
|
| 141 |
def test_send_multiple_email_dicts(self): |
| 142 |
""" It should accept and send a list of EmailMessage dicts. """ |
| 143 |
N = 10 |
| 144 |
msgs = [mail.EmailMessage() for i in range(N)] |
| 145 |
tasks.send_emails(msgs, backend_kwargs={}) |
| 146 |
|
| 147 |
self.assertEqual(len(mail.outbox), N) |
| 148 |
for i in range(N): |
| 149 |
self.assertEqual(email_to_dict(msgs[i]), email_to_dict(mail.outbox[i])) |
| 150 |
|
| 151 |
def test_send_multiple_email_dicts_response(self): |
| 152 |
""" It should return the number of messages sent. """ |
| 153 |
N = 10 |
| 154 |
msgs = [mail.EmailMessage() for i in range(N)] |
| 155 |
messages_sent = tasks.send_emails(msgs, backend_kwargs={}) |
| 156 |
self.assertEqual(messages_sent, N) |
| 157 |
self.assertEqual(len(mail.outbox), N) |
| 158 |
|
| 159 |
@override_settings(CELERY_EMAIL_BACKEND='tests.tests.TracingBackend') |
| 160 |
def test_uses_correct_backend(self): |
| 161 |
""" It should use the backend configured in CELERY_EMAIL_BACKEND. """ |
| 162 |
TracingBackend.called = False |
| 163 |
msg = mail.EmailMessage() |
| 164 |
tasks.send_email(email_to_dict(msg), backend_kwargs={}) |
| 165 |
self.assertTrue(TracingBackend.called) |
| 166 |
|
| 167 |
@override_settings(CELERY_EMAIL_BACKEND='tests.tests.TracingBackend') |
| 168 |
def test_backend_parameters(self): |
| 169 |
""" It should pass kwargs like username and password to the backend. """ |
| 170 |
TracingBackend.kwargs = None |
| 171 |
msg = mail.EmailMessage() |
| 172 |
tasks.send_email(email_to_dict(msg), backend_kwargs={'foo': 'bar'}) |
| 173 |
self.assertEqual(TracingBackend.kwargs.get('foo'), 'bar') |
| 174 |
|
| 175 |
@override_settings(CELERY_EMAIL_BACKEND='tests.tests.TracingBackend') |
| 176 |
def test_backend_parameters_kwargs(self): |
| 177 |
""" It should pass on kwargs specified as keyword params. """ |
| 178 |
TracingBackend.kwargs = None |
| 179 |
msg = mail.EmailMessage() |
| 180 |
tasks.send_email(email_to_dict(msg), foo='bar') |
| 181 |
self.assertEqual(TracingBackend.kwargs.get('foo'), 'bar') |
| 182 |
|
| 183 |
|
| 184 |
class EvenErrorBackend(locmem.EmailBackend): |
| 185 |
""" Fails to deliver every 2nd message. """ |
| 186 |
def __init__(self, *args, **kwargs): |
| 187 |
super(EvenErrorBackend, self).__init__(*args, **kwargs) |
| 188 |
self.message_count = 0 |
| 189 |
|
| 190 |
def send_messages(self, messages): |
| 191 |
self.message_count += 1 |
| 192 |
if even(self.message_count-1): |
| 193 |
raise RuntimeError("Something went wrong sending the message") |
| 194 |
else: |
| 195 |
return super(EvenErrorBackend, self).send_messages(messages) |
| 196 |
|
| 197 |
|
| 198 |
class TaskErrorTests(TestCase): |
| 199 |
""" |
| 200 |
Tests that the 'tasks.send_emails' task does not crash if a single message |
| 201 |
could not be sent and that it requeues that message. |
| 202 |
""" |
| 203 |
# TODO: replace setUp/tearDown with 'unittest.mock' at some point |
| 204 |
def setUp(self): |
| 205 |
super(TaskErrorTests, self).setUp() |
| 206 |
|
| 207 |
self._retry_calls = [] |
| 208 |
|
| 209 |
def mock_retry(*args, **kwargs): |
| 210 |
self._retry_calls.append((args, kwargs)) |
| 211 |
|
| 212 |
self._old_retry = tasks.send_emails.retry |
| 213 |
tasks.send_emails.retry = mock_retry |
| 214 |
|
| 215 |
def tearDown(self): |
| 216 |
super(TaskErrorTests, self).tearDown() |
| 217 |
tasks.send_emails.retry = self._old_retry |
| 218 |
|
| 219 |
@override_settings(CELERY_EMAIL_BACKEND='tests.tests.EvenErrorBackend') |
| 220 |
def test_send_multiple_emails(self): |
| 221 |
N = 10 |
| 222 |
msgs = [mail.EmailMessage(subject="msg %d" % i) for i in range(N)] |
| 223 |
tasks.send_emails([email_to_dict(msg) for msg in msgs], |
| 224 |
backend_kwargs={'foo': 'bar'}) |
| 225 |
|
| 226 |
# Assert that only "odd"/good messages have been sent. |
| 227 |
self.assertEqual(len(mail.outbox), 5) |
| 228 |
self.assertEqual( |
| 229 |
[msg.subject for msg in mail.outbox], |
| 230 |
["msg 1", "msg 3", "msg 5", "msg 7", "msg 9"] |
| 231 |
) |
| 232 |
|
| 233 |
# Assert that "even"/bad messages have been requeued, |
| 234 |
# one retry task per bad message. |
| 235 |
self.assertEqual(len(self._retry_calls), 5) |
| 236 |
odd_msgs = [msg for idx, msg in enumerate(msgs) if even(idx)] |
| 237 |
for msg, (args, kwargs) in zip(odd_msgs, self._retry_calls): |
| 238 |
retry_args = args[0] |
| 239 |
self.assertEqual(retry_args, [[email_to_dict(msg)], {'foo': 'bar'}]) |
| 240 |
self.assertTrue(isinstance(kwargs.get('exc'), RuntimeError)) |
| 241 |
self.assertFalse(kwargs.get('throw', True)) |
| 242 |
|
| 243 |
|
| 244 |
class BackendTests(TestCase): |
| 245 |
""" |
| 246 |
Tests that our *own* email backend ('backends.CeleryEmailBackend') works, |
| 247 |
i.e. it submits the correct number of jobs (according to the chunk size) |
| 248 |
and passes backend parameters to the task. |
| 249 |
""" |
| 250 |
# TODO: replace setUp/tearDown with 'unittest.mock' at some point |
| 251 |
def setUp(self): |
| 252 |
super(BackendTests, self).setUp() |
| 253 |
|
| 254 |
self._delay_calls = [] |
| 255 |
|
| 256 |
def mock_delay(*args, **kwargs): |
| 257 |
self._delay_calls.append((args, kwargs)) |
| 258 |
|
| 259 |
self._old_delay = tasks.send_emails.delay |
| 260 |
tasks.send_emails.delay = mock_delay |
| 261 |
|
| 262 |
def tearDown(self): |
| 263 |
super(BackendTests, self).tearDown() |
| 264 |
tasks.send_emails.delay = self._old_delay |
| 265 |
|
| 266 |
def test_backend_parameters(self): |
| 267 |
""" Our backend should pass kwargs to the 'send_emails' task. """ |
| 268 |
kwargs = {'auth_user': 'user', 'auth_password': 'pass'} |
| 269 |
mail.send_mass_mail([ |
| 270 |
('test1', 'Testing with Celery! w00t!!', '[email protected]', ['[email protected]']), |
| 271 |
('test2', 'Testing with Celery! w00t!!', '[email protected]', ['[email protected]']) |
| 272 |
], **kwargs) |
| 273 |
|
| 274 |
self.assertEqual(len(self._delay_calls), 1) |
| 275 |
args, kwargs = self._delay_calls[0] |
| 276 |
messages, backend_kwargs = args |
| 277 |
self.assertEqual(messages[0]['subject'], 'test1') |
| 278 |
self.assertEqual(messages[1]['subject'], 'test2') |
| 279 |
self.assertEqual(backend_kwargs, {'username': 'user', 'password': 'pass'}) |
| 280 |
|
| 281 |
def test_chunking(self): |
| 282 |
""" |
| 283 |
Given 11 messages and a chunk size of 4, the backend should queue |
| 284 |
11/4 = 3 jobs (2 jobs with 4 messages and 1 job with 3 messages). |
| 285 |
""" |
| 286 |
N = 11 |
| 287 |
chunksize = 4 |
| 288 |
|
| 289 |
with override_settings(CELERY_EMAIL_CHUNK_SIZE=4): |
| 290 |
mail.send_mass_mail([ |
| 291 |
("subject", "body", "[email protected]", ["[email protected]"]) |
| 292 |
for _ in range(N) |
| 293 |
]) |
| 294 |
|
| 295 |
num_chunks = 3 # floor(11.0 / 4.0) |
| 296 |
self.assertEqual(len(self._delay_calls), num_chunks) |
| 297 |
|
| 298 |
full_tasks = self._delay_calls[:-1] |
| 299 |
last_task = self._delay_calls[-1] |
| 300 |
|
| 301 |
for args, kwargs in full_tasks: |
| 302 |
self.assertEqual(len(args[0]), chunksize) |
| 303 |
|
| 304 |
args, kwargs = last_task |
| 305 |
self.assertEqual(len(args[0]), N % chunksize) |
| 306 |
|
| 307 |
|
| 308 |
class ConfigTests(TestCase): |
| 309 |
""" |
| 310 |
Tests that our Celery task has been initialized with the correct options |
| 311 |
(those set in the CELERY_EMAIL_TASK_CONFIG setting) |
| 312 |
""" |
| 313 |
def test_setting_extra_configs(self): |
| 314 |
self.assertEqual(tasks.send_email.queue, 'django_email') |
| 315 |
self.assertEqual(tasks.send_email.delivery_mode, 1) |
| 316 |
self.assertEqual(tasks.send_email.rate_limit, '50/m') |
| 317 |
|
| 318 |
|
| 319 |
class IntegrationTests(TestCase): |
| 320 |
# We run these tests in ALWAYS_EAGER mode, but they might as well be |
| 321 |
# executed using a real backend (maybe we can add that to the test setup in |
| 322 |
# the future?) |
| 323 |
|
| 324 |
def setUp(self): |
| 325 |
super(IntegrationTests, self).setUp() |
| 326 |
# TODO: replace with 'unittest.mock' at some point |
| 327 |
celery.current_app.conf.task_always_eager = True |
| 328 |
|
| 329 |
def tearDown(self): |
| 330 |
super(IntegrationTests, self).tearDown() |
| 331 |
celery.current_app.conf.task_always_eager = False |
| 332 |
|
| 333 |
def test_sending_email(self): |
| 334 |
[result] = mail.send_mail('test', 'Testing with Celery! w00t!!', '[email protected]', |
| 335 |
['[email protected]']) |
| 336 |
self.assertEqual(result.get(), 1) |
| 337 |
self.assertEqual(len(mail.outbox), 1) |
| 338 |
self.assertEqual(mail.outbox[0].subject, 'test') |
| 339 |
|
| 340 |
def test_sending_html_email(self): |
| 341 |
msg = EmailMultiAlternatives('test', 'Testing with Celery! w00t!!', '[email protected]', |
| 342 |
['[email protected]']) |
| 343 |
html = '<p>Testing with Celery! w00t!!</p>' |
| 344 |
msg.attach_alternative(html, 'text/html') |
| 345 |
[result] = msg.send() |
| 346 |
self.assertEqual(result.get(), 1) |
| 347 |
self.assertEqual(len(mail.outbox), 1) |
| 348 |
self.assertEqual(mail.outbox[0].subject, 'test') |
| 349 |
self.assertEqual(len(mail.outbox[0].alternatives), 1) |
| 350 |
self.assertEqual(list(mail.outbox[0].alternatives[0]), [html, 'text/html']) |
| 351 |
|
| 352 |
def test_sending_mail_with_text_attachment(self): |
| 353 |
msg = mail.EmailMessage( |
| 354 |
'test', 'Testing with Celery! w00t!!', '[email protected]', |
| 355 |
['[email protected]']) |
| 356 |
msg.attach('image.png', 'csv content', 'text/csv') |
| 357 |
[result] = msg.send() |
| 358 |
self.assertEqual(result.get(), 1) |
| 359 |
self.assertEqual(len(mail.outbox), 1) |
| 360 |
self.assertEqual(mail.outbox[0].subject, 'test') |
| 361 |
self.assertEqual(mail.outbox[0].content_subtype, "plain") |
| 362 |
|
| 363 |
def test_sending_html_only_email(self): |
| 364 |
msg = mail.EmailMessage('test', 'Testing <b>with Celery! w00t!!</b>', '[email protected]', |
| 365 |
['[email protected]']) |
| 366 |
msg.content_subtype = "html" |
| 367 |
[result] = msg.send() |
| 368 |
self.assertEqual(result.get(), 1) |
| 369 |
self.assertEqual(len(mail.outbox), 1) |
| 370 |
self.assertEqual(mail.outbox[0].subject, 'test') |
| 371 |
self.assertEqual(mail.outbox[0].content_subtype, "html") |
| 372 |
|
| 373 |
def test_sending_mass_email(self): |
| 374 |
emails = ( |
| 375 |
('mass 1', 'mass message 1', '[email protected]', ['[email protected]']), |
| 376 |
('mass 2', 'mass message 2', '[email protected]', ['[email protected]']), |
| 377 |
) |
| 378 |
[result] = mail.send_mass_mail(emails) |
| 379 |
self.assertEqual(result.get(), 2) |
| 380 |
self.assertEqual(len(mail.outbox), 2) |
| 381 |
self.assertEqual(mail.outbox[0].subject, 'mass 1') |
| 382 |
self.assertEqual(mail.outbox[1].subject, 'mass 2') |
| 383 |
|
| 384 |
def test_sending_mass_email_chunked(self): |
| 385 |
emails = [ |
| 386 |
('mass %i' % i, 'message', '[email protected]', ['[email protected]']) |
| 387 |
for i in range(11)] |
| 388 |
with override_settings(CELERY_EMAIL_CHUNK_SIZE=4): |
| 389 |
[result1, result2, result3] = mail.send_mass_mail(emails) |
| 390 |
self.assertEqual(result1.get(), 4) |
| 391 |
self.assertEqual(result2.get(), 4) |
| 392 |
self.assertEqual(result3.get(), 3) |
| 393 |
self.assertEqual(len(mail.outbox), 11) |
| 394 |
self.assertEqual(mail.outbox[0].subject, 'mass 0') |
| 395 |
self.assertEqual(mail.outbox[1].subject, 'mass 1') |