/
test_mailing.py
463 lines (338 loc) · 13.7 KB
/
test_mailing.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
import itertools
import six
import unittest
from datetime import timedelta
from django.core import mail
from django.test.utils import patch_logger
from django.utils.six.moves import range
from django.utils.timezone import now
from newsletter.models import (
Newsletter, Subscription, Submission, Message, Article, get_default_sites
)
from newsletter.utils import ACTIONS
from .utils import MailTestCase, UserTestCase, template_exists
class MailingTestCase(MailTestCase):
def get_newsletter_kwargs(self):
""" Returns the keyword arguments for instanciating the newsletter. """
return {
'title': 'Test newsletter',
'slug': 'test-newsletter',
'sender': 'Test Sender',
'email': 'test@testsender.com'
}
def setUp(self):
self.n = Newsletter(**self.get_newsletter_kwargs())
self.n.save()
self.n.site = get_default_sites()
self.m = Message(title='Test message',
newsletter=self.n,
slug='test-message')
self.m.save()
self.s = Subscription(
name='Test Name', email='test@test.com',
newsletter=self.n, subscribed=True
)
self.s.save()
def send_email(self, action):
assert action in ACTIONS + ('message', ), 'Unknown action: %s' % action
if action == 'message':
# Create submission
sub = Submission.from_message(self.m)
sub.prepared = True
sub.publish_date = now() - timedelta(seconds=1)
sub.save()
# Send message email
Submission.submit_queue()
else:
self.s.send_activation_email(action)
class ArticleTestCase(MailingTestCase):
def make_article(self):
a = Article()
a.title = 'Test title'
a.text = 'This should be a very long text with <html> in it as well.'
a.post = self.m
a.save()
return a
def update(self, article):
return Article.objects.get(pk=article.pk)
def test_article(self):
self.make_article()
def test_sortorder_defaults(self):
total = 3
last = 0
for current in range(total):
a = self.make_article()
if last:
self.assertTrue(a.sortorder > last)
last = a.sortorder
class MessageTestCase(MailingTestCase):
def test_message_str(self):
m1 = Message(title='Test message', slug='test-message')
with patch_logger('newsletter.models', 'warning') as warnings:
self.assertEqual(six.text_type(m1), "Test message")
self.assertEqual(len(warnings), 1)
m2 = Message.objects.create(
title='Test message str',
newsletter=self.n,
slug='test-message-str'
)
self.assertEqual(six.text_type(m2), "Test message str in Test newsletter")
class CreateSubmissionTestCase(MailingTestCase):
def test_subscription(self):
""" Test whether the recipient corresponds for Subscription. """
self.assertEqual(self.s.get_recipient(), 'Test Name <test@test.com>')
def test_submission_from_message(self):
""" Test creating a submission from a message. """
sub = Submission.from_message(self.m)
subscriptions = sub.subscriptions.all()
self.assertEqual(list(subscriptions), [self.s])
self.assertFalse(sub.prepared)
self.assertFalse(sub.sent)
self.assertFalse(sub.sending)
def test_submission_subscribed(self):
""" Test a simpel submission with single subscriber. """
self.s.subscribed = False
self.s.save()
sub = Submission.from_message(self.m)
subscriptions = sub.subscriptions.all()
self.assertEqual(list(subscriptions), [])
def test_submission_unsubscribed(self):
""" Test submission with unsubscribed activated subscriber. """
self.s.unsubscribed = True
self.s.save()
sub = Submission.from_message(self.m)
subscriptions = sub.subscriptions.all()
self.assertEqual(list(subscriptions), [])
def test_submission_unsubscribed_unactivated(self):
""" Test submissions with unsubscribed unactivated subscriber. """
self.s.subscribed = False
self.s.unsubscribed = True
self.s.save()
sub = Submission.from_message(self.m)
subscriptions = sub.subscriptions.all()
self.assertEqual(list(subscriptions), [])
def test_twosubmissions(self):
""" Test submission with two activated subscribers. """
s2 = Subscription(
name='Test Name 2', email='test2@test.com',
newsletter=self.n, subscribed=True
)
s2.save()
sub = Submission.from_message(self.m)
subscriptions = sub.subscriptions.all()
self.assertTrue(self.s in list(subscriptions))
self.assertTrue(s2 in list(subscriptions))
def test_twosubmissions_unsubscried(self):
""" Test submission with two subscribers, one unactivated. """
s2 = Subscription(
name='Test Name 2', email='test2@test.com',
newsletter=self.n, subscribed=False
)
s2.save()
sub = Submission.from_message(self.m)
subscriptions = sub.subscriptions.all()
self.assertEqual(list(subscriptions), [self.s])
class SubmitSubmissionTestCase(MailingTestCase):
def setUp(self):
super(SubmitSubmissionTestCase, self).setUp()
self.sub = Submission.from_message(self.m)
self.sub.save()
def test_submission(self):
""" Assure initial Submission is in expected state. """
self.assertFalse(self.sub.prepared)
self.assertFalse(self.sub.sent)
self.assertFalse(self.sub.sending)
def test_nosubmit(self):
""" Assure nothing happends if not prepared. """
# Assure nothing happends
Submission.submit_queue()
self.assertFalse(self.sub.prepared)
self.assertFalse(self.sub.sent)
self.assertFalse(self.sub.sending)
def test_submitsubmission(self):
""" Test queue-based submission. """
# Adding a subscription after the submission has been created, it should
# not be used when submitting self.sub
new_subscr = Subscription.objects.create(
name='Other Name', email='other@test.com',
newsletter=self.n, subscribed=True
)
self.sub.prepared = True
self.sub.publish_date = now() - timedelta(seconds=1)
self.sub.save()
Submission.submit_queue()
# Get the object fresh from DB, as to assure no caching takes place
submission = Submission.objects.get(pk=self.sub.pk)
self.assertTrue(submission.sent)
self.assertFalse(submission.sending)
# Make sure mail is being sent out
self.assertEqual(len(mail.outbox), 1)
# Make sure a submission contains the title and unsubscribe URL
self.assertEmailContains(submission.message.title)
self.assertEmailContains(submission.newsletter.unsubscribe_url())
self.assertEmailHasHeader(
'List-Unsubscribe',
'http://example.com/newsletter/test-newsletter/unsubscribe/'
)
class SubscriptionTestCase(UserTestCase, MailingTestCase):
def setUp(self):
super(SubscriptionTestCase, self).setUp()
self.us = Subscription(user=self.user, newsletter=self.n)
self.us.save()
self.ns = Subscription(
name='Test susbcriber', newsletter=self.n,
email='test@test.com'
)
self.ns.save()
self.ss = [self.us, self.ns]
def test_usersubscription(self):
self.assertEqual(self.us.name, self.user.get_full_name())
self.assertEqual(self.us.email, self.user.email)
def test_subscribe_unsubscribe(self):
for s in self.ss:
self.assertFalse(s.subscribed)
self.assertFalse(s.unsubscribed)
self.assertFalse(s.subscribe_date)
self.assertFalse(s.unsubscribe_date)
# Repeat this to ensure consequencentness
for x in range(2):
s.subscribed = True
s.save()
self.assertTrue(s.subscribed)
self.assertTrue(s.subscribe_date)
self.assertFalse(s.unsubscribed)
old_subscribe_date = s.subscribe_date
s.unsubscribed = True
s.save()
self.assertFalse(s.subscribed)
self.assertTrue(s.unsubscribed)
self.assertTrue(s.unsubscribe_date)
s.unsubscribed = False
s.save()
self.assertFalse(s.unsubscribed)
self.assertTrue(s.subscribed)
self.assertNotEqual(s.subscribe_date, old_subscribe_date)
class AllEmailsTestsMixin(object):
""" Mixin for testing properties of sent e-mails for all message types. """
def assertSentEmailIsProper(self, action):
"""
This method should be overridden in subclasses.
Assertions identical for all message types should be in this method.
"""
raise NotImplementedError(
'%(class_name)s inherits from of AllEmailsTestsMixin '
'and should define assertSentEmailIsProper method.' % {
'class_name': self.__class__.__name__
}
)
def test_subscription_email(self):
""" Assure subscription email is proper. """
self.send_email('subscribe')
self.assertSentEmailIsProper('subscribe')
def test_unsubscription_email(self):
""" Assure unsubscription email is proper. """
self.send_email('unsubscribe')
self.assertSentEmailIsProper('unsubscribe')
def test_update_email(self):
""" Assure update email is proper. """
self.send_email('update')
self.assertSentEmailIsProper('update')
def test_message_email(self):
""" Assure message email is proper. """
self.send_email('message')
self.assertSentEmailIsProper('message')
class HtmlEmailsTestCase(MailingTestCase, AllEmailsTestsMixin):
"""
TestCase for testing whether e-mails sent for newsletter
with send_html=True have HTML alternatives.
"""
def get_newsletter_kwargs(self):
"""
Update keyword arguments for instanciating the newsletter
with send_html = True.
"""
kwargs = super(HtmlEmailsTestCase, self).get_newsletter_kwargs()
kwargs.update(send_html=True)
return kwargs
def assertSentEmailIsProper(self, action):
"""
Assert that there's exactly one email in outbox
and that it contains alternative with mimetype text/html.
"""
# Make sure one mail is being sent out
self.assertEqual(len(mail.outbox), 1)
# Make sure mail contains HTML alternative
self.assertEmailAlternativesContainMimetype('text/html')
class TextOnlyEmailsTestCase(MailingTestCase, AllEmailsTestsMixin):
"""
TestCase for testing whether e-mails sent for newsletter
with send_html=False are text only.
"""
def get_newsletter_kwargs(self):
"""
Update keyword arguments for instanciating the newsletter
with send_html = False.
"""
kwargs = super(TextOnlyEmailsTestCase, self).get_newsletter_kwargs()
kwargs.update(send_html=False)
return kwargs
def assertSentEmailIsProper(self, action):
"""
Assert that there's exactly one email in outbox
and that it has no alternative content types.
"""
# Make sure one mail is being sent out
self.assertEqual(len(mail.outbox), 1)
# Make sure mail is text only
self.assertEmailHasNoAlternatives()
template_overrides = (
'newsletter/message/test-newsletter-with-overrides/' + action + suff
for action, suff in itertools.product(
('subscribe', 'update', 'unsubscribe', 'message'),
('_subject.txt', '.txt', '.html')
)
)
# When tests are run outside test project
# test templates overrides will not exist,
# so skip their testing.
@unittest.skipUnless(
all(
template_exists(template_name) for template_name in template_overrides
),
'Test templates overrides not found.'
)
class TemplateOverridesTestCase(MailingTestCase, AllEmailsTestsMixin):
"""
TestCase for testing template overrides for specific newsletters.
"""
def get_newsletter_kwargs(self):
"""
Update keyword arguments for instanciating the newsletter
so that slug corresponds to one for which template overrides exists
and make sure e-mails will be sent with text and HTML versions.
"""
kwargs = super(TemplateOverridesTestCase, self).get_newsletter_kwargs()
kwargs.update(slug='test-newsletter-with-overrides',
send_html=True)
return kwargs
def assertSentEmailIsProper(self, action):
"""
Assert that there's exactly one email in outbox
and that it contains proper strings from template overrides
in subject and body.
"""
# Make sure one mail is being sent out
self.assertEqual(len(mail.outbox), 1)
# Make sure mail subject contains string
# from template override for given action
self.assertEmailSubjectContains(
'override for %s_subject.txt' % action
)
# Make sure body of mail text version contains string
# from text template override for given action
self.assertEmailBodyContains('override for %s.txt' % action)
# Make sure body of mail HTML version contains string
# from HTML template override for given action
self.assertEmailAlternativeBodyContains(
'override for %s.html' % action
)