Debian Codegraph @

tests/test_plugin_pushover.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 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 import apprise
40 from apprise.exception import AppriseImproperlyConfigured
41 from apprise.plugins.pushover import NotifyPushover, PushoverPriority
42
43 logging.disable(logging.CRITICAL)
44
45 # Attachment Directory
46 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
47
48 # Our Testing URLs
49 apprise_url_tests = (
50 (
51 "pover://",
52 {
53 "instance": AppriseImproperlyConfigured,
54 },
55 ),
56 # bad url
57 (
58 "pover://:@/",
59 {
60 "instance": AppriseImproperlyConfigured,
61 },
62 ),
63 # APIkey; no user
64 (
65 "pover://%s" % ("a" * 30),
66 {
67 "instance": AppriseImproperlyConfigured,
68 },
69 ),
70 # API Key + custom sound setting
71 (
72 "pover://{}@{}?sound=mysound".format("u" * 30, "a" * 30),
73 {
74 "instance": NotifyPushover,
75 },
76 ),
77 # API Key + valid alternate sound picked
78 (
79 "pover://{}@{}?sound=spacealarm".format("u" * 30, "a" * 30),
80 {
81 "instance": NotifyPushover,
82 },
83 ),
84 # API Key + valid url_title with url
85 (
86 "pover://{}@{}?url=my-url&url_title=title".format("u" * 30, "a" * 30),
87 {
88 "instance": NotifyPushover,
89 },
90 ),
91 # API Key + Valid User
92 (
93 "pover://{}@{}".format("u" * 30, "a" * 30),
94 {
95 "instance": NotifyPushover,
96 # don't include an image by default
97 "include_image": False,
98 },
99 ),
100 # API Key + Valid User + 1 Device
101 (
102 "pover://{}@{}/DEVICE".format("u" * 30, "a" * 30),
103 {
104 "instance": NotifyPushover,
105 },
106 ),
107 # API Key + Valid User + 1 Device (via to=)
108 (
109 "pover://{}@{}?to=DEVICE".format("u" * 30, "a" * 30),
110 {
111 "instance": NotifyPushover,
112 },
113 ),
114 # API Key + Valid User + 2 Devices
115 (
116 "pover://{}@{}/DEVICE1/Device-with-dash/".format("u" * 30, "a" * 30),
117 {
118 "instance": NotifyPushover,
119 # Our expected url(privacy=True) startswith() response:
120 "privacy_url": "pover://[email protected]",
121 },
122 ),
123 # API Key + Valid User + invalid device
124 (
125 "pover://{}@{}/{}/".format("u" * 30, "a" * 30, "d" * 30),
126 {
127 "instance": NotifyPushover,
128 # Notify will return False since there is a bad device in our list
129 "response": False,
130 },
131 ),
132 # API Key + Valid User + device + invalid device
133 (
134 "pover://{}@{}/DEVICE1/{}/".format("u" * 30, "a" * 30, "d" * 30),
135 {
136 "instance": NotifyPushover,
137 # Notify will return False since there is a bad device in our list
138 "response": False,
139 },
140 ),
141 # API Key + Valid User + 1 Group key (percent-encoded)
142 (
143 "pover://{}@{}/%23{}".format("u" * 30, "a" * 30, "g" * 30),
144 {
145 "instance": NotifyPushover,
146 },
147 ),
148 # API Key + Valid User + 1 Group key (literal #)
149 (
150 "pover://{}@{}/#{}/".format("u" * 30, "a" * 30, "g" * 30),
151 {
152 "instance": NotifyPushover,
153 },
154 ),
155 # API Key + Valid User + Group key (via to= percent-encoded)
156 (
157 "pover://{}@{}?to=%23{}".format("u" * 30, "a" * 30, "g" * 30),
158 {
159 "instance": NotifyPushover,
160 },
161 ),
162 # API Key + Valid User + 2 Group keys (percent-encoded)
163 (
164 "pover://{}@{}/%23{}/%23{}".format(
165 "u" * 30, "a" * 30, "g" * 30, "h" * 30
166 ),
167 {
168 "instance": NotifyPushover,
169 },
170 ),
171 # API Key + Valid User + 2 Group keys (literal #)
172 (
173 "pover://{}@{}/#{}/#{}/".format(
174 "u" * 30, "a" * 30, "g" * 30, "h" * 30
175 ),
176 {
177 "instance": NotifyPushover,
178 },
179 ),
180 # API Key + Valid User + 1 Device + 1 Group key (percent-encoded)
181 (
182 "pover://{}@{}/DEVICE/%23{}".format("u" * 30, "a" * 30, "g" * 30),
183 {
184 "instance": NotifyPushover,
185 },
186 ),
187 # API Key + Valid User + 1 Device + 1 Group key (literal #)
188 (
189 "pover://{}@{}/DEVICE/#{}".format("u" * 30, "a" * 30, "g" * 30),
190 {
191 "instance": NotifyPushover,
192 },
193 ),
194 # API Key + Valid User + invalid group (contains invalid chars)
195 (
196 "pover://{}@{}/%23invalid-group/".format("u" * 30, "a" * 30),
197 {
198 "instance": NotifyPushover,
199 # Notify will return False since the group key is invalid
200 # (contains a dash which is not alphanumeric)
201 "response": False,
202 },
203 ),
204 # API Key + priority setting
205 (
206 "pover://{}@{}?priority=high".format("u" * 30, "a" * 30),
207 {
208 "instance": NotifyPushover,
209 },
210 ),
211 # API Key + priority setting + html mode
212 (
213 "pover://{}@{}?priority=high&format=html".format("u" * 30, "a" * 30),
214 {
215 "instance": NotifyPushover,
216 },
217 ),
218 # API Key + priority setting + markdown mode
219 (
220 "pover://{}@{}?priority=high&format=markdown".format(
221 "u" * 30, "a" * 30
222 ),
223 {
224 "instance": NotifyPushover,
225 },
226 ),
227 # API Key + invalid priority setting
228 (
229 "pover://{}@{}?priority=invalid".format("u" * 30, "a" * 30),
230 {
231 "instance": NotifyPushover,
232 },
233 ),
234 # API Key + emergency(2) priority setting
235 (
236 "pover://{}@{}?priority=emergency".format("u" * 30, "a" * 30),
237 {
238 "instance": NotifyPushover,
239 },
240 ),
241 # API Key + emergency(2) priority setting (via numeric value
242 (
243 "pover://{}@{}?priority=2".format("u" * 30, "a" * 30),
244 {
245 "instance": NotifyPushover,
246 },
247 ),
248 # API Key + emergency priority setting with interval and expire
249 (
250 "pover://{}@{}?priority=emergency&{}&{}".format(
251 "u" * 30, "a" * 30, "interval=30", "expire=300"
252 ),
253 {
254 "instance": NotifyPushover,
255 },
256 ),
257 # API Key + emergency priority setting with text interval
258 (
259 "pover://{}@{}?priority=emergency&{}&{}".format(
260 "u" * 30, "a" * 30, "interval=invalid", "expire=300"
261 ),
262 {
263 "instance": NotifyPushover,
264 },
265 ),
266 # API Key + emergency priority setting with text expire
267 (
268 "pover://{}@{}?priority=emergency&{}&{}".format(
269 "u" * 30, "a" * 30, "interval=30", "expire=invalid"
270 ),
271 {
272 "instance": NotifyPushover,
273 },
274 ),
275 # API Key + emergency priority setting with invalid expire
276 (
277 "pover://{}@{}?priority=emergency&{}".format(
278 "u" * 30, "a" * 30, "expire=100000"
279 ),
280 {
281 "instance": AppriseImproperlyConfigured,
282 },
283 ),
284 # API Key + emergency priority setting with invalid interval
285 (
286 "pover://{}@{}?priority=emergency&{}".format(
287 "u" * 30, "a" * 30, "interval=15"
288 ),
289 {
290 "instance": AppriseImproperlyConfigured,
291 },
292 ),
293 # API Key + priority setting (empty)
294 (
295 "pover://{}@{}?priority=".format("u" * 30, "a" * 30),
296 {
297 "instance": NotifyPushover,
298 },
299 ),
300 (
301 "pover://{}@{}".format("u" * 30, "a" * 30),
302 {
303 "instance": NotifyPushover,
304 # force a failure
305 "response": False,
306 "requests_response_code": requests.codes.internal_server_error,
307 },
308 ),
309 (
310 "pover://{}@{}".format("u" * 30, "a" * 30),
311 {
312 "instance": NotifyPushover,
313 # throw a bizarre code forcing us to fail to look it up
314 "response": False,
315 "requests_response_code": 999,
316 },
317 ),
318 (
319 "pover://{}@{}".format("u" * 30, "a" * 30),
320 {
321 "instance": NotifyPushover,
322 # Throws a series of i/o exceptions with this flag
323 # is set and tests that we gracefully handle them
324 "test_requests_exceptions": True,
325 },
326 ),
327 # E2EE: valid 64-char hex encryption key
328 (
329 "pover://{}@{}?key={}".format("u" * 30, "a" * 30, "b" * 64),
330 {
331 "instance": NotifyPushover,
332 "privacy_url": "pover://[email protected]",
333 },
334 ),
335 # E2EE: explicit e2ee=yes with key
336 (
337 "pover://{}@{}?key={}&e2ee=yes".format("u" * 30, "a" * 30, "c" * 64),
338 {
339 "instance": NotifyPushover,
340 },
341 ),
342 # E2EE: key present but e2ee=no (plaintext send)
343 (
344 "pover://{}@{}?key={}&e2ee=no".format("u" * 30, "a" * 30, "d" * 64),
345 {
346 "instance": NotifyPushover,
347 },
348 ),
349 # E2EE: invalid key (not 64 hex chars)
350 (
351 "pover://{}@{}?key=tooshort".format("u" * 30, "a" * 30),
352 {
353 "instance": AppriseImproperlyConfigured,
354 },
355 ),
356 # E2EE: invalid key (correct length but non-hex)
357 (
358 "pover://{}@{}?key={}".format(
359 "u" * 30,
360 "a" * 30,
361 # 64 chars but contains 'z' which is not valid hex
362 "z" * 64,
363 ),
364 {
365 "instance": AppriseImproperlyConfigured,
366 },
367 ),
368 )
369
370
371 def test_plugin_pushover_urls():
372 """NotifyPushover() Apprise URLs."""
373
374 # Run our general tests
375 AppriseURLTester(tests=apprise_url_tests).run_all()
376
377
378 @mock.patch("requests.post")
379 def test_plugin_pushover_attachments(mock_post, tmpdir):
380 """NotifyPushover() Attachment Checks."""
381
382 # Initialize some generic (but valid) tokens
383 user_key = "u" * 30
384 api_token = "a" * 30
385
386 # Prepare a good response
387 response = mock.Mock()
388 response.content = dumps(
389 {"status": 1, "request": "647d2300-702c-4b38-8b2f-d56326ae460b"}
390 )
391 response.status_code = requests.codes.ok
392
393 # Prepare a bad response
394 bad_response = mock.Mock()
395 bad_response.content = dumps(
396 {"status": 1, "request": "647d2300-702c-4b38-8b2f-d56326ae460b"}
397 )
398 bad_response.status_code = requests.codes.internal_server_error
399
400 # Assign our good response
401 mock_post.return_value = response
402
403 # prepare our attachment
404 attach = apprise.AppriseAttachment(
405 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
406 )
407
408 # Instantiate our object
409 obj = apprise.Apprise.instantiate(f"pover://{user_key}@{api_token}/")
410 assert isinstance(obj, NotifyPushover)
411
412 # Test our attachment
413 assert bool(obj.notify(body="test", attach=attach)) is True
414
415 # Test our call count
416 assert mock_post.call_count == 1
417 assert (
418 mock_post.call_args_list[0][0][0]
419 == "https://api.pushover.net/1/messages.json"
420 )
421
422 # Reset our mock object for multiple tests
423 mock_post.reset_mock()
424
425 # Test multiple attachments
426 assert attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
427 assert bool(obj.notify(body="test", attach=attach)) is True
428
429 # Test our call count
430 assert mock_post.call_count == 2
431 assert (
432 mock_post.call_args_list[0][0][0]
433 == "https://api.pushover.net/1/messages.json"
434 )
435 assert (
436 mock_post.call_args_list[1][0][0]
437 == "https://api.pushover.net/1/messages.json"
438 )
439
440 # Reset our mock object for multiple tests
441 mock_post.reset_mock()
442
443 image = tmpdir.mkdir("pover_image").join("test.jpg")
444 image.write("a" * NotifyPushover.attach_max_size_bytes)
445
446 attach = apprise.AppriseAttachment.instantiate(str(image))
447 assert bool(obj.notify(body="test", attach=attach)) is True
448
449 # Test our call count
450 assert mock_post.call_count == 1
451 assert (
452 mock_post.call_args_list[0][0][0]
453 == "https://api.pushover.net/1/messages.json"
454 )
455
456 # Reset our mock object for multiple tests
457 mock_post.reset_mock()
458
459 # Add 1 more byte to the file (putting it over the limit)
460 image.write("a" * (NotifyPushover.attach_max_size_bytes + 1))
461
462 attach = apprise.AppriseAttachment.instantiate(str(image))
463 assert bool(obj.notify(body="test", attach=attach)) is False
464
465 # Test our call count
466 assert mock_post.call_count == 0
467
468 # Test case when file is missing
469 attach = apprise.AppriseAttachment.instantiate(
470 f"file://{image!s}?cache=False"
471 )
472 os.unlink(str(image))
473 assert bool(obj.notify(body="body", title="title", attach=attach)) is False
474
475 # Test our call count
476 assert mock_post.call_count == 0
477
478 # Test unsuported files:
479 image = tmpdir.mkdir("pover_unsupported").join("test.doc")
480 image.write("a" * 256)
481 attach = apprise.AppriseAttachment.instantiate(str(image))
482
483 # Content is silently ignored
484 assert bool(obj.notify(body="test", attach=attach)) is True
485
486 # prepare our attachment
487 attach = apprise.AppriseAttachment(
488 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
489 )
490
491 # Throw an exception on the first call to requests.post()
492 for side_effect in (requests.RequestException(), OSError(), bad_response):
493 mock_post.side_effect = [side_effect, side_effect]
494
495 # We'll fail now because of our error handling
496 assert obj.send(body="test", attach=attach) is False
497
498 # Same case without an attachment
499 assert obj.send(body="test") is False
500
501
502 @mock.patch("requests.post")
503 def test_plugin_pushover_edge_cases(mock_post):
504 """NotifyPushover() Edge Cases."""
505
506 # No token
507 with pytest.raises(AppriseImproperlyConfigured):
508 NotifyPushover(token=None)
509
510 # Initialize some generic (but valid) tokens
511 token = "a" * 30
512 user_key = "u" * 30
513
514 invalid_device = "d" * 35
515
516 # Support strings
517 devices = f"device1,device2,,,,{invalid_device}"
518
519 # Prepare Mock
520 mock_post.return_value = requests.Request()
521 mock_post.return_value.status_code = requests.codes.ok
522
523 # No webhook id specified
524 with pytest.raises(AppriseImproperlyConfigured):
525 NotifyPushover(user_key=user_key, webhook_id=None)
526
527 obj = NotifyPushover(user_key=user_key, token=token, targets=devices)
528 assert isinstance(obj, NotifyPushover)
529 # Our invalid device is ignored; 2 valid devices remain
530 assert len(obj.devices) == 2
531 assert len(obj.groups) == 0
532
533 # We notify the 2 devices loaded
534 assert (
535 bool(
536 obj.notify(
537 body="body", title="title", notify_type=apprise.NotifyType.INFO
538 )
539 )
540 is True
541 )
542
543 obj = NotifyPushover(user_key=user_key, token=token)
544 assert isinstance(obj, NotifyPushover)
545 # Default is to send to all devices (sentinel placed in devices list)
546 assert len(obj.devices) == 1
547 assert len(obj.groups) == 0
548 assert len(obj) == 1
549
550 # This call succeeds because all of the devices are valid
551 assert (
552 bool(
553 obj.notify(
554 body="body", title="title", notify_type=apprise.NotifyType.INFO
555 )
556 )
557 is True
558 )
559
560 obj = NotifyPushover(user_key=user_key, token=token, targets=set())
561 assert isinstance(obj, NotifyPushover)
562 # Default is to send to all devices (sentinel placed in devices list)
563 assert len(obj.devices) == 1
564 assert len(obj.groups) == 0
565 assert len(obj) == 1
566
567 # Group targets
568 group_key = "g" * 30
569 obj = NotifyPushover(
570 user_key=user_key, token=token, targets=f"#{group_key}"
571 )
572 assert isinstance(obj, NotifyPushover)
573 assert len(obj.devices) == 0
574 assert len(obj.groups) == 1
575 assert obj.groups[0] == group_key
576 assert len(obj) == 1
577
578 # Verify notification to a group succeeds (separate API call per group)
579 assert (
580 bool(
581 obj.notify(
582 body="body", title="title", notify_type=apprise.NotifyType.INFO
583 )
584 )
585 is True
586 )
587
588 # Mix of device and group → 2 HTTP calls (1 device batch + 1 group)
589 obj = NotifyPushover(
590 user_key=user_key, token=token, targets=["device1", f"#{group_key}"]
591 )
592 assert isinstance(obj, NotifyPushover)
593 assert len(obj.devices) == 1
594 assert len(obj.groups) == 1
595 assert len(obj) == 2
596
597 # Invalid group key (contains dash — not alphanumeric)
598 obj = NotifyPushover(
599 user_key=user_key, token=token, targets="#invalid-group"
600 )
601 assert isinstance(obj, NotifyPushover)
602 # Invalid target is rejected; both lists empty → send() returns False
603 assert len(obj.devices) == 0
604 assert len(obj.groups) == 0
605
606 # Always 1 is returned as minimum
607 assert len(obj) == 1
608
609 # No User Key specified
610 with pytest.raises(AppriseImproperlyConfigured):
611 NotifyPushover(user_key=None, token="abcd")
612
613 # No Access Token specified
614 with pytest.raises(AppriseImproperlyConfigured):
615 NotifyPushover(user_key="abcd", token=None)
616
617 with pytest.raises(AppriseImproperlyConfigured):
618 NotifyPushover(user_key="abcd", token=" ")
619
620
621 @mock.patch("requests.post")
622 def test_plugin_pushover_multi_format(mock_post):
623 """NotifyPushover() multi-format resolution."""
624
625 mock_post.return_value = requests.Request()
626 mock_post.return_value.status_code = requests.codes.ok
627
628 token = "a" * 30
629 user_key = "u" * 30
630
631 obj = NotifyPushover(user_key=user_key, token=token)
632
633 # HTML: declared source aligns directly, html flag set, body as-is.
634 mock_post.reset_mock()
635 assert obj.notify(body="<b>hi</b>", body_format=apprise.NotifyFormat.HTML)
636 sent = mock_post.call_args[1]["data"]
637 assert sent["html"] == 1
638 assert sent["message"] == "<b>hi</b>"
639
640 # Markdown is converted to HTML because Pushover has no Markdown mode.
641 mock_post.reset_mock()
642 assert obj.notify(body="*hi*", body_format=apprise.NotifyFormat.MARKDOWN)
643 sent = mock_post.call_args[1]["data"]
644 assert sent["html"] == 1
645 assert sent["message"] != "*hi*"
646
647 # Undeclared input stays unconverted, even with a Markdown override.
648 mock_post.reset_mock()
649 obj_override = NotifyPushover(
650 user_key=user_key, token=token, format="markdown"
651 )
652 assert obj_override.notify(body="*hi*")
653 sent = mock_post.call_args[1]["data"]
654 assert "html" not in sent
655 assert sent["message"] == "*hi*"
656
657
658 @mock.patch("requests.post")
659 def test_plugin_pushover_config_files(mock_post):
660 """NotifyPushover() Config File Cases."""
661 content = """
662 urls:
663 - pover://USER@TOKEN:
664 - priority: -2
665 tag: pushover_int low
666 - priority: "-2"
667 tag: pushover_str_int low
668 - priority: low
669 tag: pushover_str low
670
671 # This will take on normal (default) priority
672 - priority: invalid
673 tag: pushover_invalid
674
675 - pover://USER2@TOKEN2:
676 - priority: 2
677 tag: pushover_int emerg
678 - priority: "2"
679 tag: pushover_str_int emerg
680 - priority: emergency
681 tag: pushover_str emerg
682 """
683
684 # Prepare Mock
685 mock_post.return_value = requests.Request()
686 mock_post.return_value.status_code = requests.codes.ok
687
688 # Create ourselves a config object
689 ac = apprise.AppriseConfig()
690 assert ac.add_config(content=content) is True
691
692 aobj = apprise.Apprise()
693
694 # Add our configuration
695 aobj.add(ac)
696
697 # We should be able to read our 7 services from that
698 # 3x low
699 # 3x emerg
700 # 1x invalid (so takes on normal priority)
701 assert len(ac.services()) == 7
702 assert len(aobj) == 7
703 assert len(list(aobj.find(tag="low"))) == 3
704 for s in aobj.find(tag="low"):
705 assert s.priority == PushoverPriority.LOW
706
707 assert len(list(aobj.find(tag="emerg"))) == 3
708 for s in aobj.find(tag="emerg"):
709 assert s.priority == PushoverPriority.EMERGENCY
710
711 assert len(list(aobj.find(tag="pushover_str"))) == 2
712 assert len(list(aobj.find(tag="pushover_str_int"))) == 2
713 assert len(list(aobj.find(tag="pushover_int"))) == 2
714
715 assert len(list(aobj.find(tag="pushover_invalid"))) == 1
716 assert (
717 next(aobj.find(tag="pushover_invalid")).priority
718 == PushoverPriority.NORMAL
719 )
720
721 # Notifications work
722 # We test 'pushover_str_int' and 'low' which only matches 1 end point
723 assert (
724 bool(
725 aobj.notify(
726 title="title", body="body", tag=[("pushover_str_int", "low")]
727 )
728 )
729 is True
730 )
731
732 # Notify everything loaded
733 assert bool(aobj.notify(title="title", body="body")) is True
734
735
736 @mock.patch("requests.post")
737 def test_plugin_pushover_group_request_exception(mock_post):
738 """NotifyPushover() group RequestException must not raise KeyError."""
739 user_key = "u" * 30
740 token = "a" * 30
741 group_key = "g" * 30
742
743 mock_post.side_effect = requests.RequestException("connection error")
744
745 obj = NotifyPushover(
746 user_key=user_key, token=token, targets=f"#{group_key}"
747 )
748 assert isinstance(obj, NotifyPushover)
749 assert len(obj.groups) == 1
750 assert len(obj.devices) == 0
751
752 # Must return False cleanly -- no KeyError from payload["device"]
753 assert obj.send(body="test") is False
754
755
756 @mock.patch("requests.post")
757 def test_plugin_pushover_url_roundtrip(mock_post):
758 """NotifyPushover() url() must preserve sound, url, and url_title."""
759 from apprise.plugins.pushover import NotifyPushover
760
761 user_key = "u" * 30
762 token = "a" * 30
763
764 mock_post.return_value = mock.Mock()
765 mock_post.return_value.status_code = requests.codes.ok
766
767 # Instantiate with all three round-trip fields set
768 obj = NotifyPushover(
769 user_key=user_key,
770 token=token,
771 sound="bike",
772 supplemental_url="https://example.com",
773 supplemental_url_title="Click Here",
774 )
775 assert isinstance(obj, NotifyPushover)
776 assert obj.sound == "bike"
777 assert obj.supplemental_url == "https://example.com"
778 assert obj.supplemental_url_title == "Click Here"
779
780 # Round-trip via url() -> parse_url() -> re-instantiate
781 generated_url = obj.url()
782 assert "sound=bike" in generated_url
783 assert "url=" in generated_url
784 assert "url_title=" in generated_url
785
786 parsed = NotifyPushover.parse_url(generated_url)
787 assert parsed is not None
788 assert parsed["sound"] == "bike"
789 assert parsed["supplemental_url"] == "https://example.com"
790 assert parsed["supplemental_url_title"] == "Click Here"
791
792 obj2 = NotifyPushover(**parsed)
793 assert obj2.sound == "bike"
794 assert obj2.supplemental_url == "https://example.com"
795 assert obj2.supplemental_url_title == "Click Here"
796
797
798 def test_plugin_pushover_parse_url_title_unquote():
799 """NotifyPushover() parse_url() unquote url_title like other fields."""
800 user_key = "u" * 30
801 token = "a" * 30
802
803 # url_title with percent-encoded spaces and special chars
804 url = "pover://{}@{}/?url_title=Hello%20World".format(user_key, token)
805 parsed = NotifyPushover.parse_url(url)
806 assert parsed is not None
807 # Must be decoded, not raw percent-encoded
808 assert parsed["supplemental_url_title"] == "Hello World"
809
810 # Spacing is fine too
811 url = "pover://{}@{}/?url_title=Hello World".format(user_key, token)
812 parsed = NotifyPushover.parse_url(url)
813 assert parsed is not None
814 # Must be decoded, not raw percent-encoded
815 assert parsed["supplemental_url_title"] == "Hello World"
816
817
818 @mock.patch("requests.post")
819 def test_plugin_pushover_attach_memory(mock_post):
820 """Regression: AttachMemory must be sendable without OSError."""
821 from apprise.attachment.memory import AttachMemory
822
823 user_key = "u" * 30
824 api_token = "a" * 30
825
826 response = mock.Mock()
827 response.content = dumps(
828 {"status": 1, "request": "647d2300-702c-4b38-8b2f-d56326ae460b"}
829 )
830 response.status_code = requests.codes.ok
831 mock_post.return_value = response
832
833 obj = apprise.Apprise.instantiate(f"pover://{user_key}@{api_token}/")
834 assert isinstance(obj, NotifyPushover)
835
836 mem = AttachMemory(
837 content=b"<html><body><h1>Test</h1></body></html>",
838 name="report.html",
839 mimetype="text/html",
840 )
841
842 assert bool(obj.notify(body="Test", attach=mem)) is True
843 assert mock_post.call_count == 1
844
845
846 @mock.patch("requests.post")
847 def test_plugin_pushover_e2ee(mock_post):
848 """NotifyPushover() E2EE encryption support."""
849 import apprise.plugins.pushover as _pover_mod
850
851 user_key = "u" * 30
852 token = "a" * 30
853 # A valid 256-bit AES key expressed as 64 hex characters
854 valid_key = "ab" * 32 # 64 chars
855
856 response = mock.Mock()
857 response.content = dumps(
858 {"status": 1, "request": "647d2300-702c-4b38-8b2f-d56326ae460b"}
859 )
860 response.status_code = requests.codes.ok
861 mock_post.return_value = response
862
863 # --- Invalid key: too short ---
864 with pytest.raises(AppriseImproperlyConfigured):
865 NotifyPushover(user_key=user_key, token=token, encryption_key="abc")
866
867 # --- Invalid key: 64 chars but non-hex ---
868 with pytest.raises(AppriseImproperlyConfigured):
869 NotifyPushover(user_key=user_key, token=token, encryption_key="z" * 64)
870
871 # --- Valid key: object instantiates correctly ---
872 obj = NotifyPushover(
873 user_key=user_key, token=token, encryption_key=valid_key
874 )
875 assert isinstance(obj, NotifyPushover)
876 assert obj.encryption_key == valid_key
877 # e2ee defaults to True
878 assert obj.e2ee is True
879
880 # --- e2ee=False: encryption disabled even when key present ---
881 obj_no_e2ee = NotifyPushover(
882 user_key=user_key, token=token, encryption_key=valid_key, e2ee=False
883 )
884 assert obj_no_e2ee.e2ee is False
885
886 # --- No key: e2ee flag is still stored but encryption is skipped ---
887 obj_nokey = NotifyPushover(user_key=user_key, token=token)
888 assert obj_nokey.encryption_key is None
889 # Send without key succeeds normally (no encryption path taken)
890 assert obj_nokey.send(body="test") is True
891 assert mock_post.call_count == 1
892 mock_post.reset_mock()
893
894 # --- URL round-trip with key: key and e2ee survive parse/reconstruct ---
895 generated = obj.url()
896 assert "key=" in generated
897 # e2ee=no is NOT emitted because the default is True
898 assert "e2ee=" not in generated
899
900 parsed = NotifyPushover.parse_url(generated)
901 assert parsed is not None
902 assert parsed["encryption_key"] == valid_key
903 obj2 = NotifyPushover(**parsed)
904 assert obj2.encryption_key == valid_key
905 assert obj2.e2ee is True
906 assert obj.url_identifier == obj2.url_identifier
907
908 # --- URL round-trip with key + e2ee=no ---
909 generated_no = obj_no_e2ee.url()
910 assert "e2ee=no" in generated_no
911
912 parsed_no = NotifyPushover.parse_url(generated_no)
913 assert parsed_no is not None
914 obj3 = NotifyPushover(**parsed_no)
915 assert obj3.e2ee is False
916 assert obj3.encryption_key == valid_key
917
918 # --- Privacy URL hides the key ---
919 priv = obj.url(privacy=True)
920 assert valid_key not in priv
921 assert "key=" in priv
922
923 # --- Successful encrypted send (patch support flag + _encrypt_field so
924 # the test works in both minimal and qa tox environments) ---
925 _fake_enc = "FAKE_ENC_BASE64VALUE=="
926 mock_post.reset_mock()
927 with (
928 mock.patch.object(_pover_mod, "PUSHOVER_E2EE_SUPPORT", True),
929 mock.patch.object(obj, "_encrypt_field", return_value=_fake_enc),
930 ):
931 assert obj.send(body="Hello", title="World") is True
932 assert mock_post.call_count == 1
933 call_data = mock_post.call_args[1]["data"]
934 # The API must receive encrypted=1
935 assert call_data.get("encrypted") == 1
936 # message and title must be the fake-encrypted string
937 assert call_data["message"] == _fake_enc
938 assert call_data["title"] == _fake_enc
939
940 # --- Encrypted send with url and url_title fields ---
941 mock_post.reset_mock()
942 obj_url = NotifyPushover(
943 user_key=user_key,
944 token=token,
945 encryption_key=valid_key,
946 supplemental_url="https://example.com",
947 supplemental_url_title="Click",
948 )
949 with (
950 mock.patch.object(_pover_mod, "PUSHOVER_E2EE_SUPPORT", True),
951 mock.patch.object(obj_url, "_encrypt_field", return_value=_fake_enc),
952 ):
953 assert obj_url.send(body="body", title="title") is True
954 call_data = mock_post.call_args[1]["data"]
955 assert call_data.get("encrypted") == 1
956 assert call_data["url"] == _fake_enc
957 assert call_data["url_title"] == _fake_enc
958
959 # --- e2ee=False: plaintext send despite key being set ---
960 mock_post.reset_mock()
961 assert obj_no_e2ee.send(body="plaintext", title="ptitle") is True
962 call_data = mock_post.call_args[1]["data"]
963 assert "encrypted" not in call_data
964 assert call_data["message"] == "plaintext"
965 assert call_data["title"] == "ptitle"
966
967 # --- Fallback: PUSHOVER_E2EE_SUPPORT patched to False ---
968 mock_post.reset_mock()
969 orig_support = _pover_mod.PUSHOVER_E2EE_SUPPORT
970 _pover_mod.PUSHOVER_E2EE_SUPPORT = False
971 try:
972 # Should warn and fall back to sending unencrypted
973 result = obj.send(body="unenc body", title="unenc title")
974 assert result is True
975 assert mock_post.call_count == 1
976 call_data = mock_post.call_args[1]["data"]
977 # encrypted flag must NOT be set when we fell back
978 assert "encrypted" not in call_data
979 assert call_data["message"] == "unenc body"
980 finally:
981 _pover_mod.PUSHOVER_E2EE_SUPPORT = orig_support
982
983 # --- Crypto failure in _encrypt_field causes send() to return False ---
984 mock_post.reset_mock()
985 with (
986 mock.patch.object(_pover_mod, "PUSHOVER_E2EE_SUPPORT", True),
987 mock.patch.object(
988 obj, "_encrypt_field", side_effect=ValueError("boom")
989 ),
990 ):
991 result = obj.send(body="fail body", title="fail title")
992 assert result is False
993 assert mock_post.call_count == 0
994
995 # --- runtime_deps returns tuple containing 'cryptography' ---
996 deps = NotifyPushover.runtime_deps()
997 assert isinstance(deps, tuple)
998 assert "cryptography" in deps
999
1000
1001 def test_plugin_pushover_e2ee_field_encrypt():
1002 """Exercise _encrypt_field directly; skipped when cryptography absent."""
1003 import apprise.plugins.pushover as _pover_mod
1004
1005 pytest.importorskip("cryptography")
1006
1007 user_key = "u" * 30
1008 token = "a" * 30
1009 valid_key = "ab" * 32 # 64 hex chars = 32-byte AES-256 key
1010
1011 obj = NotifyPushover(
1012 user_key=user_key, token=token, encryption_key=valid_key
1013 )
1014 key_bytes = bytes.fromhex(valid_key)
1015
1016 # Happy path: should return a non-empty ASCII base64 string
1017 plaintext = "hello world"
1018 result = obj._encrypt_field(plaintext, key_bytes)
1019 assert isinstance(result, str)
1020 assert len(result) > 0
1021
1022 # Self-decryption round-trip: verify the blob layout and that
1023 # decrypting it reproduces the original plaintext.
1024 # This validates our AES + HMAC + gzip implementation matches
1025 # the Pushover spec (IV || ciphertext || HMAC, all base64 encoded).
1026 import base64 as _b64
1027 import gzip as _gzip
1028 import hmac as _hmac_std
1029
1030 from cryptography.hazmat.primitives import (
1031 hashes as _h,
1032 hmac as _hmac_crypt,
1033 padding as _pad,
1034 )
1035 from cryptography.hazmat.primitives.ciphers import (
1036 Cipher as _C,
1037 algorithms as _alg,
1038 modes as _mode,
1039 )
1040
1041 blob = _b64.b64decode(result)
1042 # Minimum: 16-byte IV + 16-byte AES block + 32-byte HMAC = 64 B
1043 assert len(blob) >= 64
1044
1045 iv = blob[:16]
1046 mac_from_blob = blob[-32:]
1047 ct = blob[16:-32]
1048
1049 # Verify HMAC-SHA256 over IV || ciphertext
1050 h = _hmac_crypt.HMAC(key_bytes, _h.SHA256())
1051 h.update(iv + ct)
1052 expected_mac = h.finalize()
1053 assert _hmac_std.compare_digest(mac_from_blob, expected_mac)
1054
1055 # AES-256-CBC decrypt
1056 cipher = _C(_alg.AES(key_bytes), _mode.CBC(iv))
1057 decryptor = cipher.decryptor()
1058 padded_plain = decryptor.update(ct) + decryptor.finalize()
1059
1060 # Remove PKCS7 padding
1061 unpadder = _pad.PKCS7(128).unpadder()
1062 compressed = unpadder.update(padded_plain) + unpadder.finalize()
1063
1064 # Gzip decompress and compare to original plaintext
1065 recovered = _gzip.decompress(compressed).decode("utf-8")
1066 assert recovered == plaintext
1067
1068 # Empty string is also a valid input (compressed + encrypted)
1069 result_empty = obj._encrypt_field("", key_bytes)
1070 assert isinstance(result_empty, str)
1071 assert len(result_empty) > 0
1072 blob_empty = _b64.b64decode(result_empty)
1073 assert len(blob_empty) >= 64
1074
1075 # Exception path: patch urandom to trigger the except/raise branch
1076 with (
1077 mock.patch.object(
1078 _pover_mod._os, "urandom", side_effect=OSError("rng failure")
1079 ),
1080 pytest.raises(OSError, match="rng failure"),
1081 ):
1082 obj._encrypt_field("boom", key_bytes)