/
test_notifications.py
334 lines (296 loc) · 9.24 KB
/
test_notifications.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
import json
import os
import sys
import tempfile
from multiprocessing.pool import ThreadPool
from unittest.mock import MagicMock
import cloudpickle
import pytest
import prefect
from prefect import Task, task
from prefect.engine.state import (
Cached,
Failed,
Finished,
Pending,
Retrying,
Running,
Scheduled,
Skipped,
State,
Success,
TriggerFailed,
)
from prefect.utilities.configuration import set_temporary_config
from prefect.utilities.notifications import (
callback_factory,
gmail_notifier,
slack_message_formatter,
slack_notifier,
)
def test_callback_factory_generates_pickleable_objs():
"""
This test does some heavy lifting to create two lambda functions,
and then passes them through callback_factory to generate a state-handler.
We then pickle the state handler to a temporary file, delete the functions,
and try to unpickle the file in a new Process, asserting that the result is what we
think it should be.
"""
def load_bytes(fname):
import cloudpickle
with open(fname, "rb") as f:
obj = cloudpickle.load(f)
return obj(1, 2, 3)
fn = lambda obj, state: None
check = lambda state: True
handler = callback_factory(fn, check)
sd, tmp_file = tempfile.mkstemp()
os.close(sd)
try:
with open(tmp_file, "wb") as bit_file:
cloudpickle.dump(handler, bit_file)
del fn
del check
pool = ThreadPool(processes=1)
result = pool.apply_async(load_bytes, (tmp_file,))
value = result.get()
assert value == 3
except Exception as exc:
raise exc
finally:
os.unlink(tmp_file)
@pytest.mark.parametrize(
"state",
[
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
],
)
def test_formatter_formats_states(state):
orig = slack_message_formatter(Task(), state())
assert json.loads(json.dumps(orig)) == orig
@pytest.mark.parametrize(
"state",
[
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
],
)
def test_formatter_formats_states_with_string_message(state):
orig = slack_message_formatter(Task(), state(message="I am informative"))
assert orig["attachments"][0]["fields"][0]["value"] == "I am informative"
assert json.loads(json.dumps(orig)) == orig
@pytest.mark.parametrize(
"state",
[
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
],
)
def test_formatter_formats_states_with_exception_message(state):
orig = slack_message_formatter(Task(), state(result=ZeroDivisionError("Nope")))
expected = "```ZeroDivisionError('Nope'"
expected += ")```" if sys.version_info >= (3, 7) else ",)```"
assert orig["attachments"][0]["fields"][0]["value"] == expected
assert json.loads(json.dumps(orig)) == orig
def test_every_state_gets_a_unique_color():
all_states = [
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
]
colors = set()
for state in all_states:
color = slack_message_formatter(Task(), state())["attachments"][0]["color"]
colors.add(color)
assert len(colors) == len(all_states)
def test_slack_notifier_returns_new_state_and_old_state_is_ignored(monkeypatch):
ok = MagicMock(ok=True)
monkeypatch.setattr(prefect.utilities.notifications.requests, "post", ok)
new_state = Failed(message="1", result=0)
with set_temporary_config({"cloud.use_local_secrets": True}):
with prefect.context(secrets=dict(SLACK_WEBHOOK_URL="")):
assert slack_notifier(Task(), "", new_state) is new_state
def test_slack_notifier_pulls_url_from_secret(monkeypatch):
post = MagicMock(ok=True)
monkeypatch.setattr("prefect.utilities.notifications.requests.post", post)
state = Failed(message="1", result=0)
with set_temporary_config({"cloud.use_local_secrets": True}):
with pytest.raises(ValueError, match="SLACK_WEBHOOK_URL"):
slack_notifier(Task(), "", state)
with prefect.context(secrets=dict(SLACK_WEBHOOK_URL="https://foo/bar")):
slack_notifier(Task(), "", state)
assert post.call_args[0][0] == "https://foo/bar"
with prefect.context(secrets=dict(TOP_SECRET='"42"')):
slack_notifier(Task(), "", state, webhook_secret="TOP_SECRET")
assert post.call_args[0][0] == "42"
def test_slack_notifier_ignores_ignore_states(monkeypatch):
all_states = [
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
]
ok = MagicMock(ok=True)
monkeypatch.setattr(prefect.utilities.notifications.requests, "post", ok)
for state in all_states:
s = state()
with set_temporary_config({"cloud.use_local_secrets": True}):
with prefect.context(secrets=dict(SLACK_WEBHOOK_URL="")):
returned = slack_notifier(Task(), "", s, ignore_states=[State])
assert returned is s
assert ok.called is False
@pytest.mark.parametrize(
"state",
[
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
],
)
def test_slack_notifier_is_curried_and_ignores_ignore_states(monkeypatch, state):
state = state()
ok = MagicMock(ok=True)
monkeypatch.setattr(prefect.utilities.notifications.requests, "post", ok)
handler = slack_notifier(ignore_states=[Finished])
with set_temporary_config({"cloud.use_local_secrets": True}):
with prefect.context(secrets=dict(SLACK_WEBHOOK_URL="")):
returned = handler(Task(), "", state)
assert returned is state
assert ok.called is not state.is_finished()
@pytest.mark.parametrize(
"state",
[
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
],
)
def test_slack_notifier_is_curried_and_uses_only_states(monkeypatch, state):
state = state()
ok = MagicMock(ok=True)
monkeypatch.setattr(prefect.utilities.notifications.requests, "post", ok)
handler = slack_notifier(only_states=[TriggerFailed])
with set_temporary_config({"cloud.use_local_secrets": True}):
with prefect.context(secrets=dict(SLACK_WEBHOOK_URL="")):
returned = handler(Task(), "", state)
assert returned is state
assert ok.called is isinstance(state, TriggerFailed)
def test_gmail_notifier_sends_simple_email(monkeypatch):
smtp = MagicMock()
sendmail = MagicMock()
smtp.SMTP_SSL.return_value.sendmail = sendmail
monkeypatch.setattr(prefect.utilities.notifications, "smtplib", smtp)
s = Failed("optional message...")
monkeypatch.setattr(prefect.config.cloud, "use_local_secrets", True)
with prefect.context(secrets=dict(EMAIL_USERNAME="alice", EMAIL_PASSWORD=1234)):
returned = gmail_notifier(Task(name="dud"), "", s)
assert returned is s
email_from, to, body = sendmail.call_args[0]
assert email_from == "notifications@prefect.io"
assert to == "alice"
assert "Failed" in body
assert "optional message" in body
assert s.color in body
@pytest.mark.parametrize(
"state",
[
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
],
)
def test_gmail_notifier_is_curried_and_uses_only_states(monkeypatch, state):
state = state()
smtp = MagicMock()
sendmail = MagicMock()
smtp.SMTP_SSL.return_value.sendmail = sendmail
monkeypatch.setattr(prefect.utilities.notifications, "smtplib", smtp)
with set_temporary_config({"cloud.use_local_secrets": True}):
with prefect.context(secrets=dict(EMAIL_USERNAME="", EMAIL_PASSWORD="")):
handler = gmail_notifier(only_states=[TriggerFailed])
returned = handler(Task(), "", state)
assert returned is state
assert sendmail.called is isinstance(state, TriggerFailed)
def test_gmail_notifier_ignores_ignore_states(monkeypatch):
all_states = [
Running,
Pending,
Finished,
Failed,
TriggerFailed,
Cached,
Scheduled,
Retrying,
Success,
Skipped,
]
smtp = MagicMock()
sendmail = MagicMock()
smtp.SMTP_SSL.return_value.sendmail = sendmail
monkeypatch.setattr(prefect.utilities.notifications, "smtplib", smtp)
for state in all_states:
s = state()
with set_temporary_config({"cloud.use_local_secrets": True}):
with prefect.context(secrets=dict(EMAIL_USERNAME="", EMAIL_PASSWORD="")):
returned = gmail_notifier(Task(), "", s, ignore_states=[State])
assert returned is s
assert sendmail.called is False