Debian Codegraph @

tests/test_plugin_mailgun.py

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