Debian Codegraph @

tests/test_plugin_sparkpost.py

raw symbols SCIP
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from json import dumps
29
30 # Disable logging for a cleaner testing output
31 import logging
32 import os
33 from unittest import mock
34
35 from helpers import AppriseURLTester
36 import pytest
37 import requests
38
39 from apprise import Apprise, AppriseAttachment, NotifyType
40 from apprise.plugins.sparkpost import NotifySparkPost
41
42 logging.disable(logging.CRITICAL)
43
44 # Attachment Directory
45 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
46
47 # Our Testing URLs
48 apprise_url_tests = (
49 (
50 "sparkpost://",
51 {
52 "instance": TypeError,
53 },
54 ),
55 (
56 "sparkpost://:@/",
57 {
58 "instance": TypeError,
59 },
60 ),
61 # No Token specified
62 (
63 "sparkpost://[email protected]",
64 {
65 "instance": TypeError,
66 },
67 ),
68 # Token is valid, but no user name specified
69 (
70 "sparkpost://localhost.localdomain/{}".format("a" * 32),
71 {
72 "instance": TypeError,
73 },
74 ),
75 # Invalid from email address
76 (
77 'sparkpost://"@localhost.localdomain/{}'.format("b" * 32),
78 {
79 "instance": TypeError,
80 },
81 ),
82 # No To email address, but everything else is valid
83 (
84 "sparkpost://[email protected]/{}".format("c" * 32),
85 {
86 "instance": NotifySparkPost,
87 "requests_response_text": {
88 "results": {
89 "total_rejected_recipients": 0,
90 "total_accepted_recipients": 1,
91 "id": "11668787484950529",
92 }
93 },
94 },
95 ),
96 (
97 "sparkpost://[email protected]/{}?format=markdown".format(
98 "d" * 32
99 ),
100 {
101 "instance": NotifySparkPost,
102 "requests_response_text": {
103 "results": {
104 "total_rejected_recipients": 0,
105 "total_accepted_recipients": 1,
106 "id": "11668787484950529",
107 }
108 },
109 },
110 ),
111 (
112 "sparkpost://[email protected]/{}?format=html".format(
113 "d" * 32
114 ),
115 {
116 "instance": NotifySparkPost,
117 "requests_response_text": {
118 "results": {
119 "total_rejected_recipients": 0,
120 "total_accepted_recipients": 1,
121 "id": "11668787484950529",
122 }
123 },
124 "force_debug": True,
125 },
126 ),
127 (
128 "sparkpost://[email protected]/{}?format=text".format(
129 "d" * 32
130 ),
131 {
132 "instance": NotifySparkPost,
133 "requests_response_text": {
134 "results": {
135 "total_rejected_recipients": 0,
136 "total_accepted_recipients": 1,
137 "id": "11668787484950529",
138 }
139 },
140 },
141 ),
142 # valid url with region specified (case insensitve)
143 (
144 "sparkpost://[email protected]/{}?region=uS".format("d" * 32),
145 {
146 "instance": NotifySparkPost,
147 "requests_response_text": {
148 "results": {
149 "total_rejected_recipients": 0,
150 "total_accepted_recipients": 1,
151 "id": "11668787484950529",
152 }
153 },
154 },
155 ),
156 # valid url with region specified (case insensitve)
157 (
158 "sparkpost://[email protected]/{}?region=EU".format("e" * 32),
159 {
160 "instance": NotifySparkPost,
161 "requests_response_text": {
162 "results": {
163 "total_rejected_recipients": 0,
164 "total_accepted_recipients": 1,
165 "id": "11668787484950529",
166 }
167 },
168 },
169 ),
170 # headers
171 (
172 "sparkpost://[email protected]/{}"
173 "?+X-Customer-Campaign-ID=Apprise".format("f" * 32),
174 {
175 "instance": NotifySparkPost,
176 "requests_response_text": {
177 "results": {
178 "total_rejected_recipients": 0,
179 "total_accepted_recipients": 1,
180 "id": "11668787484950529",
181 }
182 },
183 },
184 ),
185 # template tokens
186 (
187 "sparkpost://[email protected]/{}"
188 "?:name=Chris&:status=admin".format("g" * 32),
189 {
190 "instance": NotifySparkPost,
191 "requests_response_text": {
192 "results": {
193 "total_rejected_recipients": 0,
194 "total_accepted_recipients": 1,
195 "id": "11668787484950529",
196 }
197 },
198 },
199 ),
200 # bcc and cc
201 (
202 "sparkpost://[email protected]/{}"
203 "[email protected]&[email protected]".format("h" * 32),
204 {
205 "instance": NotifySparkPost,
206 "requests_response_text": {
207 "results": {
208 "total_rejected_recipients": 0,
209 "total_accepted_recipients": 1,
210 "id": "11668787484950529",
211 }
212 },
213 },
214 ),
215 # invalid url with region specified (case insensitve)
216 (
217 "sparkpost://[email protected]/{}?region=invalid".format(
218 "a" * 32
219 ),
220 {
221 "instance": TypeError,
222 },
223 ),
224 # One 'To' Email address
225 (
226 "sparkpost://[email protected]/{}/[email protected]".format(
227 "a" * 32
228 ),
229 {
230 "instance": NotifySparkPost,
231 "requests_response_text": {
232 "results": {
233 "total_rejected_recipients": 0,
234 "total_accepted_recipients": 1,
235 "id": "11668787484950529",
236 }
237 },
238 },
239 ),
240 # Invalid 'To' Email address
241 (
242 "sparkpost://[email protected]/{}/invalid".format("i" * 32),
243 {
244 "instance": NotifySparkPost,
245 # Expected notify() response
246 "notify_response": False,
247 },
248 ),
249 # Multiple 'To', 'Cc', and 'Bcc' addresses (with invalid ones)
250 (
251 "sparkpost://[email protected]/{}/{}?bcc={}&cc={}".format(
252 "j" * 32,
253 "/".join(
254 ("[email protected]", "invalid", "User2:[email protected]")
255 ),
256 ",".join(("[email protected]", "i@v", "User1:[email protected]")),
257 ",".join(("[email protected]", "g@r@b", "Da:[email protected]")),
258 ),
259 {
260 "instance": NotifySparkPost,
261 "requests_response_text": {
262 "results": {
263 "total_rejected_recipients": 0,
264 "total_accepted_recipients": 1,
265 "id": "11668787484950529",
266 }
267 },
268 },
269 ),
270 (
271 "sparkpost://[email protected]/{}[email protected]".format(
272 "k" * 32
273 ),
274 {
275 "instance": NotifySparkPost,
276 "requests_response_text": {
277 "results": {
278 "total_rejected_recipients": 0,
279 "total_accepted_recipients": 1,
280 "id": "11668787484950529",
281 }
282 },
283 },
284 ),
285 # One To Email address, a from name specified too
286 (
287 "sparkpost://[email protected]/{}/"
288 '[email protected]?name="Frodo"'.format("l" * 32),
289 {
290 "instance": NotifySparkPost,
291 "requests_response_text": {
292 "results": {
293 "total_rejected_recipients": 0,
294 "total_accepted_recipients": 1,
295 "id": "11668787484950529",
296 }
297 },
298 },
299 ),
300 # Test invalid JSON response
301 (
302 "sparkpost://[email protected]/{}".format("m" * 32),
303 {
304 "instance": NotifySparkPost,
305 "requests_response_text": "{",
306 },
307 ),
308 (
309 "sparkpost://[email protected]/{}".format("n" * 32),
310 {
311 "instance": NotifySparkPost,
312 # force a failure
313 "response": False,
314 "requests_response_code": requests.codes.internal_server_error,
315 },
316 ),
317 (
318 "sparkpost://[email protected]/{}".format("o" * 32),
319 {
320 "instance": NotifySparkPost,
321 # throw a bizarre code forcing us to fail to look it up
322 "response": False,
323 "requests_response_code": 999,
324 },
325 ),
326 (
327 "sparkpost://[email protected]/{}".format("p" * 32),
328 {
329 "instance": NotifySparkPost,
330 # Throws a series of i/o exceptions with this flag
331 # is set and tests that we gracefully handle them
332 "test_requests_exceptions": True,
333 },
334 ),
335 )
336
337
338 def test_plugin_sparkpost_urls():
339 """NotifySparkPost() Apprise URLs."""
340
341 # Run our general tests
342 AppriseURLTester(tests=apprise_url_tests).run_all()
343
344
345 @mock.patch("requests.post")
346 def test_plugin_sparkpost_throttling(mock_post):
347 """NotifySparkPost() Throttling."""
348
349 NotifySparkPost.sparkpost_retry_wait_sec = 0.1
350 NotifySparkPost.sparkpost_retry_attempts = 3
351
352 # API Key
353 apikey = "abc123"
354 user = "user"
355 host = "example.com"
356 targets = f"{user}@{host}"
357
358 # Exception should be thrown about the fact no user was specified
359 with pytest.raises(TypeError):
360 NotifySparkPost(apikey=apikey, targets=targets, host=host)
361
362 # Exception should be thrown about the fact no private key was specified
363 with pytest.raises(TypeError):
364 NotifySparkPost(apikey=None, targets=targets, user=user, host=host)
365
366 okay_response = requests.Request()
367 okay_response.status_code = requests.codes.ok
368 okay_response.content = dumps(
369 {
370 "results": {
371 "total_rejected_recipients": 0,
372 "total_accepted_recipients": 1,
373 "id": "11668787484950529",
374 }
375 }
376 )
377
378 retry_response = requests.Request()
379 retry_response.status_code = requests.codes.too_many_requests
380 retry_response.content = dumps(
381 {
382 "errors": [
383 {
384 "description": (
385 "Unconfigured or unverified sending domain."
386 ),
387 "code": "7001",
388 "message": "Invalid domain",
389 }
390 ]
391 }
392 )
393
394 # Prepare Mock (force 2 retry responses and then one okay)
395 mock_post.side_effect = (retry_response, retry_response, okay_response)
396
397 obj = Apprise.instantiate(
398 f"sparkpost://[email protected]/{apikey}"
399 )
400 assert isinstance(obj, NotifySparkPost)
401
402 # We'll successfully perform the notification as we're within
403 # our retry limit
404 assert obj.notify("test") is True
405
406 mock_post.reset_mock()
407 mock_post.side_effect = (retry_response, retry_response, retry_response)
408
409 # Now we are less than our expected limit check so we will fail
410 assert obj.notify("test") is False
411
412
413 @mock.patch("requests.post")
414 def test_plugin_sparkpost_attachments(mock_post):
415 """NotifySparkPost() Attachments."""
416 NotifySparkPost.sparkpost_retry_wait_sec = 0.1
417 NotifySparkPost.sparkpost_retry_attempts = 3
418
419 okay_response = requests.Request()
420 okay_response.status_code = requests.codes.ok
421 okay_response.content = dumps(
422 {
423 "results": {
424 "total_rejected_recipients": 0,
425 "total_accepted_recipients": 1,
426 "id": "11668787484950529",
427 }
428 }
429 )
430
431 # Assign our mock object our return value
432 mock_post.return_value = okay_response
433
434 # API Key
435 apikey = "abc123"
436
437 obj = Apprise.instantiate(
438 f"sparkpost://[email protected]/{apikey}"
439 )
440 assert isinstance(obj, NotifySparkPost)
441
442 # Test Valid Attachment
443 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
444 attach = AppriseAttachment(path)
445 assert (
446 obj.notify(
447 body="body",
448 title="title",
449 notify_type=NotifyType.INFO,
450 attach=attach,
451 )
452 is True
453 )
454
455 # Test invalid attachment
456 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
457 assert (
458 obj.notify(
459 body="body",
460 title="title",
461 notify_type=NotifyType.INFO,
462 attach=path,
463 )
464 is False
465 )
466
467 with mock.patch("base64.b64encode", side_effect=OSError()):
468 # We can't send the message if we fail to parse the data
469 assert (
470 obj.notify(
471 body="body",
472 title="title",
473 notify_type=NotifyType.INFO,
474 attach=attach,
475 )
476 is False
477 )
478
479 obj = Apprise.instantiate(
480 f"sparkpost://[email protected]/{apikey}/"
481 "[email protected]/[email protected]?batch=yes"
482 )
483 assert isinstance(obj, NotifySparkPost)
484
485 # As a batch mode, both emails can be lumped into 1
486 assert len(obj) == 1
487
488 # Force our batch to break into separate messages
489 obj.default_batch_size = 1
490
491 # We'll send 2 messages no
492 assert len(obj) == 2
493 mock_post.reset_mock()
494
495 assert (
496 obj.notify(
497 body="body",
498 title="title",
499 notify_type=NotifyType.INFO,
500 attach=attach,
501 )
502 is True
503 )
504 assert mock_post.call_count == 2
505
506 # single batch
507 mock_post.reset_mock()
508 # We'll send 1 message
509 obj.default_batch_size = 2
510
511 assert (
512 obj.notify(
513 body="body",
514 title="title",
515 notify_type=NotifyType.INFO,
516 attach=attach,
517 )
518 is True
519 )
520 assert mock_post.call_count == 1
521
522
523 def test_plugin_sparkpost_cc_bcc_invalid_branch():
524 """NotifySparkPost() CC/BCC validation: invalid entries are dropped."""
525
526 # Build a NotifySparkPost with:
527 # cc = one valid address + one that parse_emails passes through but
528 # is_email rejects (hits the FALSE branch in the CC loop).
529 # A list must be used -- parse_emails filters invalid tokens out
530 # of comma-separated strings before is_email is ever called.
531 # bcc = same, for the FALSE branch in the BCC loop
532 obj = NotifySparkPost(
533 apikey="abc123",
534 targets=["[email protected]"],
535 cc=["[email protected]", "notanemail"],
536 bcc=["[email protected]", "alsonotanemail"],
537 user="user",
538 host="example.com",
539 )
540
541 # Valid CC entry was added; invalid one was silently dropped
542 assert "[email protected]" in obj.cc
543 assert len(obj.cc) == 1
544
545 # Valid BCC entry was added; invalid one was silently dropped
546 assert "[email protected]" in obj.bcc
547 assert len(obj.bcc) == 1