forked from spotify/luigi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnotifications_test.py
452 lines (356 loc) · 15.5 KB
/
notifications_test.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
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from helpers import unittest
import mock
import sys
import socket
from helpers import with_config
from luigi import notifications
from luigi.notifications import generate_email
from luigi.scheduler import Scheduler
from luigi.worker import Worker
from luigi import six
import luigi
class TestEmail(unittest.TestCase):
def testEmailNoPrefix(self):
self.assertEqual("subject", notifications._prefix('subject'))
@with_config({"email": {"prefix": "[prefix]"}})
def testEmailPrefix(self):
self.assertEqual("[prefix] subject", notifications._prefix('subject'))
class TestException(Exception):
pass
class TestTask(luigi.Task):
foo = luigi.Parameter()
bar = luigi.Parameter()
class FailSchedulingTask(TestTask):
def requires(self):
raise TestException('Oops!')
def run(self):
pass
def complete(self):
return False
class FailRunTask(TestTask):
def run(self):
raise TestException('Oops!')
def complete(self):
return False
class ExceptionFormatTest(unittest.TestCase):
def setUp(self):
self.sch = Scheduler()
def test_fail_run(self):
task = FailRunTask(foo='foo', bar='bar')
self._run_task(task)
def test_fail_run_html(self):
task = FailRunTask(foo='foo', bar='bar')
self._run_task_html(task)
def test_fail_schedule(self):
task = FailSchedulingTask(foo='foo', bar='bar')
self._run_task(task)
def test_fail_schedule_html(self):
task = FailSchedulingTask(foo='foo', bar='bar')
self._run_task_html(task)
@with_config({'email': {'receiver': '[email protected]',
'prefix': '[TEST] '}})
@mock.patch('luigi.notifications.send_error_email')
def _run_task(self, task, mock_send):
with Worker(scheduler=self.sch) as w:
w.add(task)
w.run()
self.assertEqual(mock_send.call_count, 1)
args, kwargs = mock_send.call_args
self._check_subject(args[0], task)
self._check_body(args[1], task, html=False)
@with_config({'email': {'receiver': '[email protected]',
'prefix': '[TEST] ',
'format': 'html'}})
@mock.patch('luigi.notifications.send_error_email')
def _run_task_html(self, task, mock_send):
with Worker(scheduler=self.sch) as w:
w.add(task)
w.run()
self.assertEqual(mock_send.call_count, 1)
args, kwargs = mock_send.call_args
self._check_subject(args[0], task)
self._check_body(args[1], task, html=True)
def _check_subject(self, subject, task):
self.assertIn(str(task), subject)
def _check_body(self, body, task, html=False):
if html:
self.assertIn('<th>name</th><td>{}</td>'.format(task.task_family), body)
self.assertIn('<div class="highlight"', body)
self.assertIn('Oops!', body)
for param, value in task.param_kwargs.items():
self.assertIn('<th>{}</th><td>{}</td>'.format(param, value), body)
else:
self.assertIn('Name: {}\n'.format(task.task_family), body)
self.assertIn('Parameters:\n', body)
self.assertIn('TestException: Oops!', body)
for param, value in task.param_kwargs.items():
self.assertIn('{}: {}\n'.format(param, value), body)
@with_config({"email": {"receiver": "[email protected]"}})
def testEmailRecipients(self):
six.assertCountEqual(self, notifications._email_recipients(), ["[email protected]"])
six.assertCountEqual(self, notifications._email_recipients("[email protected]"), ["[email protected]", "[email protected]"])
six.assertCountEqual(self, notifications._email_recipients(["[email protected]", "[email protected]"]),
@with_config({"email": {}}, replace_sections=True)
def testEmailRecipientsNoConfig(self):
six.assertCountEqual(self, notifications._email_recipients(), [])
six.assertCountEqual(self, notifications._email_recipients("[email protected]"), ["[email protected]"])
six.assertCountEqual(self, notifications._email_recipients(["[email protected]", "[email protected]"]),
["[email protected]", "[email protected]"])
def test_generate_unicode_email(self):
generate_email(
sender='[email protected]',
subject=six.u('sübjéct'),
message=six.u("你好"),
recipients=['[email protected]'],
image_png=None,
)
class NotificationFixture(object):
"""
Defines API and message fixture.
config, sender, subject, message, recipients, image_png
"""
sender = 'luigi@unittest'
subject = 'Oops!'
message = """A multiline
message."""
recipients = ['[email protected]', '[email protected]']
image_png = None
notification_args = [sender, subject, message, recipients, image_png]
mocked_email_msg = '''Content-Type: multipart/related; boundary="===============0998157881=="
MIME-Version: 1.0
Subject: Oops!
From: luigi@unittest
--===============0998157881==
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Type: text/plain; charset="utf-8"
A multiline
message.
--===============0998157881==--'''
class TestSMTPEmail(unittest.TestCase, NotificationFixture):
"""
Tests sending SMTP email.
"""
def setUp(self):
sys.modules['smtplib'] = mock.MagicMock()
import smtplib # noqa: F401
def tearDown(self):
del sys.modules['smtplib']
@with_config({"smtp": {"ssl": "False",
"host": "my.smtp.local",
"port": "999",
"local_hostname": "ptms",
"timeout": "1200",
"username": "Robin",
"password": "dooH",
"no_tls": "False"}})
def test_sends_smtp_email(self):
"""
Call notifications.send_email_smtp with fixture parameters with smtp_without_tls set to False
and check that sendmail is properly called.
"""
smtp_kws = {"host": "my.smtp.local",
"port": 999,
"local_hostname": "ptms",
"timeout": 1200}
with mock.patch('smtplib.SMTP') as SMTP:
with mock.patch('luigi.notifications.generate_email') as generate_email:
generate_email.return_value\
.as_string.return_value = self.mocked_email_msg
notifications.send_email_smtp(*self.notification_args)
SMTP.assert_called_once_with(**smtp_kws)
SMTP.return_value.login.assert_called_once_with("Robin", "dooH")
SMTP.return_value.starttls.assert_called_once_with()
SMTP.return_value.sendmail\
.assert_called_once_with(self.sender, self.recipients,
self.mocked_email_msg)
@with_config({"smtp": {"ssl": "False",
"host": "my.smtp.local",
"port": "999",
"local_hostname": "ptms",
"timeout": "1200",
"username": "Robin",
"password": "dooH",
"no_tls": "True"}})
def test_sends_smtp_email_without_tls(self):
"""
Call notifications.send_email_smtp with fixture parameters with no_tls set to True
and check that sendmail is properly called without also calling
starttls.
"""
smtp_kws = {"host": "my.smtp.local",
"port": 999,
"local_hostname": "ptms",
"timeout": 1200}
with mock.patch('smtplib.SMTP') as SMTP:
with mock.patch('luigi.notifications.generate_email') as generate_email:
generate_email.return_value \
.as_string.return_value = self.mocked_email_msg
notifications.send_email_smtp(*self.notification_args)
SMTP.assert_called_once_with(**smtp_kws)
self.assertEqual(SMTP.return_value.starttls.called, False)
SMTP.return_value.login.assert_called_once_with("Robin", "dooH")
SMTP.return_value.sendmail \
.assert_called_once_with(self.sender, self.recipients,
self.mocked_email_msg)
@with_config({"smtp": {"ssl": "False",
"host": "my.smtp.local",
"port": "999",
"local_hostname": "ptms",
"timeout": "1200",
"username": "Robin",
"password": "dooH",
"no_tls": "True"}})
def test_sends_smtp_email_exceptions(self):
"""
Call notifications.send_email_smtp when it cannot connect to smtp server (socket.error)
starttls.
"""
smtp_kws = {"host": "my.smtp.local",
"port": 999,
"local_hostname": "ptms",
"timeout": 1200}
with mock.patch('smtplib.SMTP') as SMTP:
with mock.patch('luigi.notifications.generate_email') as generate_email:
SMTP.side_effect = socket.error()
generate_email.return_value \
.as_string.return_value = self.mocked_email_msg
try:
notifications.send_email_smtp(*self.notification_args)
except socket.error:
self.fail("send_email_smtp() raised expection unexpectedly")
SMTP.assert_called_once_with(**smtp_kws)
self.assertEqual(notifications.generate_email.called, False)
self.assertEqual(SMTP.sendemail.called, False)
class TestSendgridEmail(unittest.TestCase, NotificationFixture):
"""
Tests sending Sendgrid email.
"""
def setUp(self):
sys.modules['sendgrid'] = mock.MagicMock()
import sendgrid # noqa: F401
def tearDown(self):
del sys.modules['sendgrid']
@with_config({"sendgrid": {"username": "Nikola",
"password": "jahuS"}})
def test_sends_sendgrid_email(self):
"""
Call notifications.send_email_sendgrid with fixture parameters
and check that SendGridClient is properly called.
"""
with mock.patch('sendgrid.SendGridClient') as SendgridClient:
notifications.send_email_sendgrid(*self.notification_args)
SendgridClient.assert_called_once_with("Nikola", "jahuS", raise_errors=True)
self.assertTrue(SendgridClient.return_value.send.called)
class TestSESEmail(unittest.TestCase, NotificationFixture):
"""
Tests sending email through AWS SES.
"""
def setUp(self):
sys.modules['boto3'] = mock.MagicMock()
import boto3 # noqa: F401
def tearDown(self):
del sys.modules['boto3']
@with_config({})
def test_sends_ses_email(self):
"""
Call notifications.send_email_ses with fixture parameters
and check that boto is properly called.
"""
with mock.patch('boto3.client') as boto_client:
with mock.patch('luigi.notifications.generate_email') as generate_email:
generate_email.return_value\
.as_string.return_value = self.mocked_email_msg
notifications.send_email_ses(*self.notification_args)
SES = boto_client.return_value
SES.send_raw_email.assert_called_once_with(
Source=self.sender,
Destinations=self.recipients,
RawMessage={'Data': self.mocked_email_msg})
class TestSNSNotification(unittest.TestCase, NotificationFixture):
"""
Tests sending email through AWS SNS.
"""
def setUp(self):
sys.modules['boto3'] = mock.MagicMock()
import boto3 # noqa: F401
def tearDown(self):
del sys.modules['boto3']
@with_config({})
def test_sends_sns_email(self):
"""
Call notifications.send_email_sns with fixture parameters
and check that boto3 is properly called.
"""
with mock.patch('boto3.resource') as res:
notifications.send_email_sns(*self.notification_args)
SNS = res.return_value
SNS.Topic.assert_called_once_with(self.recipients[0])
SNS.Topic.return_value.publish.assert_called_once_with(
Subject=self.subject, Message=self.message)
@with_config({})
def test_sns_subject_is_shortened(self):
"""
Call notifications.send_email_sns with too long Subject (more than 100 chars)
and check that it is cut to lenght of 100 chars.
"""
long_subject = 'Luigi: SanityCheck(regexPattern=aligned-source\\|data-not-older\\|source-chunks-compl,'\
'mailFailure=False, mongodb=mongodb://localhost/stats) FAILED'
with mock.patch('boto3.resource') as res:
notifications.send_email_sns(self.sender, long_subject, self.message,
self.recipients, self.image_png)
SNS = res.return_value
SNS.Topic.assert_called_once_with(self.recipients[0])
called_subj = SNS.Topic.return_value.publish.call_args[1]['Subject']
self.assertTrue(len(called_subj) <= 100,
"Subject can be max 100 chars long! Found {}.".format(len(called_subj)))
class TestNotificationDispatcher(unittest.TestCase, NotificationFixture):
"""
Test dispatching of notifications on configuration values.
"""
def check_dispatcher(self, target):
"""
Call notifications.send_email and test that the proper
function was called.
"""
expected_args = self.notification_args
with mock.patch('luigi.notifications.{}'.format(target)) as sender:
notifications.send_email(self.subject, self.message, self.sender,
self.recipients, image_png=self.image_png)
self.assertTrue(sender.called)
call_args = sender.call_args[0]
self.assertEqual(tuple(expected_args), call_args)
@with_config({'email': {'force_send': 'True',
'method': 'smtp'}})
def test_smtp(self):
return self.check_dispatcher('send_email_smtp')
@with_config({'email': {'force_send': 'True',
'method': 'ses'}})
def test_ses(self):
return self.check_dispatcher('send_email_ses')
@with_config({'email': {'force_send': 'True',
'method': 'sendgrid'}})
def test_sendgrid(self):
return self.check_dispatcher('send_email_sendgrid')
@with_config({'email': {'force_send': 'True',
'method': 'sns'}})
def test_sns(self):
return self.check_dispatcher('send_email_sns')