Debian Codegraph @

tests/test_plugin_mailgun.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 # Disable logging for a cleaner testing output
29 import logging
30 import os
31 from unittest import mock
32
33 from helpers import AppriseURLTester
34 import requests
35
36 from apprise import Apprise, AppriseAttachment, NotifyType
37 from apprise.plugins.mailgun import NotifyMailgun
38
39 logging.disable(logging.CRITICAL)
40
41 # Attachment Directory
42 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
43
44 # Our Testing URLs
45 apprise_url_tests = (
46 (
47 "mailgun://",
48 {
49 "instance": TypeError,
50 },
51 ),
52 (
53 "mailgun://:@/",
54 {
55 "instance": TypeError,
56 },
57 ),
58 # No Token specified
59 (
60 "mailgun://[email protected]",
61 {
62 "instance": TypeError,
63 },
64 ),
65 # Token is valid, but no user name specified
66 (
67 "mailgun://localhost.localdomain/{}-{}-{}".format(
68 "a" * 32, "b" * 8, "c" * 8
69 ),
70 {
71 "instance": TypeError,
72 },
73 ),
74 # Invalid from email address
75 (
76 'mailgun://"@localhost.localdomain/{}-{}-{}'.format(
77 "a" * 32, "b" * 8, "c" * 8
78 ),
79 {
80 "instance": TypeError,
81 },
82 ),
83 # No To email address, but everything else is valid
84 (
85 "mailgun://[email protected]/{}-{}-{}".format(
86 "a" * 32, "b" * 8, "c" * 8
87 ),
88 {
89 "instance": NotifyMailgun,
90 },
91 ),
92 (
93 "mailgun://[email protected]/{}-{}-{}?format=markdown".format(
94 "a" * 32, "b" * 8, "c" * 8
95 ),
96 {
97 "instance": NotifyMailgun,
98 },
99 ),
100 (
101 "mailgun://[email protected]/{}-{}-{}?format=html".format(
102 "a" * 32, "b" * 8, "c" * 8
103 ),
104 {
105 "instance": NotifyMailgun,
106 },
107 ),
108 (
109 "mailgun://[email protected]/{}-{}-{}?format=text".format(
110 "a" * 32, "b" * 8, "c" * 8
111 ),
112 {
113 "instance": NotifyMailgun,
114 },
115 ),
116 # valid url with region specified (case insensitve)
117 (
118 "mailgun://[email protected]/{}-{}-{}?region=uS".format(
119 "a" * 32, "b" * 8, "c" * 8
120 ),
121 {
122 "instance": NotifyMailgun,
123 },
124 ),
125 # valid url with region specified (case insensitve)
126 (
127 "mailgun://[email protected]/{}-{}-{}?region=EU".format(
128 "a" * 32, "b" * 8, "c" * 8
129 ),
130 {
131 "instance": NotifyMailgun,
132 },
133 ),
134 # invalid url with region specified (case insensitve)
135 (
136 "mailgun://[email protected]/{}-{}-{}?region=invalid".format(
137 "a" * 32, "b" * 8, "c" * 8
138 ),
139 {
140 "instance": TypeError,
141 },
142 ),
143 # Use of both 'name' and 'from' together; these are synonymous
144 (
145 "mailgun://[email protected]/{}-{}-{}?"
146 "[email protected]&name=Jason<[email protected]>".format(
147 "a" * 32, "b" * 8, "c" * 8
148 ),
149 {"instance": NotifyMailgun},
150 ),
151 # headers
152 (
153 "mailgun://[email protected]/{}-{}-{}"
154 "?+X-Customer-Campaign-ID=Apprise".format("a" * 32, "b" * 8, "c" * 8),
155 {
156 "instance": NotifyMailgun,
157 },
158 ),
159 # template tokens
160 (
161 "mailgun://[email protected]/{}-{}-{}"
162 "?:name=Chris&:status=admin".format("a" * 32, "b" * 8, "c" * 8),
163 {
164 "instance": NotifyMailgun,
165 },
166 ),
167 # We can use the `from=` directive as well:
168 (
169 "mailgun://[email protected]/{}-{}-{}"
170 "?:from=Chris&:status=admin".format("a" * 32, "b" * 8, "c" * 8),
171 {
172 "instance": NotifyMailgun,
173 },
174 ),
175 # bcc and cc
176 (
177 "mailgun://[email protected]/{}-{}-{}"
178 "[email protected]&[email protected]".format(
179 "a" * 32, "b" * 8, "c" * 8
180 ),
181 {
182 "instance": NotifyMailgun,
183 },
184 ),
185 # One To Email address
186 (
187 "mailgun://[email protected]/{}-{}-{}/[email protected]".format(
188 "a" * 32, "b" * 8, "c" * 8
189 ),
190 {
191 "instance": NotifyMailgun,
192 },
193 ),
194 (
195 "mailgun://[email protected]/"
196 "{}-{}-{}[email protected]".format("a" * 32, "b" * 8, "c" * 8),
197 {"instance": NotifyMailgun},
198 ),
199 # One To Email address, a from name specified too
200 (
201 "mailgun://[email protected]/{}-{}-{}/"
202 '[email protected]?name="Frodo"'.format("a" * 32, "b" * 8, "c" * 8),
203 {"instance": NotifyMailgun},
204 ),
205 # Invalid 'To' Email address
206 (
207 "mailgun://[email protected]/{}-{}-{}/invalid".format(
208 "a" * 32, "b" * 8, "c" * 8
209 ),
210 {
211 "instance": NotifyMailgun,
212 # Expected notify() response
213 "notify_response": False,
214 },
215 ),
216 # Multiple 'To', 'Cc', and 'Bcc' addresses (with invalid ones)
217 (
218 "mailgun://[email protected]/{}-{}-{}/{}?bcc={}&cc={}".format(
219 "a" * 32,
220 "b" * 8,
221 "c" * 8,
222 "/".join(
223 ("[email protected]", "invalid", "User2:[email protected]")
224 ),
225 ",".join(("[email protected]", "i@v", "User1:[email protected]")),
226 ",".join(("[email protected]", "g@r@b", "Da:[email protected]")),
227 ),
228 {
229 "instance": NotifyMailgun,
230 },
231 ),
232 (
233 "mailgun://[email protected]/{}-{}-{}".format(
234 "a" * 32, "b" * 8, "c" * 8
235 ),
236 {
237 "instance": NotifyMailgun,
238 # force a failure
239 "response": False,
240 "requests_response_code": requests.codes.internal_server_error,
241 },
242 ),
243 (
244 "mailgun://[email protected]/{}-{}-{}".format(
245 "a" * 32, "b" * 8, "c" * 8
246 ),
247 {
248 "instance": NotifyMailgun,
249 # throw a bizarre code forcing us to fail to look it up
250 "response": False,
251 "requests_response_code": 999,
252 },
253 ),
254 (
255 "mailgun://[email protected]/{}-{}-{}".format(
256 "a" * 32, "b" * 8, "c" * 8
257 ),
258 {
259 "instance": NotifyMailgun,
260 # Throws a series of i/o exceptions with this flag
261 # is set and tests that we gracefully handle them
262 "test_requests_exceptions": True,
263 },
264 ),
265 )
266
267
268 def test_plugin_mailgun_urls():
269 """NotifyMailgun() Apprise URLs."""
270
271 # Run our general tests
272 AppriseURLTester(tests=apprise_url_tests).run_all()
273
274
275 @mock.patch("requests.post")
276 def test_plugin_mailgun_attachments(mock_post):
277 """NotifyMailgun() Attachments."""
278
279 okay_response = requests.Request()
280 okay_response.status_code = requests.codes.ok
281 okay_response.content = ""
282
283 # Assign our mock object our return value
284 mock_post.return_value = okay_response
285
286 # API Key
287 apikey = "abc123"
288
289 obj = Apprise.instantiate(f"mailgun://[email protected]/{apikey}")
290 assert isinstance(obj, NotifyMailgun)
291
292 # Test Valid Attachment
293 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
294 attach = AppriseAttachment(path)
295 assert (
296 obj.notify(
297 body="body",
298 title="title",
299 notify_type=NotifyType.INFO,
300 attach=attach,
301 )
302 is True
303 )
304
305 # Test invalid attachment
306 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
307 assert (
308 obj.notify(
309 body="body",
310 title="title",
311 notify_type=NotifyType.INFO,
312 attach=path,
313 )
314 is False
315 )
316
317 mock_post.return_value = None
318 mock_post.side_effect = OSError()
319 # We can't send the message if we can't read the attachment
320 assert (
321 obj.notify(
322 body="body",
323 title="title",
324 notify_type=NotifyType.INFO,
325 attach=attach,
326 )
327 is False
328 )
329
330 # Test Valid Attachment (load 3)
331 path = (
332 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
333 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
334 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
335 )
336 attach = AppriseAttachment(path)
337
338 # Return our good configuration
339 mock_post.side_effect = None
340 mock_post.return_value = okay_response
341 with mock.patch("builtins.open", side_effect=OSError()):
342 # We can't send the message we can't open the attachment for reading
343 assert (
344 obj.notify(
345 body="body",
346 title="title",
347 notify_type=NotifyType.INFO,
348 attach=attach,
349 )
350 is False
351 )
352
353 # Do it again, but fail on the third file
354 with mock.patch(
355 "builtins.open", side_effect=(mock.Mock(), mock.Mock(), OSError())
356 ):
357 assert (
358 obj.notify(
359 body="body",
360 title="title",
361 notify_type=NotifyType.INFO,
362 attach=attach,
363 )
364 is False
365 )
366
367 with mock.patch("builtins.open") as mock_open:
368 mock_fp = mock.Mock()
369 mock_fp.seek.side_effect = OSError()
370 mock_open.return_value = mock_fp
371
372 # We can't send the message we can't seek through it
373 assert (
374 obj.notify(
375 body="body",
376 title="title",
377 notify_type=NotifyType.INFO,
378 attach=attach,
379 )
380 is False
381 )
382
383 mock_post.reset_mock()
384 # Fail on the third file; this tests the for-loop inside the seek()
385 # section of the code that calls close() on previously opened files
386 mock_fp.seek.side_effect = (None, None, OSError())
387 mock_open.return_value = mock_fp
388 # We can't send the message we can't seek through it
389 assert (
390 obj.notify(
391 body="body",
392 title="title",
393 notify_type=NotifyType.INFO,
394 attach=attach,
395 )
396 is False
397 )
398
399 # test the handling of our batch modes
400 obj = Apprise.instantiate(
401 f"mailgun://[email protected]/{apikey}/"
402 "[email protected]/[email protected]?batch=yes"
403 )
404 assert isinstance(obj, NotifyMailgun)
405
406 # objects will be combined into a single post in batch mode
407 assert len(obj) == 1
408
409 # Force our batch to break into separate messages
410 obj.default_batch_size = 1
411
412 # We'll send 2 messages now
413 assert len(obj) == 2
414
415 mock_post.reset_mock()
416
417 assert (
418 obj.notify(
419 body="body",
420 title="title",
421 notify_type=NotifyType.INFO,
422 attach=attach,
423 )
424 is True
425 )
426 assert mock_post.call_count == 2
427
428 # single batch
429 mock_post.reset_mock()
430 # We'll send 1 message
431 obj.default_batch_size = 2
432
433 assert (
434 obj.notify(
435 body="body",
436 title="title",
437 notify_type=NotifyType.INFO,
438 attach=attach,
439 )
440 is True
441 )
442 assert mock_post.call_count == 1
443
444
445 @mock.patch("requests.post")
446 def test_plugin_mailgun_header_check(mock_post):
447 """NotifyMailgun() Test Header Prep."""
448
449 okay_response = requests.Request()
450 okay_response.status_code = requests.codes.ok
451 okay_response.content = ""
452
453 # Assign our mock object our return value
454 mock_post.return_value = okay_response
455
456 # API Key
457 apikey = "abc123"
458
459 obj = Apprise.instantiate(f"mailgun://[email protected]/{apikey}")
460 assert isinstance(obj, NotifyMailgun)
461 assert isinstance(obj.url(), str)
462
463 # No calls made yet
464 assert mock_post.call_count == 0
465
466 # Send our notification
467 assert (
468 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
469 is True
470 )
471
472 # 2 calls were made, one to perform an email lookup, the second
473 # was the notification itself
474 assert mock_post.call_count == 1
475 assert (
476 mock_post.call_args_list[0][0][0]
477 == "https://api.mailgun.net/v3/localhost.localdomain/messages"
478 )
479
480 payload = mock_post.call_args_list[0][1]["data"]
481 assert "from" in payload
482 assert payload["from"] == "Apprise <[email protected]>"
483 assert payload["to"] == "[email protected]"
484
485 # Reset our mock object
486 mock_post.reset_mock()
487
488 obj = Apprise.instantiate(
489 f"mailgun://[email protected]/{apikey}?from=Luke%20Skywalker"
490 )
491 assert isinstance(obj, NotifyMailgun)
492 assert isinstance(obj.url(), str)
493
494 # No calls made yet
495 assert mock_post.call_count == 0
496
497 # Send our notification
498 assert (
499 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
500 is True
501 )
502
503 assert mock_post.call_count == 1
504 payload = mock_post.call_args_list[0][1]["data"]
505 assert "from" in payload
506 assert "to" in payload
507 assert payload["from"] == "Luke Skywalker <[email protected]>"
508 assert payload["to"] == "[email protected]"
509
510 # Reset our mock object
511 mock_post.reset_mock()
512
513 obj = Apprise.instantiate(
514 f"mailgun://[email protected]/{apikey}"
515 "?from=Luke%20Skywalker<[email protected]>"
516 )
517 assert isinstance(obj, NotifyMailgun)
518 assert isinstance(obj.url(), str)
519
520 # No calls made yet
521 assert mock_post.call_count == 0
522
523 # Send our notification
524 assert (
525 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
526 is True
527 )
528
529 assert mock_post.call_count == 1
530 payload = mock_post.call_args_list[0][1]["data"]
531 assert "from" in payload
532 assert "to" in payload
533 assert payload["from"] == "Luke Skywalker <[email protected]>"
534 assert payload["to"] == "[email protected]"
535
536 # Reset our mock object
537 mock_post.reset_mock()
538
539 obj = Apprise.instantiate(
540 f"mailgun://[email protected]/{apikey}[email protected]"
541 )
542 assert isinstance(obj, NotifyMailgun)
543 assert isinstance(obj.url(), str)
544
545 # No calls made yet
546 assert mock_post.call_count == 0
547
548 # Send our notification
549 assert (
550 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
551 is True
552 )
553
554 assert mock_post.call_count == 1
555 payload = mock_post.call_args_list[0][1]["data"]
556 assert "from" in payload
557 assert "to" in payload
558 assert payload["from"] == "[email protected]"
559 assert payload["to"] == "[email protected]"
560
561
562 def test_plugin_mailgun_cc_bcc_invalid_branch():
563 """NotifyMailgun() CC/BCC validation: invalid entries are dropped."""
564
565 # API key and a valid 'from' address (required by __init__)
566 apikey = "abc123"
567
568 # Build a NotifyMailgun with:
569 # cc = one valid address + one that parse_emails passes but is_email
570 # rejects (hits the FALSE branch at line 327).
571 # A list must be used -- parse_emails filters invalid tokens out
572 # of comma-separated strings before is_email is ever called.
573 # bcc = same, for the FALSE branch at line 343
574 obj = NotifyMailgun(
575 apikey=apikey,
576 targets=["[email protected]"],
577 cc=["[email protected]", "notanemail"],
578 bcc=["[email protected]", "alsonotanemail"],
579 user="user",
580 host="example.com",
581 )
582
583 # Valid CC entry was added; invalid one was silently dropped
584 assert "[email protected]" in obj.cc
585 assert len(obj.cc) == 1
586
587 # Valid BCC entry was added; invalid one was silently dropped
588 assert "[email protected]" in obj.bcc
589 assert len(obj.bcc) == 1