-
Notifications
You must be signed in to change notification settings - Fork 82
/
tests.py
509 lines (429 loc) · 22 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import json
import sys
import unittest
from email.mime.image import MIMEImage
from io import BytesIO
from django.core import mail
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.test import TestCase
from postmark.django_backend import EmailBackend
if sys.version_info[0] < 3:
from StringIO import StringIO
from urllib2 import HTTPError
else:
from io import StringIO
from urllib.error import HTTPError
import mock
from postmark import (
PMBatchMail, PMMail, PMMailInactiveRecipientException,
PMMailUnprocessableEntityException, PMMailServerErrorException,
PMMailMissingValueException, PMBounceManager
)
from django.conf import settings
class PMMailTests(unittest.TestCase):
def test_406_error_inactive_recipient(self):
json_payload = BytesIO()
json_payload.write(b'{"Message": "", "ErrorCode": 406}')
json_payload.seek(0)
message = PMMail(sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
422, '', {}, json_payload)):
self.assertRaises(PMMailInactiveRecipientException, message.send)
def test_422_error_unprocessable_entity(self):
json_payload = BytesIO()
json_payload.write(b'{"Message": "", "ErrorCode": 422}')
json_payload.seek(0)
message = PMMail(sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
422, '', {}, json_payload)):
self.assertRaises(PMMailUnprocessableEntityException, message.send)
def test_500_error_server_error(self):
message = PMMail(sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
500, '', {}, None)):
self.assertRaises(PMMailServerErrorException, message.send)
def assert_missing_value_exception(self, message_func, error_message):
with self.assertRaises(PMMailMissingValueException) as cm:
message_func()
self.assertEqual(error_message, cm.exception.parameter)
def test_send(self):
# Confirm send() still works as before use_template was added
message = PMMail(sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
200, '', {}, None)):
message.send()
def test_missing_subject(self):
# No subject should raise exception when using send()
message = PMMail(sender='[email protected]', to='[email protected]',
text_body='Body', api_key='test')
self.assert_missing_value_exception(
message.send,
'Cannot send an e-mail without a subject'
)
def test_missing_recipient_fields(self):
# No recipient should raise exception when using send()
message = PMMail(sender='[email protected]', subject='test',
text_body='Body', api_key='test')
self.assert_missing_value_exception(
message.send,
'Cannot send an e-mail without at least one recipient (.to field or .bcc field)'
)
def test_missing_to_field_but_populated_bcc_field(self):
# No to field but populated bcc field should not raise exception when using send()
message = PMMail(sender='[email protected]', subject='test', bcc='[email protected]',
text_body='Body', api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 200, '', {}, None)):
message.send()
def test_check_values_bad_template_data(self):
# Try sending with template ID only
message = PMMail(api_key='test', sender='[email protected]', to='[email protected]', template_id=1)
self.assert_missing_value_exception(
message.send,
'Cannot send a template e-mail without a both template_id and template_model set'
)
def test_send_with_template(self):
# Both template_id and template_model are set, so send should work.
message = PMMail(api_key='test', sender='[email protected]', to='[email protected]',
template_id=1, template_model={'junk': 'more junk'})
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
200, '', {}, None)):
message.send()
def test_check_values_bad_template_alias_data(self):
client = PMMail(api_key='test', sender='[email protected]', to='[email protected]', template_alias='my-template-alias')
self.assert_missing_value_exception(
client.send, 'Cannot send a template e-mail without both a template_alias and template_model set'
)
def test_check_values_bad_template_model_data(self):
client = PMMail(api_key='test', sender='[email protected]', to='[email protected]', template_model={'junk': 'more junk'})
self.assert_missing_value_exception(
client.send, 'Cannot send a template e-mail without either a template_id or template_alias set'
)
def test_send_with_alias(self):
message = PMMail(
api_key='test',
sender='[email protected]',
to='[email protected]',
template_alias='my-template-alias',
template_model={'junk': 'more junk'},
)
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 200, '', {}, None)):
message.send()
def test_inline_attachments(self):
image = MIMEImage(b'image_file', 'png', name='image.png')
image_with_id = MIMEImage(b'inline_image_file', 'png', name='image_with_id.png')
image_with_id.add_header('Content-ID', '<[email protected]>')
inline_image = MIMEImage(b'inline_image_file', 'png', name='inline_image.png')
inline_image.add_header('Content-ID', '<[email protected]>')
inline_image.add_header('Content-Disposition', 'inline', filename='inline_image.png')
expected = [
{'Name': 'TextFile', 'Content': 'content', 'ContentType': 'text/plain'},
{'Name': 'InlineImage', 'Content': 'image_content', 'ContentType': 'image/png', 'ContentID': 'cid:[email protected]'},
{'Name': 'image.png', 'Content': 'aW1hZ2VfZmlsZQ==', 'ContentType': 'image/png'},
{'Name': 'image_with_id.png', 'Content': 'aW5saW5lX2ltYWdlX2ZpbGU=', 'ContentType': 'image/png', 'ContentID': '[email protected]'},
{'Name': 'inline_image.png', 'Content': 'aW5saW5lX2ltYWdlX2ZpbGU=', 'ContentType': 'image/png', 'ContentID': 'cid:[email protected]'},
]
json_message = PMMail(
sender='[email protected]', to='[email protected]', subject='Subject', text_body='Body', api_key='test',
attachments=[
('TextFile', 'content', 'text/plain'),
('InlineImage', 'image_content', 'image/png', 'cid:[email protected]'),
image,
image_with_id,
inline_image,
]
).to_json_message()
assert len(json_message['Attachments']) == len(expected)
for orig, attachment in zip(expected, json_message['Attachments']):
for k, v in orig.items():
assert orig[k] == attachment[k].rstrip()
def test_send_metadata(self):
message = PMMail(api_key='test', sender='[email protected]', to='[email protected]',
subject='test', text_body='test', metadata={'test': 'test'})
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
200, '', {}, None)):
message.send()
def test_send_metadata_invalid_format(self):
self.assertRaises(TypeError, PMMail, api_key='test', sender='[email protected]', to='[email protected]',
subject='test', text_body='test', metadata={'test': {}})
class PMBatchMailTests(unittest.TestCase):
def test_406_error_inactive_recipient(self):
messages = [
PMMail(
sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test'
),
PMMail(
sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test'
),
]
json_payload = BytesIO()
json_payload.write(b'{"Message": "", "ErrorCode": 406}')
json_payload.seek(0)
batch = PMBatchMail(messages=messages, api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
422, '', {}, json_payload)):
self.assertRaises(PMMailInactiveRecipientException, batch.send)
def test_422_error_unprocessable_entity(self):
messages = [
PMMail(
sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test'
),
PMMail(
sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test'
),
]
json_payload = BytesIO()
json_payload.write(b'{"Message": "", "ErrorCode": 422}')
json_payload.seek(0)
batch = PMBatchMail(messages=messages, api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
422, '', {}, json_payload)):
self.assertRaises(PMMailUnprocessableEntityException, batch.send)
def test_500_error_server_error(self):
messages = [
PMMail(
sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test'
),
PMMail(
sender='[email protected]', to='[email protected]',
subject='Subject', text_body='Body', api_key='test'
),
]
batch = PMBatchMail(messages=messages, api_key='test')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('',
500, '', {}, None)):
self.assertRaises(PMMailServerErrorException, batch.send)
class PMBounceManagerTests(unittest.TestCase):
def test_activate(self):
bounce = PMBounceManager(api_key='test')
with mock.patch('postmark.core.HTTPConnection.request') as mock_request:
with mock.patch('postmark.core.HTTPConnection.getresponse') as mock_response:
mock_response.return_value = StringIO('{"test": "test"}')
self.assertEqual(bounce.activate(1), {'test': 'test'})
class EmailBackendTests(TestCase):
def test_send_multi_alternative_html_email(self):
# build a message and send it
message = EmailMultiAlternatives(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='hello there'
)
message.attach_alternative('<b>hello</b> there', 'text/html')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 200, '', {}, None)) as transport:
message.send()
data = json.loads(transport.call_args[0][0].data.decode('utf-8'))
self.assertEqual('hello there', data['TextBody'])
self.assertEqual('<b>hello</b> there', data['HtmlBody'])
def test_send_content_subtype_email(self):
# build a message and send it
message = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
message.content_subtype = 'html'
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 200, '', {}, None)) as transport:
message.send()
data = json.loads(transport.call_args[0][0].data.decode('utf-8'))
self.assertEqual('<b>hello</b> there', data['HtmlBody'])
self.assertFalse('TextBody' in data)
def test_send_multi_alternative_with_subtype_html_email(self):
"""
Client uses EmailMultiAlternative but instead of specifying a html alternative they insert html content
into the main message and specify message_subtype
:return:
"""
message = EmailMultiAlternatives(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
# NO alternatives attached. subtype specified instead
message.content_subtype = 'html'
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 200, '', {}, None)) as transport:
message.send()
data = json.loads(transport.call_args[0][0].data.decode('utf-8'))
self.assertFalse('TextBody' in data)
self.assertEqual('<b>hello</b> there', data['HtmlBody'])
def test_message_count_single(self):
"""Test backend returns count sending single message."""
with self.settings(POSTMARK_RETURN_MESSAGE_ID=False):
message = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
with mock.patch('postmark.core.urlopen') as transport:
transport.return_value.read.return_value.decode.return_value = """
{
"To": "[email protected]",
"SubmittedAt": "2014-02-17T07:25:01.4178645-05:00",
"MessageID": "0a129aee-e1cd-480d-b08d-4f48548ff48d",
"ErrorCode": 0,
"Message": "OK"
}
"""
transport.return_value.code = 200
response = message.send()
self.assertEqual(response, 1)
def test_message_count_batch(self):
"""Test backend returns count sending batch messages."""
with self.settings(POSTMARK_RETURN_MESSAGE_ID=False):
message1 = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
message2 = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
with mock.patch('postmark.core.urlopen') as transport:
transport.return_value.read.return_value.decode.return_value = """
[
{
"ErrorCode": 0,
"Message": "OK",
"MessageID": "b7bc2f4a-e38e-4336-af7d-e6c392c2f817",
"SubmittedAt": "2010-11-26T12:01:05.1794748-05:00",
"To": "[email protected]"
},
{
"ErrorCode": 0,
"Message": "OK",
"MessageID": "e2ecbbfc-fe12-463d-b933-9fe22915106d",
"SubmittedAt": "2010-11-26T12:01:05.1794748-05:00",
"To": "[email protected]"
}
]
"""
transport.return_value.code = 200
# Directly send bulk mail via django
connection = mail.get_connection()
sent_messages = connection.send_messages([message1, message2])
self.assertEqual(sent_messages, 2)
def test_send_messages_nothing_to_send_single(self):
"""Make sure no errors when send results in zero messages."""
with self.settings(POSTMARK_RETURN_MESSAGE_ID=False):
message1 = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=[], subject='html test', body='<b>hello</b> there'
)
with mock.patch('postmark.core.urlopen') as transport:
# Directly send bulk mail via django
connection = mail.get_connection()
sent_messages = connection.send_messages([message1])
self.assertEqual(0, sent_messages)
def test_send_messages_nothing_to_send_double(self):
"""Make sure no errors when send results in zero messages."""
with self.settings(POSTMARK_RETURN_MESSAGE_ID=False):
message1 = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=[], subject='html test', body='<b>hello</b> there'
)
message2 = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=[], subject='html test', body='<b>hello</b> there'
)
with mock.patch('postmark.core.urlopen') as transport:
# Directly send bulk mail via django
connection = mail.get_connection()
sent_messages = connection.send_messages([message1, message2])
self.assertEqual(0, sent_messages)
def test_message_id_single(self):
"""Test backend returns message sending single message with setting True"""
with self.settings(POSTMARK_RETURN_MESSAGE_ID=True):
message = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
with mock.patch('postmark.core.urlopen') as transport:
transport.return_value.read.return_value.decode.return_value = """
{
"To": "[email protected]",
"SubmittedAt": "2014-02-17T07:25:01.4178645-05:00",
"MessageID": "0a129aee-e1cd-480d-b08d-4f48548ff48d",
"ErrorCode": 0,
"Message": "OK"
}
"""
transport.return_value.code = 200
message_ids = message.send()
self.assertEqual(message_ids[0], "0a129aee-e1cd-480d-b08d-4f48548ff48d")
def test_message_id_batch(self):
"""Test backend returns message sending batch messages with setting True"""
with self.settings(POSTMARK_RETURN_MESSAGE_ID=True):
message1 = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
message2 = EmailMessage(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='<b>hello</b> there'
)
with mock.patch('postmark.core.urlopen') as transport:
transport.return_value.read.return_value.decode.return_value = """
[
{
"ErrorCode": 0,
"Message": "OK",
"MessageID": "b7bc2f4a-e38e-4336-af7d-e6c392c2f817",
"SubmittedAt": "2010-11-26T12:01:05.1794748-05:00",
"To": "[email protected]"
},
{
"ErrorCode": 0,
"Message": "OK",
"MessageID": "e2ecbbfc-fe12-463d-b933-9fe22915106d",
"SubmittedAt": "2010-11-26T12:01:05.1794748-05:00",
"To": "[email protected]"
}
]
"""
transport.return_value.code = 200
# Directly send bulk mail via django
connection = mail.get_connection()
sent_messages = connection.send_messages([message1, message2])
self.assertIn('b7bc2f4a-e38e-4336-af7d-e6c392c2f817', sent_messages)
self.assertIn('e2ecbbfc-fe12-463d-b933-9fe22915106d', sent_messages)
def test_send_attachment_bytes(self):
message = EmailMultiAlternatives(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='hello there'
)
f = StringIO(u'1,2,3')
message.attach('filename.csv', f.read(), 'text/csv')
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 200, '', {}, None)):
message.send()
def test_message_stream(self):
message = EmailMultiAlternatives(
connection=EmailBackend(api_key='dummy'),
from_email='[email protected]', to=['[email protected]'], subject='html test', body='hello there'
)
message.attach_alternative('<b>hello</b> there', 'text/html')
message.message_stream = 'broadcast'
with mock.patch('postmark.core.urlopen', side_effect=HTTPError('', 200, '', {}, None)) as transport:
message.send()
data = json.loads(transport.call_args[0][0].data.decode('utf-8'))
self.assertEqual('broadcast', data['MessageStream'])
self.assertEqual('hello there', data['TextBody'])
self.assertEqual('<b>hello</b> there', data['HtmlBody'])
if __name__ == '__main__':
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
INSTALLED_APPS=[
],
MIDDLEWARE_CLASSES=[],
EMAIL_BACKEND = 'postmark.django_backend.EmailBackend',
POSTMARK_API_KEY='dummy',
)
unittest.main()