forked from themartorana/python-postmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
404 lines (349 loc) · 13.8 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
import json
import sys
import unittest
from email.mime.image import MIMEImage
from io import BytesIO
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.test import override_settings, 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="from@example.com",
to="to@example.com",
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="from@example.com",
to="to@example.com",
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="from@example.com",
to="to@example.com",
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="from@example.com",
to="to@example.com",
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="from@example.com", to="to@example.com", 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="from@example.com", 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="from@example.com",
subject="test",
bcc="to@example.com",
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="from@example.com", to="to@example.com", 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_check_values_bad_template_data_alias(self):
# Try sending with template ID only
message = PMMail(
api_key="test", sender="from@example.com", to="to@example.com", template_alias="alias"
)
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="from@example.com",
to="to@example.com",
template_id=1,
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", "<image2@postmarkapp.com>")
inline_image = MIMEImage(b"inline_image_file", "png", name="inline_image.png")
inline_image.add_header("Content-ID", "<image3@postmarkapp.com>")
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:image@postmarkapp.com",
},
{"Name": "image.png", "Content": "aW1hZ2VfZmlsZQ==", "ContentType": "image/png"},
{
"Name": "image_with_id.png",
"Content": "aW5saW5lX2ltYWdlX2ZpbGU=",
"ContentType": "image/png",
"ContentID": "image2@postmarkapp.com",
},
{
"Name": "inline_image.png",
"Content": "aW5saW5lX2ltYWdlX2ZpbGU=",
"ContentType": "image/png",
"ContentID": "cid:image3@postmarkapp.com",
},
]
json_message = PMMail(
sender="from@example.com",
to="to@example.com",
subject="Subject",
text_body="Body",
api_key="test",
attachments=[
("TextFile", "content", "text/plain"),
("InlineImage", "image_content", "image/png", "cid:image@postmarkapp.com"),
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="from@example.com",
to="to@example.com",
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="from@example.com",
to="to@example.com",
subject="test",
text_body="test",
metadata={"test": {}},
)
class PMBatchMailTests(unittest.TestCase):
def test_406_error_inactive_recipient(self):
messages = [
PMMail(
sender="from@example.com",
to="to@example.com",
subject="Subject",
text_body="Body",
api_key="test",
),
PMMail(
sender="from@example.com",
to="to@example.com",
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="from@example.com",
to="to@example.com",
subject="Subject",
text_body="Body",
api_key="test",
),
PMMail(
sender="from@example.com",
to="to@example.com",
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="from@example.com",
to="to@example.com",
subject="Subject",
text_body="Body",
api_key="test",
),
PMMail(
sender="from@example.com",
to="to@example.com",
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.getresponse") as mock_response:
mock_response.return_value = StringIO('{"test": "test"}')
self.assertEqual(bounce.activate(1), {"test": "test"})
class EmailBackendTests(TestCase):
def setUp(self):
self.backend = EmailBackend(api_key="dummy")
def test_send_multi_alternative_html_email(self):
# build a message and send it
message = EmailMultiAlternatives(
connection=self.backend,
from_email="from@test.com",
to=["recipient@test.com"],
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=self.backend,
from_email="from@test.com",
to=["recipient@test.com"],
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=self.backend,
from_email="from@test.com",
to=["recipient@test.com"],
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"])
if __name__ == "__main__":
if not settings.configured:
settings.configure(
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
INSTALLED_APPS=[],
MIDDLEWARE_CLASSES=[],
)
unittest.main()