Debian Codegraph @

tests/test_plugin_postmark.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.postmark import NotifyPostmark
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 "postmark://",
50 {
51 # No credentials
52 "instance": AppriseImproperlyConfigured,
53 },
54 ),
55 (
56 "postmark://:@/",
57 {
58 # Empty credentials
59 "instance": AppriseImproperlyConfigured,
60 },
61 ),
62 (
63 "postmark://abcd",
64 {
65 # API key only, no from email
66 "instance": AppriseImproperlyConfigured,
67 },
68 ),
69 (
70 "postmark://abcd@host",
71 {
72 # API key only, no from email
73 "instance": AppriseImproperlyConfigured,
74 },
75 ),
76 (
77 "postmark://abcd:[email protected]",
78 {
79 # No targets; defaults to from address
80 "instance": NotifyPostmark,
81 },
82 ),
83 (
84 "postmark://abcd:[email protected]?format=text",
85 {
86 # Text format override
87 "instance": NotifyPostmark,
88 },
89 ),
90 (
91 "postmark://abcd:[email protected]/[email protected]",
92 {
93 # A good email with explicit target
94 "instance": NotifyPostmark,
95 "force_debug": True,
96 },
97 ),
98 (
99 "postmark://abcd:[email protected]/[email protected]?name=John",
100 {
101 # With From display name
102 "instance": NotifyPostmark,
103 "privacy_url": (
104 "postmark://a...d:[email protected]/[email protected]"
105 ),
106 "url_matches": r"name=John",
107 },
108 ),
109 (
110 (
111 "postmark://abcd:[email protected]/[email protected]"
112 "[email protected]"
113 ),
114 {
115 # With Reply-To
116 "instance": NotifyPostmark,
117 "url_matches": r"reply=",
118 },
119 ),
120 (
121 (
122 "postmark://abcd:[email protected]/[email protected]"
123 "[email protected]"
124 ),
125 {
126 # With Blind Carbon Copy
127 "instance": NotifyPostmark,
128 },
129 ),
130 (
131 (
132 "postmark://abcd:[email protected]/[email protected]"
133 "[email protected]"
134 ),
135 {
136 # With Carbon Copy
137 "instance": NotifyPostmark,
138 },
139 ),
140 (
141 (
142 "postmark://abcd:[email protected]/[email protected]"
143 "?cc=Chris<[email protected]>"
144 ),
145 {
146 # With named Carbon Copy
147 "instance": NotifyPostmark,
148 },
149 ),
150 (
151 (
152 "postmark://abcd:[email protected]/[email protected]"
153 "[email protected]"
154 ),
155 {
156 # Via ?to= for additional targets
157 "instance": NotifyPostmark,
158 },
159 ),
160 (
161 "postmark://abcd:[email protected]/bademailaddress",
162 {
163 # Invalid target dropped; no valid recipients -- fails to send
164 "instance": NotifyPostmark,
165 "notify_response": False,
166 },
167 ),
168 (
169 "postmark://abcd:[email protected]/[email protected]",
170 {
171 "instance": NotifyPostmark,
172 # force a failure
173 "response": False,
174 "requests_response_code": requests.codes.internal_server_error,
175 },
176 ),
177 (
178 "postmark://abcd:[email protected]/[email protected]",
179 {
180 "instance": NotifyPostmark,
181 # throw a bizarre code forcing us to fail to look it up
182 "response": False,
183 "requests_response_code": 999,
184 },
185 ),
186 (
187 "postmark://abcd:[email protected]/[email protected]",
188 {
189 "instance": NotifyPostmark,
190 # Throws a series of connection exceptions with this flag
191 "test_requests_exceptions": True,
192 },
193 ),
194 )
195
196
197 def test_plugin_postmark_urls():
198 """NotifyPostmark() Apprise URLs."""
199
200 # Run our general tests
201 AppriseURLTester(tests=apprise_url_tests).run_all()
202
203
204 @mock.patch("requests.get")
205 @mock.patch("requests.post")
206 def test_plugin_postmark_edge_cases(mock_post, mock_get):
207 """NotifyPostmark() Edge Cases."""
208
209 # No API key
210 with pytest.raises(AppriseImproperlyConfigured):
211 NotifyPostmark(apikey=None, from_email="[email protected]")
212
213 # Invalid from email
214 with pytest.raises(AppriseImproperlyConfigured):
215 NotifyPostmark(apikey="abcd", from_email="!invalid")
216
217 # No from email (None)
218 with pytest.raises(AppriseImproperlyConfigured):
219 NotifyPostmark(apikey="abcd", from_email=None)
220
221 # Invalid target email -- plugin loads but target is dropped
222 obj = NotifyPostmark(
223 apikey="abcd",
224 from_email="[email protected]",
225 targets="!invalid",
226 )
227 # All targets dropped -> send() returns False
228 assert isinstance(obj, NotifyPostmark)
229
230 # Test invalid bcc/cc entries mixed with valid ones
231 assert isinstance(
232 NotifyPostmark(
233 apikey="abcd",
234 from_email="[email protected]",
235 bcc=("[email protected]", "!invalid"),
236 cc=("[email protected]", "!invalid"),
237 ),
238 NotifyPostmark,
239 )
240
241 # Test invalid reply_to entries mixed with valid ones
242 assert isinstance(
243 NotifyPostmark(
244 apikey="abcd",
245 from_email="[email protected]",
246 reply_to=("[email protected]", "!invalid"),
247 ),
248 NotifyPostmark,
249 )
250
251
252 @mock.patch("requests.get")
253 @mock.patch("requests.post")
254 def test_plugin_postmark_send(mock_post, mock_get):
255 """NotifyPostmark() Send."""
256
257 def _mk_resp(code=requests.codes.ok):
258 r = mock.Mock()
259 r.status_code = code
260 r.content = b""
261 return r
262
263 mock_post.return_value = _mk_resp()
264 mock_get.return_value = _mk_resp()
265
266 # Basic send to self (no explicit target)
267 obj = Apprise.instantiate("postmark://abcd:[email protected]")
268 assert isinstance(obj, NotifyPostmark)
269 assert bool(obj.notify(body="body", title="title")) is True
270
271 # Verify the X-Postmark-Server-Token header was set
272 assert mock_post.call_count == 1
273 call_kwargs = mock_post.call_args
274 import json
275
276 posted = json.loads(call_kwargs[1]["data"])
277 assert posted["To"] == "[email protected]"
278 assert "X-Postmark-Server-Token" in call_kwargs[1]["headers"]
279
280 mock_post.reset_mock()
281
282 # Send with an explicit target
283 obj = Apprise.instantiate(
284 "postmark://abcd:[email protected]/[email protected]"
285 )
286 assert bool(obj.notify(body="body", title="title")) is True
287 posted = json.loads(mock_post.call_args[1]["data"])
288 assert posted["To"] == "[email protected]"
289 mock_post.reset_mock()
290
291 # Send with cc and bcc
292 obj = NotifyPostmark(
293 apikey="abcd",
294 from_email="[email protected]",
295 targets=["[email protected]"],
296 cc=["[email protected]"],
297 bcc=["[email protected]"],
298 )
299 assert bool(obj.notify(body="body", title="title")) is True
300 posted = json.loads(mock_post.call_args[1]["data"])
301 assert "Cc" in posted
302 assert "Bcc" in posted
303 mock_post.reset_mock()
304
305 # Send with reply_to
306 obj = NotifyPostmark(
307 apikey="abcd",
308 from_email="[email protected]",
309 reply_to=["[email protected]"],
310 )
311 assert bool(obj.notify(body="body", title="title")) is True
312 posted = json.loads(mock_post.call_args[1]["data"])
313 assert "ReplyTo" in posted
314 mock_post.reset_mock()
315
316 # Empty title falls back to default_empty_subject
317 obj = NotifyPostmark(
318 apikey="abcd",
319 from_email="[email protected]",
320 )
321 assert bool(obj.notify(body="body", title="")) is True
322 posted = json.loads(mock_post.call_args[1]["data"])
323 assert posted["Subject"] == NotifyPostmark.default_empty_subject
324 mock_post.reset_mock()
325
326 # Text format
327 obj = NotifyPostmark(
328 apikey="abcd",
329 from_email="[email protected]",
330 )
331 from apprise.common import NotifyFormat
332
333 obj.notify_format = NotifyFormat.TEXT
334 assert bool(obj.notify(body="body", title="title")) is True
335 posted = json.loads(mock_post.call_args[1]["data"])
336 assert "TextBody" in posted
337 assert "HtmlBody" not in posted
338 mock_post.reset_mock()
339
340 # HTTP error response
341 mock_post.return_value = _mk_resp(requests.codes.internal_server_error)
342 obj = Apprise.instantiate(
343 "postmark://abcd:[email protected]/[email protected]"
344 )
345 assert bool(obj.notify(body="body", title="title")) is False
346 mock_post.reset_mock()
347
348 # Unknown HTTP code
349 mock_post.return_value = _mk_resp(999)
350 assert bool(obj.notify(body="body", title="title")) is False
351 mock_post.reset_mock()
352
353 # RequestException
354 mock_post.side_effect = requests.RequestException("Connection failed")
355 assert bool(obj.notify(body="body", title="title")) is False
356 mock_post.side_effect = None
357 mock_post.reset_mock()
358
359 # No valid targets -> False without any HTTP call
360 obj = NotifyPostmark(
361 apikey="abcd",
362 from_email="[email protected]",
363 targets=["!invalid"],
364 )
365 mock_post.return_value = _mk_resp()
366 assert bool(obj.notify(body="body", title="title")) is False
367 assert mock_post.call_count == 0
368
369 # Multiple targets -- partial failure
370 mock_post.reset_mock()
371 responses = [_mk_resp(), _mk_resp(requests.codes.bad_request)]
372 mock_post.side_effect = responses
373 obj = NotifyPostmark(
374 apikey="abcd",
375 from_email="[email protected]",
376 targets=["[email protected]", "[email protected]"],
377 )
378 assert bool(obj.notify(body="body", title="title")) is False
379 assert mock_post.call_count == 2
380 mock_post.side_effect = None
381
382
383 @mock.patch("requests.post")
384 def test_plugin_postmark_attachments(mock_post):
385 """NotifyPostmark() Attachments."""
386
387 def _mk_resp(code=requests.codes.ok):
388 r = mock.Mock()
389 r.status_code = code
390 r.content = b""
391 return r
392
393 mock_post.return_value = _mk_resp()
394
395 # Single attachment success
396 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
397 attach = AppriseAttachment(path)
398 obj = Apprise.instantiate("postmark://abcd:[email protected]")
399 assert isinstance(obj, NotifyPostmark)
400 assert (
401 bool(
402 obj.notify(
403 body="body",
404 title="title",
405 notify_type=NotifyType.INFO,
406 attach=attach,
407 )
408 )
409 is True
410 )
411
412 import json
413
414 posted = json.loads(mock_post.call_args[1]["data"])
415 assert "Attachments" in posted
416 assert len(posted["Attachments"]) == 1
417 assert posted["Attachments"][0]["Name"] == "apprise-test.gif"
418 mock_post.reset_mock()
419
420 # Multiple attachments
421 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
422 attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
423 assert (
424 bool(
425 obj.notify(
426 body="body",
427 title="title",
428 notify_type=NotifyType.INFO,
429 attach=attach,
430 )
431 )
432 is True
433 )
434 posted = json.loads(mock_post.call_args[1]["data"])
435 assert len(posted["Attachments"]) == 2
436 mock_post.reset_mock()
437
438 # Attachment inaccessible (file not found)
439 with mock.patch("os.path.isfile", return_value=False):
440 assert (
441 bool(
442 obj.notify(
443 body="body",
444 title="title",
445 notify_type=NotifyType.INFO,
446 attach=AppriseAttachment(
447 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
448 ),
449 )
450 )
451 is False
452 )
453
454 # Attachment read error (OSError)
455 with mock.patch("builtins.open", side_effect=OSError):
456 assert (
457 bool(
458 obj.notify(
459 body="body",
460 title="title",
461 notify_type=NotifyType.INFO,
462 attach=AppriseAttachment(
463 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
464 ),
465 )
466 )
467 is False
468 )
469
470
471 @mock.patch("requests.post")
472 def test_plugin_postmark_url_parsing(mock_post):
473 """NotifyPostmark() URL parsing and round-trip."""
474
475 def _mk_resp(code=requests.codes.ok):
476 r = mock.Mock()
477 r.status_code = code
478 r.content = b""
479 return r
480
481 mock_post.return_value = _mk_resp()
482
483 # Basic round-trip
484 obj = NotifyPostmark(
485 apikey="mytoken",
486 from_email="[email protected]",
487 )
488 url = obj.url()
489 result = NotifyPostmark.parse_url(url)
490 assert result is not None
491 obj2 = NotifyPostmark(**result)
492 assert obj.url_identifier == obj2.url_identifier
493
494 # With explicit target
495 obj = NotifyPostmark(
496 apikey="mytoken",
497 from_email="[email protected]",
498 targets=["[email protected]"],
499 )
500 url = obj.url()
501 result = NotifyPostmark.parse_url(url)
502 assert result is not None
503 obj2 = NotifyPostmark(**result)
504 assert len(obj.targets) == len(obj2.targets)
505
506 # With from_name
507 obj = NotifyPostmark(
508 apikey="mytoken",
509 from_email="[email protected]",
510 from_name="Alice",
511 )
512 url = obj.url()
513 assert "name=Alice" in url
514 result = NotifyPostmark.parse_url(url)
515 assert result is not None
516 obj2 = NotifyPostmark(**result)
517 assert obj2.from_addr[0] == "Alice"
518
519 # With bcc and cc
520 obj = NotifyPostmark(
521 apikey="mytoken",
522 from_email="[email protected]",
523 targets=["[email protected]"],
524 cc=["[email protected]"],
525 bcc=["[email protected]"],
526 )
527 url = obj.url()
528 result = NotifyPostmark.parse_url(url)
529 assert result is not None
530 obj2 = NotifyPostmark(**result)
531 assert "[email protected]" in obj2.cc
532 assert "[email protected]" in obj2.bcc
533
534 # With reply_to
535 obj = NotifyPostmark(
536 apikey="mytoken",
537 from_email="[email protected]",
538 reply_to=["[email protected]"],
539 )
540 url = obj.url()
541 result = NotifyPostmark.parse_url(url)
542 assert result is not None
543 obj2 = NotifyPostmark(**result)
544 assert "[email protected]" in obj2.reply_to
545
546 # parse_url returns None for completely unparseable input
547 assert NotifyPostmark.parse_url(None) is None
548
549 # ?apikey= override
550 result = NotifyPostmark.parse_url(
551 "postmark://?apikey=overridekey&[email protected]"
552 "&[email protected]"
553 )
554 assert result is not None
555 assert result["apikey"] == "overridekey"
556
557 # ?from= override (from address via query param)
558 result = NotifyPostmark.parse_url(
559 "postmark://[email protected]/[email protected][email protected]"
560 )
561 assert result is not None
562 assert result["from_email"] == "[email protected]"
563
564 # privacy_url hides the API key
565 obj = NotifyPostmark(
566 apikey="secrettoken",
567 from_email="[email protected]",
568 )
569 privacy = obj.url(privacy=True)
570 assert "secrettoken" not in privacy
571 assert "s...n" in privacy or "..." in privacy
572
573 # __len__
574 obj = NotifyPostmark(
575 apikey="mytoken",
576 from_email="[email protected]",
577 targets=["[email protected]", "[email protected]"],
578 )
579 assert len(obj) == 2
580
581 # url_identifier
582 obj1 = NotifyPostmark(
583 apikey="tok",
584 from_email="[email protected]",
585 )
586 obj2 = NotifyPostmark(
587 apikey="tok",
588 from_email="[email protected]",
589 targets=["[email protected]"],
590 )
591 assert obj1.url_identifier == obj2.url_identifier