Debian Codegraph @

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