/
test_automatic_emails.py
926 lines (810 loc) · 32.2 KB
/
test_automatic_emails.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import datetime
import mock
from nose.plugins.attrib import attr
from configman import ConfigurationManager
from socorro.cron import crontabber
from socorro.cron.jobs import automatic_emails
from socorro.external.exacttarget import exacttarget
from socorro.lib.datetimeutil import utc_now
from ..base import IntegrationTestCaseBase, TestCaseBase
#==============================================================================
@attr(integration='postgres')
class TestAutomaticEmails(TestCaseBase):
def _setup_simple_config(self, domains=None):
conf = automatic_emails.AutomaticEmailsCronApp.get_required_config()
conf.add_option('logger', default=mock.Mock())
return ConfigurationManager(
[conf],
values_source_list=[{
'common_email_domains': domains,
}],
argv_source=[]
)
def test_correct_email(self):
domains = ('gmail.com', 'yahoo.com')
config_manager = self._setup_simple_config(domains=domains)
with config_manager.context() as config:
app = automatic_emails.AutomaticEmailsCronApp(config, '')
# easy corrections
self.assertEqual(
app.correct_email('peterbe@YAHOOO.COM', typo_correct=True),
'peterbe@yahoo.com'
)
self.assertEqual(
app.correct_email('peterbe@gmai.com', typo_correct=True),
'peterbe@gmail.com'
)
self.assertEqual(
app.correct_email('peterbe@gmaill.com', typo_correct=True),
'peterbe@gmail.com'
)
self.assertEqual(
# case insensitive
app.correct_email('peterbe@Gamil.com', typo_correct=True),
'peterbe@gmail.com'
)
self.assertEqual(
app.correct_email('peterbe@gmaiK.com', typo_correct=True),
'peterbe@gmail.com'
)
self.assertEqual(
app.correct_email('peterbe@gmail..com', typo_correct=True),
'peterbe@gmail.com'
)
# dots here and there
self.assertEqual(
app.correct_email('peterbe@gmail.com.'),
'peterbe@gmail.com'
)
self.assertEqual(
app.correct_email('peterbe@.gmail.com'),
'peterbe@gmail.com'
)
self.assertEqual(
app.correct_email('peterbe@.gmail.com.'),
'peterbe@gmail.com'
)
# dots and typos
self.assertEqual(
# case insensitive
app.correct_email('peterbe@Gamil.com.', typo_correct=True),
'peterbe@gmail.com'
)
# What doesn't work are edit distances greater than 1
self.assertFalse(app.correct_email('peterbe@gamill.com'))
self.assertFalse(app.correct_email('peterbe@gmil.cam'))
# and don't mess with @ signs
self.assertFalse(
app.correct_email('peterbe@hotmail.com@gamil.com')
)
def test_correct_ambiguous_email(self):
domains = ('gmail.com', 'yahoo.com', 'mail.com')
config_manager = self._setup_simple_config(domains=domains)
with config_manager.context() as config:
app = automatic_emails.AutomaticEmailsCronApp(config, '')
# because 'gmail.com' and 'mail.com' is so similar,
# we don't want correction of 'mail.com' to incorrectly
# become 'gmail.com'
self.assertEqual(
app.correct_email('peterbe@gmail.com', typo_correct=True),
None
)
self.assertEqual(
app.correct_email('peterbe@mail.com', typo_correct=True),
None
)
#==============================================================================
@attr(integration='postgres')
class IntegrationTestAutomaticEmails(IntegrationTestCaseBase):
def setUp(self):
super(IntegrationTestAutomaticEmails, self).setUp()
# prep a fake table
now = utc_now() - datetime.timedelta(minutes=30)
last_month = now - datetime.timedelta(days=31)
cursor = self.conn.cursor()
cursor.execute("""
INSERT INTO reports
(uuid, email, product, version, release_channel, date_processed)
VALUES (
'1',
'someone@example.com',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
), (
'2',
'"Quidam" <quidam@example.com>',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
), (
'3',
'anotherone@example.com',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
), (
'4',
'a@example.org',
'NightlyTrain',
'1.0',
'Nightly',
'%(now)s'
), (
'5',
'b@example.org',
'NightlyTrain',
'1.0',
'Nightly',
'%(now)s'
), (
'6',
'c@example.org',
'NightlyTrain',
'1.0',
'Nightly',
'%(now)s'
), (
'7',
'd@example.org',
'NightlyTrain',
'1.0',
'Nightly',
'%(now)s'
), (
'8',
'e@example.org',
'NightlyTrain',
'1.0',
'Nightly',
'%(now)s'
), (
'9',
'me@my.name',
'EarthRaccoon',
'1.0',
'Nightly',
'%(now)s'
), (
'18',
'z\xc3\x80drian@example.org',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
)
""" % {'now': now})
# Let's insert a duplicate
cursor.execute("""
INSERT INTO reports
(uuid, email, product, version, release_channel, date_processed)
VALUES (
'10',
'anotherone@example.com',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
)
""" % {'now': now})
# And let's insert some invalid crashes
cursor.execute("""
INSERT INTO reports
(uuid, email, product, version, release_channel, date_processed)
VALUES (
'11',
null,
'WaterWolf',
'20.0',
'Release',
'%(now)s'
), (
'12',
'myemail@example.com',
'WaterWolf',
'20.0',
'Release',
'%(last_month)s'
), (
'13',
'menime@example.com',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
), (
'14',
'hi@mynameis.slim',
'WindBear',
'20.0',
'Release',
'%(now)s'
)
""" % {'now': now, 'last_month': last_month})
# Finally some invalid email addresses
cursor.execute("""
INSERT INTO reports
(uuid, email, product, version, release_channel, date_processed)
VALUES (
'15',
' ',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
), (
'16',
'invalid@email',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
), (
'17',
'i.do.not.work',
'WaterWolf',
'20.0',
'Release',
'%(now)s'
)
""" % {'now': now})
cursor.execute("""
INSERT INTO emails (email, last_sending)
VALUES (
'someone@example.com',
'%(last_month)s'
), (
'"Quidam" <quidam@example.com>',
'%(last_month)s'
), (
'menime@example.com',
'%(now)s'
)
""" % {'now': now, 'last_month': last_month})
self.conn.commit()
def tearDown(self):
self.conn.cursor().execute("""
TRUNCATE TABLE reports, emails CASCADE;
""")
self.conn.commit()
super(IntegrationTestAutomaticEmails, self).tearDown()
def _setup_config_manager(
self,
delay_between_emails=7,
exacttarget_user='',
exacttarget_password='',
restrict_products=['WaterWolf'],
email_template='socorro_dev_test'
):
extra_value_source = {
'crontabber.class-AutomaticEmailsCronApp.delay_between_emails':
delay_between_emails,
'crontabber.class-AutomaticEmailsCronApp.exacttarget_user':
exacttarget_user,
'crontabber.class-AutomaticEmailsCronApp.exacttarget_password':
exacttarget_password,
'crontabber.class-AutomaticEmailsCronApp.restrict_products':
restrict_products,
'crontabber.class-AutomaticEmailsCronApp.email_template':
email_template,
}
return super(
IntegrationTestAutomaticEmails,
self
)._setup_config_manager(
'socorro.cron.jobs.automatic_emails.AutomaticEmailsCronApp|1h',
extra_value_source=extra_value_source
)
def _setup_simple_config(self, common_email_domains=None):
conf = automatic_emails.AutomaticEmailsCronApp.get_required_config()
conf.add_option('logger', default=mock.Mock())
values_source_list = {
'delay_between_emails': 7,
'exacttarget_user': '',
'exacttarget_password': '',
'restrict_products': ['WaterWolf'],
'email_template': 'socorro_dev_test'
}
if common_email_domains:
values_source_list['common_email_domains'] = common_email_domains
return ConfigurationManager(
[conf],
values_source_list=[values_source_list],
argv_source=[]
)
def _setup_test_mode_config(self):
conf = automatic_emails.AutomaticEmailsCronApp.get_required_config()
conf.add_option('logger', default=mock.Mock())
return ConfigurationManager(
[conf],
values_source_list=[{
'delay_between_emails': 7,
'exacttarget_user': '',
'exacttarget_password': '',
'restrict_products': ['WaterWolf'],
'test_mode': True,
'email_template': 'socorro_dev_test'
}],
argv_source=[]
)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_cron_job(self, exacttarget_mock):
config_manager = self._setup_config_manager()
et_mock = exacttarget_mock.return_value
# Make get_subscriber raise an exception
list_service = et_mock.list.return_value = mock.Mock()
list_service.get_subscriber = mock.Mock(
side_effect=exacttarget.NewsletterException()
)
with config_manager.context() as config:
tab = crontabber.CronTabber(config)
tab.run_all()
information = self._load_structure()
assert information['automatic-emails']
assert not information['automatic-emails']['last_error']
assert information['automatic-emails']['last_success']
self.assertEqual(et_mock.trigger_send.call_count, 4)
last_email = u'z\xc0drian@example.org'
# Verify the last call to trigger_send
fields = {
'EMAIL_ADDRESS_': last_email,
'EMAIL_FORMAT_': 'H',
'TOKEN': last_email
}
et_mock.trigger_send.assert_called_with('socorro_dev_test', fields)
# Verify that user's data was updated
cursor = self.conn.cursor()
emails_list = (
'someone@example.com',
'"Quidam" <quidam@example.com>',
'anotherone@example.com'
)
sql = """
SELECT last_sending
FROM emails
WHERE email IN %s
""" % (emails_list,)
cursor.execute(sql)
self.assertEqual(cursor.rowcount, 3)
now = utc_now()
for row in cursor.fetchall():
self.assertEqual(row[0].year, now.year)
self.assertEqual(row[0].month, now.month)
self.assertEqual(row[0].day, now.day)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_run(self, exacttarget_mock):
config_manager = self._setup_simple_config()
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
job.run(self.conn, utc_now())
et_mock = exacttarget_mock.return_value
self.assertEqual(et_mock.trigger_send.call_count, 4)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_send_email(self, exacttarget_mock):
list_service_mock = exacttarget_mock.return_value.list.return_value
list_service_mock.get_subscriber.return_value = {
'token': 'fake@example.com'
}
config_manager = self._setup_simple_config()
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'fake@example.com',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
fields = {
'EMAIL_ADDRESS_': report['email'],
'EMAIL_FORMAT_': 'H',
'TOKEN': report['email']
}
exacttarget_mock.return_value.trigger_send.assert_called_with(
'socorro_dev_test',
fields
)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_send_email_test_mode(self, exacttarget_mock):
list_service_mock = exacttarget_mock.return_value.list.return_value
list_service_mock.get_subscriber.return_value = {
'token': 'fake@example.com'
}
config_manager = self._setup_test_mode_config()
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'fake@example.com',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
fields = {
'EMAIL_ADDRESS_': config.test_email_address,
'EMAIL_FORMAT_': 'H',
'TOKEN': 'fake@example.com'
}
exacttarget_mock.return_value.trigger_send.assert_called_with(
'socorro_dev_test',
fields
)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_error_in_send_email(self, exacttarget_mock):
list_service_mock = exacttarget_mock.return_value.list.return_value
list_service_mock.get_subscriber.return_value = {
'token': 'fake@example.com'
}
exacttarget_mock.return_value.trigger_send.side_effect = (
exacttarget.NewsletterException('error')
)
config_manager = self._setup_simple_config()
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'fake@example.com',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
fields = {
'EMAIL_ADDRESS_': 'fake@example.com',
'EMAIL_FORMAT_': 'H',
'TOKEN': 'fake@example.com'
}
exacttarget_mock.return_value.trigger_send.assert_called_with(
'socorro_dev_test',
fields
)
self.assertEqual(config.logger.error.call_count, 1)
config.logger.error.assert_called_with(
'Unable to send an email to %s, error is: %s',
'fake@example.com', 'error', exc_info=True
)
list_service = exacttarget_mock.return_value.list.return_value
list_service.get_subscriber.side_effect = (
Exception(404, 'Bad Request')
)
exacttarget_mock.return_value.trigger_send.side_effect = (
Exception(404, 'Bad Request')
)
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'fake@example.com',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
fields = {
'EMAIL_ADDRESS_': u'fake@example.com',
'EMAIL_FORMAT_': 'H',
'TOKEN': u'fake@example.com'
}
exacttarget_mock.return_value.trigger_send.assert_called_with(
'socorro_dev_test',
fields
)
self.assertEqual(config.logger.error.call_count, 2)
config.logger.error.assert_called_with(
'Unable to send an email to %s, fields are %s, error is: %s',
u'fake@example.com',
str(fields),
"(404, 'Bad Request')",
exc_info=True
)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_error_in_send_email_with_easy_correction(self, exacttarget_mock):
attempted_emails = []
def mocked_trigger_send(email_template, fields):
attempted_emails.append(fields['EMAIL_ADDRESS_'])
return True
exacttarget_mock.return_value.trigger_send.side_effect = \
mocked_trigger_send
config_manager = self._setup_simple_config(
common_email_domains=['example.com', 'gmail.com']
)
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'fake@example.com.',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
self.assertEqual(config.logger.error.call_count, 0)
# note that this means only one attempt was made
self.assertEqual(attempted_emails, ['fake@example.com'])
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_error_in_send_email_with_clever_recovery(self, exacttarget_mock):
attempted_emails = []
def mocked_trigger_send(email_template, fields):
attempted_emails.append(fields['EMAIL_ADDRESS_'])
if fields['EMAIL_ADDRESS_'].endswith('exampl.com'):
raise exacttarget.NewsletterException('error')
else:
return True
exacttarget_mock.return_value.trigger_send.side_effect = \
mocked_trigger_send
config_manager = self._setup_simple_config(
common_email_domains=['example.com', 'gmail.com']
)
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'fake@exampl.com',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
self.assertEqual(config.logger.error.call_count, 0)
self.assertEqual(
attempted_emails,
['fake@exampl.com', 'fake@example.com']
)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_error_in_send_email_recovery_failing(self, exacttarget_mock):
attempted_emails = []
def mocked_trigger_send(email_template, fields):
# raise an error no matter what
attempted_emails.append(fields['EMAIL_ADDRESS_'])
raise exacttarget.NewsletterException('error')
exacttarget_mock.return_value.trigger_send.side_effect = \
mocked_trigger_send
config_manager = self._setup_simple_config(
common_email_domains=['example.com', 'gmail.com']
)
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'fake@exampl.com',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
self.assertEqual(config.logger.error.call_count, 1)
config.logger.error.assert_called_with(
'Unable to send a corrected email to %s, error is: %s',
'fake@example.com', 'error', exc_info=True
)
self.assertEqual(
attempted_emails,
['fake@exampl.com', 'fake@example.com']
)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_error_in_send_email_with_ambiguous_domain(self, exacttarget_mock):
"""try to send to a mail.com but let it fail.
Because `mail.com` easily is spell corrected to `gmail.com` but
we add `mail.com` as a common email domain in the config.
"""
attempted_emails = []
def mocked_trigger_send(email_template, fields):
# raise an error no matter what
attempted_emails.append(fields['EMAIL_ADDRESS_'])
raise exacttarget.NewsletterException('error')
if fields['EMAIL_ADDRESS_'].endswith('@mail.com.'):
raise exacttarget.NewsletterException('error')
else:
return True
exacttarget_mock.return_value.trigger_send.side_effect = \
mocked_trigger_send
config_manager = self._setup_simple_config(
common_email_domains=['example.com', 'gmail.com', 'mail.com']
)
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
report = {
'email': 'banned@mail.com',
'product': 'WaterWolf',
'version': '20.0',
'release_channel': 'Release',
}
job.send_email(report)
self.assertEqual(config.logger.error.call_count, 1)
config.logger.error.assert_called_with(
'Unable to send an email to %s, error is: %s',
'banned@mail.com', 'error', exc_info=True
)
self.assertEqual(
attempted_emails,
['banned@mail.com']
)
def test_update_user(self):
config_manager = self._setup_simple_config()
with config_manager.context() as config:
job = automatic_emails.AutomaticEmailsCronApp(config, '')
now = utc_now()
report = {
'email': 'someone@example.com'
}
job.update_user(report, now, self.conn)
cursor = self.conn.cursor()
cursor.execute("""
SELECT last_sending FROM emails WHERE email=%(email)s
""", report)
self.assertEqual(cursor.rowcount, 1)
row = cursor.fetchone()
self.assertEqual(row[0], now)
# Test with a non-existing user
report = {
'email': 'idonotexist@example.com'
}
job.update_user(report, now, self.conn)
cursor = self.conn.cursor()
cursor.execute("""
SELECT last_sending FROM emails WHERE email=%(email)s
""", report)
self.assertEqual(cursor.rowcount, 1)
row = cursor.fetchone()
self.assertEqual(row[0], now)
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_email_cannot_be_sent_twice(self, exacttarget_mock):
config_manager = self._setup_config_manager(
restrict_products=['NightlyTrain']
)
et_mock = exacttarget_mock.return_value
# Prepare failures
_failures = []
_email_sent = []
class SomeRandomError(Exception):
pass
def trigger_send(template, fields):
email = fields['EMAIL_ADDRESS_']
if email == 'c@example.org' and email not in _failures:
_failures.append(email)
raise SomeRandomError('This is an error. ')
else:
_email_sent.append(email)
et_mock.trigger_send = trigger_send
with config_manager.context() as config:
tab = crontabber.CronTabber(config)
tab.run_all()
information = self._load_structure()
assert information['automatic-emails']
assert information['automatic-emails']['last_error']
self.assertEqual(
information['automatic-emails']['last_error']['type'],
str(SomeRandomError)
)
# Verify that user's data was updated, but not all of it
self.assertEqual(_email_sent, ['a@example.org', 'b@example.org'])
cursor = self.conn.cursor()
emails_list = (
'a@example.org',
'b@example.org',
'c@example.org',
'd@example.org',
'e@example.org'
)
sql = """
SELECT email, last_sending
FROM emails
WHERE email IN %s
""" % (emails_list,)
cursor.execute(sql)
now = utc_now()
self.assertEqual(cursor.rowcount, 2)
for row in cursor.fetchall():
assert row[0] in ('a@example.org', 'b@example.org')
self.assertEqual(row[1].year, now.year)
self.assertEqual(row[1].month, now.month)
self.assertEqual(row[1].day, now.day)
# Run crontabber again and verify that all users are updated,
# and emails are not sent twice
state = tab.database['automatic-emails']
self._wind_clock(state, hours=1)
tab.database['automatic-emails'] = state
tab.run_all()
information = self._load_structure()
assert information['automatic-emails']
assert not information['automatic-emails']['last_error']
assert information['automatic-emails']['last_success']
# Verify that users were not sent an email twice
self.assertEqual(_email_sent, [
'a@example.org',
'b@example.org',
'c@example.org',
'd@example.org',
'e@example.org'
])
@mock.patch('socorro.external.exacttarget.exacttarget.ExactTarget')
def test_email_after_delay(self, exacttarget_mock):
"""Test that a user will receive an email if he or she sends us a new
crash report after the delay is passed (but not before). """
config_manager = self._setup_config_manager(
delay_between_emails=1,
restrict_products=['EarthRaccoon']
)
list_service_mock = exacttarget_mock.return_value.list.return_value
list_service_mock.get_subscriber.return_value = {
'token': 'me@my.name'
}
trigger_send_mock = exacttarget_mock.return_value.trigger_send
tomorrow = utc_now() + datetime.timedelta(days=1, hours=2)
twohourslater = utc_now() + datetime.timedelta(hours=2)
with config_manager.context() as config:
# 1. Send an email to the user and update emailing data
tab = crontabber.CronTabber(config)
tab.run_all()
information = self._load_structure()
assert information['automatic-emails']
assert not information['automatic-emails']['last_error']
assert information['automatic-emails']['last_success']
exacttarget_mock.return_value.trigger_send.assert_called_with(
'socorro_dev_test',
{
'EMAIL_ADDRESS_': 'me@my.name',
'EMAIL_FORMAT_': 'H',
'TOKEN': 'me@my.name'
}
)
self.assertEqual(trigger_send_mock.call_count, 1)
# 2. Test that before 'delay' is passed user doesn't receive
# another email
# Insert a new crash report with the same email address
cursor = self.conn.cursor()
cursor.execute("""
INSERT INTO reports
(uuid, email, product, version, release_channel, date_processed)
VALUES (
'50',
'me@my.name',
'EarthRaccoon',
'20.0',
'Release',
'%(onehourlater)s'
)
""" % {'onehourlater': utc_now() + datetime.timedelta(hours=1)})
self.conn.commit()
# Run crontabber with time pushed by two hours
with mock.patch('socorro.cron.crontabber.utc_now') as cronutc_mock:
with mock.patch('socorro.cron.base.utc_now') as baseutc_mock:
cronutc_mock.return_value = twohourslater
baseutc_mock.return_value = twohourslater
tab.run_all()
information = self._load_structure()
assert information['automatic-emails']
assert not information['automatic-emails']['last_error']
assert information['automatic-emails']['last_success']
# No new email was sent
self.assertEqual(trigger_send_mock.call_count, 1)
# 3. Verify that, after 'delay' is passed, a new email is sent
# to our user
# Insert a new crash report with the same email address
cursor = self.conn.cursor()
cursor.execute("""
INSERT INTO reports
(uuid, email, product, version, release_channel, date_processed)
VALUES (
'51',
'me@my.name',
'EarthRaccoon',
'20.0',
'Release',
'%(tomorrow)s'
)
""" % {'tomorrow': utc_now() + datetime.timedelta(days=1)})
self.conn.commit()
# Run crontabber with time pushed by a day
with mock.patch('socorro.cron.crontabber.utc_now') as cronutc_mock:
with mock.patch('socorro.cron.base.utc_now') as baseutc_mock:
cronutc_mock.return_value = tomorrow
baseutc_mock.return_value = tomorrow
tab.run_all()
information = self._load_structure()
assert information['automatic-emails']
assert not information['automatic-emails']['last_error']
assert information['automatic-emails']['last_success']
# A new email was sent
self.assertEqual(trigger_send_mock.call_count, 2)