Debian Codegraph @

tests/test_plugin_fcm.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 # Great Resources:
29 # - Dev/Legacy API:
30 # https://firebase.google.com/docs/cloud-messaging/http-server-ref
31 # - Legacy API (v1) -> OAuth
32 # - https://firebase.google.com/docs/cloud-messaging/migrate-v1
33
34 import json
35 import os
36 import sys
37 from unittest import mock
38
39 from helpers import AppriseURLTester
40 import pytest
41 import requests
42
43 from apprise import Apprise
44 from apprise.plugins.fcm import NotifyFCM
45
46 try:
47 from cryptography.exceptions import UnsupportedAlgorithm
48
49 from apprise.plugins.fcm.color import FCMColorManager
50 from apprise.plugins.fcm.common import FCM_MODES
51 from apprise.plugins.fcm.oauth import GoogleOAuth
52 from apprise.plugins.fcm.priority import FCM_PRIORITIES, FCMPriorityManager
53
54 except ImportError:
55 # No problem; there is no cryptography support
56 pass
57
58
59 # Disable logging for a cleaner testing output
60 import logging
61
62 logging.disable(logging.CRITICAL)
63
64 # Test files for KeyFile Directory
65 PRIVATE_KEYFILE_DIR = os.path.join(os.path.dirname(__file__), "var", "fcm")
66 FCM_KEYFILE = os.path.join(PRIVATE_KEYFILE_DIR, "service_account.json")
67
68
69 # Our Testing URLs
70 apprise_url_tests = (
71 (
72 "fcm://",
73 {
74 # We failed to identify any valid authentication
75 "instance": TypeError,
76 },
77 ),
78 (
79 "fcm://:@/",
80 {
81 # We failed to identify any valid authentication
82 "instance": TypeError,
83 },
84 ),
85 (
86 "fcm://project@%20%20/",
87 {
88 # invalid apikey
89 "instance": TypeError,
90 },
91 ),
92 (
93 "fcm://apikey/",
94 {
95 # no project id specified so we operate in legacy mode
96 "instance": NotifyFCM,
97 # but there are no targets specified so we return False
98 "notify_response": False,
99 },
100 ),
101 (
102 "fcm://apikey/device",
103 {
104 # Valid device
105 "instance": NotifyFCM,
106 "privacy_url": "fcm://a...y/device",
107 },
108 ),
109 (
110 "fcm://apikey/#topic",
111 {
112 # Valid topic
113 "instance": NotifyFCM,
114 "privacy_url": "fcm://a...y/%23topic",
115 },
116 ),
117 (
118 "fcm://apikey/device?mode=invalid",
119 {
120 # Valid device, invalid mode
121 "instance": TypeError,
122 },
123 ),
124 (
125 "fcm://apikey/#topic1/device/%20/",
126 {
127 # Valid topic, valid device, and invalid entry
128 "instance": NotifyFCM,
129 },
130 ),
131 (
132 "fcm://apikey?to=#topic1,device",
133 {
134 # Test to=
135 "instance": NotifyFCM,
136 },
137 ),
138 (
139 "fcm://?apikey=abc123&to=device",
140 {
141 # Test apikey= to=
142 "instance": NotifyFCM,
143 },
144 ),
145 (
146 "fcm://?apikey=abc123&to=device&image=yes",
147 {
148 # Test image boolean
149 "instance": NotifyFCM,
150 },
151 ),
152 (
153 "fcm://?apikey=abc123&to=device&color=no",
154 {
155 # Disable colors
156 "instance": NotifyFCM,
157 },
158 ),
159 (
160 "fcm://?apikey=abc123&to=device&color=aabbcc",
161 {
162 # custom colors
163 "instance": NotifyFCM,
164 },
165 ),
166 (
167 (
168 "fcm://?apikey=abc123&to=device"
169 "&image_url=http://example.com/interesting.jpg"
170 ),
171 {
172 # Test image_url
173 "instance": NotifyFCM
174 },
175 ),
176 (
177 (
178 "fcm://?apikey=abc123&to=device"
179 "&image_url=http://example.com/interesting.jpg&image=no"
180 ),
181 {
182 # Test image_url but set to no
183 "instance": NotifyFCM
184 },
185 ),
186 (
187 "fcm://?apikey=abc123&to=device&+key=value&+key2=value2",
188 {
189 # Test apikey= to= and data arguments
190 "instance": NotifyFCM,
191 },
192 ),
193 (
194 "fcm://%20?to=device&keyfile=/invalid/path",
195 {
196 # invalid Project ID
197 "instance": TypeError,
198 },
199 ),
200 (
201 "fcm://project_id?to=device&keyfile=/invalid/path",
202 {
203 # Test to= and auto-detection of OAuth mode
204 "instance": NotifyFCM,
205 # we'll fail to send our notification as a result
206 "response": False,
207 },
208 ),
209 (
210 "fcm://?to=device&project=project_id&keyfile=/invalid/path",
211 {
212 # Test project= & to= and auto detection of OAuth mode
213 "instance": NotifyFCM,
214 # we'll fail to send our notification as a result
215 "response": False,
216 },
217 ),
218 (
219 "fcm://project_id?to=device&mode=oauth2",
220 {
221 # no keyfile was specified
222 "instance": TypeError,
223 },
224 ),
225 (
226 "fcm://project_id?to=device&mode=oauth2&keyfile=/invalid/path",
227 {
228 # Same test as above except we explicitly set our oauth2 mode
229 # Test to= and auto-detection of OAuth mode
230 "instance": NotifyFCM,
231 # we'll fail to send our notification as a result
232 "response": False,
233 },
234 ),
235 (
236 "fcm://apikey/#topic1/device/?mode=legacy",
237 {
238 "instance": NotifyFCM,
239 # throw a bizarre code forcing us to fail to look it up
240 "response": False,
241 "requests_response_code": 999,
242 },
243 ),
244 (
245 "fcm://apikey/#topic1/device/?mode=legacy",
246 {
247 "instance": NotifyFCM,
248 # Throws a series of i/o exceptions with this flag
249 # is set and tests that we gracefully handle them
250 "test_requests_exceptions": True,
251 },
252 ),
253 (
254 "fcm://project/#topic1/device/?mode=oauth2&keyfile=file://{}".format(
255 os.path.join(
256 os.path.dirname(__file__), "var", "fcm", "service_account.json"
257 )
258 ),
259 {
260 "instance": NotifyFCM,
261 # throw a bizarre code forcing us to fail to look it up
262 "response": False,
263 "requests_response_code": 999,
264 },
265 ),
266 (
267 "fcm://projectid/#topic1/device/?mode=oauth2&keyfile=file://{}".format(
268 os.path.join(
269 os.path.dirname(__file__), "var", "fcm", "service_account.json"
270 )
271 ),
272 {
273 "instance": NotifyFCM,
274 # Throws a series of connection and transfer exceptions when
275 # this flag is set and tests that we gracefully handle them
276 "test_requests_exceptions": True,
277 },
278 ),
279 )
280
281
282 @pytest.fixture
283 def mock_post(mocker):
284 """Prepare a good OAuth mock response."""
285
286 mock_thing = mocker.patch("requests.post")
287
288 response = mock.Mock()
289 response.content = json.dumps(
290 {
291 "access_token": "ya29.c.abcd",
292 "expires_in": 3599,
293 "token_type": "Bearer",
294 }
295 )
296 response.status_code = requests.codes.ok
297 mock_thing.return_value = response
298
299 return mock_thing
300
301
302 @pytest.fixture
303 def mock_post_legacy(mocker):
304 """Prepare a good legacy mock response."""
305
306 mock_thing = mocker.patch("requests.post")
307
308 response = mock.Mock()
309 response.status_code = requests.codes.ok
310 response.content = b""
311 mock_thing.return_value = response
312
313 return mock_thing
314
315
316 @pytest.mark.skipif(
317 "cryptography" not in sys.modules, reason="Requires cryptography"
318 )
319 def test_plugin_fcm_urls():
320 """NotifyFCM() Apprise URLs."""
321
322 # Run our general tests
323 AppriseURLTester(tests=apprise_url_tests).run_all()
324
325
326 @pytest.mark.skipif(
327 "cryptography" not in sys.modules, reason="Requires cryptography"
328 )
329 def test_plugin_fcm_legacy_default(mock_post_legacy):
330 """NotifyFCM() Legacy/APIKey default checks."""
331
332 # A valid Legacy URL
333 obj = Apprise.instantiate(
334 "fcm://abc123/device/"
335 "?+key=value&+key2=value2"
336 "&image_url=https://example.com/interesting.png"
337 )
338
339 # Send our notification
340 assert obj.notify("test") is True
341
342 # Test our call count
343 assert mock_post_legacy.call_count == 1
344 assert (
345 mock_post_legacy.call_args_list[0][0][0]
346 == "https://fcm.googleapis.com/fcm/send"
347 )
348
349 payload = mock_post_legacy.mock_calls[0][2]
350 data = json.loads(payload["data"])
351 assert "data" in data
352 assert isinstance(data, dict)
353 assert "key" in data["data"]
354 assert data["data"]["key"] == "value"
355 assert "key2" in data["data"]
356 assert data["data"]["key2"] == "value2"
357
358 assert "notification" in data
359 assert isinstance(data["notification"], dict)
360 assert "notification" in data["notification"]
361 assert isinstance(data["notification"]["notification"], dict)
362 assert "image" in data["notification"]["notification"]
363 assert (
364 data["notification"]["notification"]["image"]
365 == "https://example.com/interesting.png"
366 )
367
368
369 @pytest.mark.skipif(
370 "cryptography" not in sys.modules, reason="Requires cryptography"
371 )
372 def test_plugin_fcm_legacy_priorities(mock_post_legacy):
373 """NotifyFCM() Legacy/APIKey priorities checks."""
374
375 obj = Apprise.instantiate("fcm://abc123/device/?priority=low")
376 assert mock_post_legacy.call_count == 0
377
378 # Send our notification
379 assert obj.notify(title="title", body="body") is True
380
381 # Test our call count
382 assert mock_post_legacy.call_count == 1
383 assert (
384 mock_post_legacy.call_args_list[0][0][0]
385 == "https://fcm.googleapis.com/fcm/send"
386 )
387
388 payload = mock_post_legacy.mock_calls[0][2]
389 data = json.loads(payload["data"])
390 assert "data" not in data
391 assert "notification" in data
392 assert isinstance(data["notification"], dict)
393 assert "notification" in data["notification"]
394 assert isinstance(data["notification"]["notification"], dict)
395 assert "image" not in data["notification"]["notification"]
396 assert "priority" in data
397
398 # legacy can only switch between high/low
399 assert data["priority"] == "normal"
400
401
402 @pytest.mark.skipif(
403 "cryptography" not in sys.modules, reason="Requires cryptography"
404 )
405 def test_plugin_fcm_legacy_no_colors(mock_post_legacy):
406 """NotifyFCM() Legacy/APIKey `color=no` checks."""
407
408 obj = Apprise.instantiate("fcm://abc123/device/?color=no")
409 assert mock_post_legacy.call_count == 0
410
411 # Send our notification
412 assert obj.notify(title="title", body="body") is True
413
414 # Test our call count
415 assert mock_post_legacy.call_count == 1
416 assert (
417 mock_post_legacy.call_args_list[0][0][0]
418 == "https://fcm.googleapis.com/fcm/send"
419 )
420
421 payload = mock_post_legacy.mock_calls[0][2]
422 data = json.loads(payload["data"])
423 assert "data" not in data
424 assert "notification" in data
425 assert isinstance(data["notification"], dict)
426 assert "notification" in data["notification"]
427 assert isinstance(data["notification"]["notification"], dict)
428 assert "image" not in data["notification"]["notification"]
429 assert "color" not in data["notification"]["notification"]
430
431
432 @pytest.mark.skipif(
433 "cryptography" not in sys.modules, reason="Requires cryptography"
434 )
435 def test_plugin_fcm_legacy_colors(mock_post_legacy):
436 """NotifyFCM() Legacy/APIKey colors checks."""
437
438 obj = Apprise.instantiate("fcm://abc123/device/?color=AA001b")
439 assert mock_post_legacy.call_count == 0
440
441 # Send our notification
442 assert obj.notify(title="title", body="body") is True
443
444 # Test our call count
445 assert mock_post_legacy.call_count == 1
446 assert (
447 mock_post_legacy.call_args_list[0][0][0]
448 == "https://fcm.googleapis.com/fcm/send"
449 )
450
451 payload = mock_post_legacy.mock_calls[0][2]
452 data = json.loads(payload["data"])
453 assert "data" not in data
454 assert "notification" in data
455 assert isinstance(data["notification"], dict)
456 assert "notification" in data["notification"]
457 assert isinstance(data["notification"]["notification"], dict)
458 assert "image" not in data["notification"]["notification"]
459 assert "color" in data["notification"]["notification"]
460 assert data["notification"]["notification"]["color"] == "#aa001b"
461
462
463 @pytest.mark.skipif(
464 "cryptography" not in sys.modules, reason="Requires cryptography"
465 )
466 def test_plugin_fcm_oauth_default(mock_post):
467 """
468 NotifyFCM() general OAuth checks - success.
469 Test using a valid Project ID and key file.
470 """
471
472 obj = Apprise.instantiate(
473 f"fcm://mock-project-id/device/#topic/?keyfile={FCM_KEYFILE}"
474 )
475
476 # send our notification
477 assert obj.notify("test") is True
478
479 # Test our call count
480 assert mock_post.call_count == 3
481 assert (
482 mock_post.call_args_list[0][0][0]
483 == "https://accounts.google.com/o/oauth2/token"
484 )
485 assert (
486 mock_post.call_args_list[1][0][0]
487 == "https://fcm.googleapis.com/v1/projects/mock-project-id/messages:send"
488 )
489 assert (
490 mock_post.call_args_list[2][0][0]
491 == "https://fcm.googleapis.com/v1/projects/mock-project-id/messages:send"
492 )
493
494
495 @pytest.mark.skipif(
496 "cryptography" not in sys.modules, reason="Requires cryptography"
497 )
498 def test_plugin_fcm_oauth_invalid_project_id(mock_post):
499 """NotifyFCM() OAuth checks, with invalid project id."""
500
501 # Test having a valid keyfile, but not a valid project id match.
502 obj = Apprise.instantiate(
503 f"fcm://invalid_project_id/device/?keyfile={FCM_KEYFILE}"
504 )
505
506 # we'll fail as a result
507 assert obj.notify("test") is False
508
509 # Test our call count
510 assert mock_post.call_count == 0
511
512
513 @pytest.mark.skipif(
514 "cryptography" not in sys.modules, reason="Requires cryptography"
515 )
516 def test_plugin_fcm_oauth_keyfile_error(mock_post):
517 """NotifyFCM() OAuth checks, while unable to read key file."""
518
519 # Now we test using a valid Project ID but we can't open our file
520 obj = Apprise.instantiate(
521 f"fcm://mock-project-id/device/?keyfile={FCM_KEYFILE}"
522 )
523
524 with mock.patch("builtins.open", side_effect=OSError):
525 # we'll fail as a result
526 assert obj.notify("test") is False
527
528 # Test our call count
529 assert mock_post.call_count == 0
530
531
532 @pytest.mark.skipif(
533 "cryptography" not in sys.modules, reason="Requires cryptography"
534 )
535 def test_plugin_fcm_oauth_data_parameters(mock_post):
536 """NotifyFCM() OAuth checks, success.
537
538 Test using a valid Project ID and data parameters.
539 """
540
541 obj = Apprise.instantiate(
542 f"fcm://mock-project-id/device/#topic/?keyfile={FCM_KEYFILE}"
543 "&+key=value&+key2=value2"
544 "&image_url=https://example.com/interesting.png"
545 )
546 assert mock_post.call_count == 0
547
548 # send our notification
549 assert obj.notify("test") is True
550
551 # Test our call count
552 assert mock_post.call_count == 3
553 assert (
554 mock_post.call_args_list[0][0][0]
555 == "https://accounts.google.com/o/oauth2/token"
556 )
557
558 assert (
559 mock_post.call_args_list[1][0][0]
560 == "https://fcm.googleapis.com/v1/projects/mock-project-id/messages:send"
561 )
562 payload = mock_post.mock_calls[1][2]
563 data = json.loads(payload["data"])
564 assert "message" in data
565 assert isinstance(data["message"], dict)
566 assert "data" in data["message"]
567 assert isinstance(data["message"]["data"], dict)
568 assert "key" in data["message"]["data"]
569 assert data["message"]["data"]["key"] == "value"
570 assert "key2" in data["message"]["data"]
571 assert data["message"]["data"]["key2"] == "value2"
572
573 assert "notification" in data["message"]
574 assert isinstance(data["message"]["notification"], dict)
575 assert "image" in data["message"]["notification"]
576 assert (
577 data["message"]["notification"]["image"]
578 == "https://example.com/interesting.png"
579 )
580
581 assert (
582 mock_post.call_args_list[2][0][0]
583 == "https://fcm.googleapis.com/v1/projects/mock-project-id/messages:send"
584 )
585
586 payload = mock_post.mock_calls[2][2]
587 data = json.loads(payload["data"])
588 assert "message" in data
589 assert isinstance(data["message"], dict)
590 assert "data" in data["message"]
591 assert isinstance(data["message"]["data"], dict)
592 assert "key" in data["message"]["data"]
593 assert data["message"]["data"]["key"] == "value"
594 assert "key2" in data["message"]["data"]
595 assert data["message"]["data"]["key2"] == "value2"
596
597 assert "notification" in data["message"]
598 assert isinstance(data["message"]["notification"], dict)
599 assert "image" in data["message"]["notification"]
600 assert (
601 data["message"]["notification"]["image"]
602 == "https://example.com/interesting.png"
603 )
604
605
606 @pytest.mark.skipif(
607 "cryptography" not in sys.modules, reason="Requires cryptography"
608 )
609 def test_plugin_fcm_oauth_priorities(mock_post):
610 """Verify priorities work as intended."""
611
612 obj = Apprise.instantiate(
613 f"fcm://mock-project-id/device/?keyfile={FCM_KEYFILE}&priority=high"
614 )
615 assert mock_post.call_count == 0
616
617 # Send our notification
618 assert obj.notify(title="title", body="body") is True
619
620 # Test our call count
621 assert mock_post.call_count == 2
622 assert (
623 mock_post.call_args_list[0][0][0]
624 == "https://accounts.google.com/o/oauth2/token"
625 )
626
627 assert (
628 mock_post.call_args_list[1][0][0]
629 == "https://fcm.googleapis.com/v1/projects/mock-project-id/messages:send"
630 )
631 payload = mock_post.mock_calls[1][2]
632 data = json.loads(payload["data"])
633 assert "message" in data
634 assert isinstance(data["message"], dict)
635 assert "data" not in data["message"]
636 assert "notification" in data["message"]
637 assert isinstance(data["message"]["notification"], dict)
638 assert "image" not in data["message"]["notification"]
639 assert data["message"]["apns"]["headers"]["apns-priority"] == "10"
640 assert data["message"]["webpush"]["headers"]["Urgency"] == "high"
641 assert data["message"]["android"]["priority"] == "HIGH"
642
643
644 @pytest.mark.skipif(
645 "cryptography" not in sys.modules, reason="Requires cryptography"
646 )
647 def test_plugin_fcm_oauth_no_colors(mock_post):
648 """Verify `color=no` work as intended."""
649
650 obj = Apprise.instantiate(
651 f"fcm://mock-project-id/device/?keyfile={FCM_KEYFILE}&color=no"
652 )
653 assert mock_post.call_count == 0
654
655 # Send our notification
656 assert obj.notify(title="title", body="body") is True
657
658 # Test our call count
659 assert mock_post.call_count == 2
660 assert (
661 mock_post.call_args_list[0][0][0]
662 == "https://accounts.google.com/o/oauth2/token"
663 )
664
665 assert (
666 mock_post.call_args_list[1][0][0]
667 == "https://fcm.googleapis.com/v1/projects/mock-project-id/messages:send"
668 )
669 payload = mock_post.mock_calls[1][2]
670 data = json.loads(payload["data"])
671 assert "message" in data
672 assert isinstance(data["message"], dict)
673 assert "data" not in data["message"]
674 assert "notification" in data["message"]
675 assert isinstance(data["message"]["notification"], dict)
676 assert "color" not in data["message"]["notification"]
677
678
679 @pytest.mark.skipif(
680 "cryptography" not in sys.modules, reason="Requires cryptography"
681 )
682 def test_plugin_fcm_oauth_colors(mock_post):
683 """Verify colors work as intended."""
684
685 obj = Apprise.instantiate(
686 f"fcm://mock-project-id/device/?keyfile={FCM_KEYFILE}&color=#12AAbb"
687 )
688 assert mock_post.call_count == 0
689
690 # Send our notification
691 assert obj.notify(title="title", body="body") is True
692
693 # Test our call count
694 assert mock_post.call_count == 2
695 assert (
696 mock_post.call_args_list[0][0][0]
697 == "https://accounts.google.com/o/oauth2/token"
698 )
699
700 assert (
701 mock_post.call_args_list[1][0][0]
702 == "https://fcm.googleapis.com/v1/projects/mock-project-id/messages:send"
703 )
704 payload = mock_post.mock_calls[1][2]
705 data = json.loads(payload["data"])
706 assert "message" in data
707 assert isinstance(data["message"], dict)
708 assert "data" not in data["message"]
709 assert "notification" in data["message"]
710 assert isinstance(data["message"]["notification"], dict)
711 assert "color" in data["message"]["android"]["notification"]
712 assert data["message"]["android"]["notification"]["color"] == "#12aabb"
713
714
715 @pytest.mark.skipif(
716 "cryptography" not in sys.modules, reason="Requires cryptography"
717 )
718 def test_plugin_fcm_keyfile_parse_default(mock_post):
719 """NotifyFCM() KeyFile Tests."""
720
721 oauth = GoogleOAuth()
722 # We can not get an Access Token without content loaded
723 assert oauth.access_token is None
724
725 # Load our content
726 assert oauth.load(FCM_KEYFILE) is True
727 assert oauth.access_token is not None
728
729 # Test our call count
730 assert mock_post.call_count == 1
731 assert (
732 mock_post.call_args_list[0][0][0]
733 == "https://accounts.google.com/o/oauth2/token"
734 )
735
736 mock_post.reset_mock()
737
738 # a second call uses cache since our token hasn't expired yet
739 assert oauth.access_token is not None
740 assert mock_post.call_count == 0
741
742
743 @pytest.mark.skipif(
744 "cryptography" not in sys.modules, reason="Requires cryptography"
745 )
746 def test_plugin_fcm_keyfile_parse_no_expiry(mock_post):
747 """Test case without `expires_in` entry."""
748
749 mock_post.return_value.content = json.dumps(
750 {
751 "access_token": "ya29.c.abcd",
752 "token_type": "Bearer",
753 }
754 )
755
756 oauth = GoogleOAuth()
757 assert oauth.load(FCM_KEYFILE) is True
758 assert oauth.access_token is not None
759
760 # Test our call count
761 assert mock_post.call_count == 1
762 assert (
763 mock_post.call_args_list[0][0][0]
764 == "https://accounts.google.com/o/oauth2/token"
765 )
766
767
768 @pytest.mark.skipif(
769 "cryptography" not in sys.modules, reason="Requires cryptography"
770 )
771 def test_plugin_fcm_keyfile_parse_user_agent(mock_post):
772 """Test case with `user-agent` override."""
773
774 oauth = GoogleOAuth(user_agent="test-agent-override")
775 assert oauth.load(FCM_KEYFILE) is True
776 assert oauth.access_token is not None
777 assert mock_post.call_count == 1
778 assert (
779 mock_post.call_args_list[0][0][0]
780 == "https://accounts.google.com/o/oauth2/token"
781 )
782
783
784 @pytest.mark.skipif(
785 "cryptography" not in sys.modules, reason="Requires cryptography"
786 )
787 def test_plugin_fcm_keyfile_parse_keyfile_failures(mock_post: mock.Mock):
788 """Test some errors that can get thrown when trying to handle the
789 `service_account.json` file."""
790
791 # Now we test a case where we can't access the file we've been pointed to:
792 oauth = GoogleOAuth()
793 with mock.patch("builtins.open", side_effect=OSError):
794 # We will fail to retrieve our Access Token
795 assert oauth.load(FCM_KEYFILE) is False
796 assert oauth.access_token is None
797
798 oauth = GoogleOAuth()
799 with mock.patch("json.loads", side_effect=([],)):
800 # We will fail to retrieve our Access Token since we did not parse
801 # a dictionary
802 assert oauth.load(FCM_KEYFILE) is False
803 assert oauth.access_token is None
804
805 # Case where we can't load the PEM key:
806 oauth = GoogleOAuth()
807 with mock.patch(
808 "cryptography.hazmat.primitives.serialization.load_pem_private_key",
809 side_effect=ValueError(""),
810 ):
811 assert oauth.load(FCM_KEYFILE) is False
812 assert oauth.access_token is None
813
814 # Case where we can't load the PEM key:
815 oauth = GoogleOAuth()
816 with mock.patch(
817 "cryptography.hazmat.primitives.serialization.load_pem_private_key",
818 side_effect=TypeError(""),
819 ):
820 assert oauth.load(FCM_KEYFILE) is False
821 assert oauth.access_token is None
822
823 # Case where we can't load the PEM key:
824 oauth = GoogleOAuth()
825 with mock.patch(
826 "cryptography.hazmat.primitives.serialization.load_pem_private_key",
827 side_effect=UnsupportedAlgorithm(""),
828 ):
829 # Note: This test should be te
830 assert oauth.load(FCM_KEYFILE) is False
831 assert oauth.access_token is None
832
833 # Verify that not a single call to the web escaped the test harness.
834 assert mock_post.mock_calls == []
835
836
837 @pytest.mark.skipif(
838 "cryptography" not in sys.modules, reason="Requires cryptography"
839 )
840 def test_plugin_fcm_keyfile_parse_token_failures(mock_post):
841 """Test some web errors that can occur when speaking upstream with Google
842 to get our token generated."""
843
844 mock_post.return_value.status_code = requests.codes.internal_server_error
845 mock_post.return_value.content = b""
846
847 oauth = GoogleOAuth()
848 assert oauth.load(FCM_KEYFILE) is True
849
850 # We'll fail due to an bad web response
851 assert oauth.access_token is None
852
853 # Return our status code to how it was
854 mock_post.return_value.status_code = requests.codes.ok
855
856 # No access token
857 bad_response_1 = mock.Mock()
858 bad_response_1.content = json.dumps(
859 {
860 "expires_in": 3599,
861 "token_type": "Bearer",
862 }
863 )
864
865 # Invalid JSON
866 bad_response_2 = mock.Mock()
867 bad_response_2.content = "{"
868
869 mock_post.return_value = None
870 # Throw an exception on the first call to requests.post()
871 for side_effect in (
872 requests.RequestException(),
873 [bad_response_1],
874 [bad_response_2],
875 ):
876 mock_post.side_effect = side_effect
877
878 # Test all of our bad side effects
879 oauth = GoogleOAuth()
880 assert oauth.load(FCM_KEYFILE) is True
881
882 # We'll fail due to an bad web response
883 assert oauth.access_token is None
884
885
886 @pytest.mark.skipif(
887 "cryptography" not in sys.modules, reason="Requires cryptography"
888 )
889 def test_plugin_fcm_bad_keyfile_parse():
890 """NotifyFCM() KeyFile Bad Service Account Type Tests."""
891
892 path = os.path.join(PRIVATE_KEYFILE_DIR, "service_account-bad-type.json")
893 oauth = GoogleOAuth()
894 assert oauth.load(path) is False
895
896
897 @pytest.mark.skipif(
898 "cryptography" not in sys.modules, reason="Requires cryptography"
899 )
900 def test_plugin_fcm_keyfile_missing_entries_parse(tmpdir):
901 """NotifyFCM() KeyFile Missing Entries Test."""
902
903 # Prepare a base keyfile reference to use
904 path = os.path.join(PRIVATE_KEYFILE_DIR, "service_account.json")
905 with open(path, encoding="utf-8") as fp:
906 content = json.loads(fp.read())
907
908 path = tmpdir.join("fcm_keyfile.json")
909
910 # Test that we fail to load if the following keys are missing:
911 for entry in (
912 "client_email",
913 "private_key_id",
914 "private_key",
915 "type",
916 "project_id",
917 ):
918 # Ensure the key actually exists in our file
919 assert entry in content
920
921 # Create a copy of our content
922 content_copy = content.copy()
923
924 # Remove our entry we expect to validate against
925 del content_copy[entry]
926 assert entry not in content_copy
927
928 path.write(json.dumps(content_copy))
929
930 oauth = GoogleOAuth()
931 assert oauth.load(str(path)) is False
932
933 # Now write ourselves a bad JSON file
934 path.write("{")
935 oauth = GoogleOAuth()
936 assert oauth.load(str(path)) is False
937
938
939 @pytest.mark.skipif(
940 "cryptography" not in sys.modules, reason="Requires cryptography"
941 )
942 def test_plugin_fcm_priority_manager():
943 """NotifyFCM() FCMPriorityManager() Testing."""
944
945 for mode in FCM_MODES:
946 for priority in FCM_PRIORITIES:
947 instance = FCMPriorityManager(mode, priority)
948 assert isinstance(instance.payload(), dict)
949 # Verify it's not empty
950 assert bool(instance)
951 assert instance.payload()
952 assert str(instance) == priority
953
954 # We do not have to set a priority
955 instance = FCMPriorityManager(mode)
956 assert isinstance(instance.payload(), dict)
957
958 # Dictionary is empty though
959 assert not bool(instance)
960 assert not instance.payload()
961 assert str(instance) == ""
962
963 with pytest.raises(TypeError):
964 instance = FCMPriorityManager(mode, "invalid")
965
966 with pytest.raises(TypeError):
967 instance = FCMPriorityManager("invald", "high")
968
969 # mode validation is done at the higher NotifyFCM() level so
970 # it is not tested here (not required)
971
972
973 @pytest.mark.skipif(
974 "cryptography" not in sys.modules, reason="Requires cryptography"
975 )
976 def test_plugin_fcm_color_manager():
977 """NotifyFCM() FCMColorManager() Testing."""
978
979 # No colors
980 instance = FCMColorManager("no")
981 assert bool(instance) is False
982 assert instance.get() is None
983 # We'll return that we are not defined
984 assert str(instance) == "no"
985
986 # Asset colors
987 instance = FCMColorManager("yes")
988 assert isinstance(instance.get(), str)
989 # Output: #rrggbb
990 assert len(instance.get()) == 7
991 # Starts with has symbol
992 assert instance.get()[0] == "#"
993 # We'll return that we are defined but using default configuration
994 assert str(instance) == "yes"
995
996 # We will be `true` because we can acquire a color based on what was
997 # passed in
998 assert bool(instance)
999
1000 # Custom color
1001 instance = FCMColorManager("#A2B3A4")
1002 assert isinstance(instance.get(), str)
1003 assert instance.get() == "#a2b3a4"
1004 assert bool(instance)
1005 # str() response does not include hashtag
1006 assert str(instance) == "a2b3a4"
1007
1008 # Custom color (no hashtag)
1009 instance = FCMColorManager("A2B3A4")
1010 assert isinstance(instance.get(), str)
1011 # Hashtag is always part of output
1012 assert instance.get() == "#a2b3a4"
1013 assert bool(instance)
1014 # str() response does not include hashtag
1015 assert str(instance) == "a2b3a4"
1016
1017 # Custom color (no hashtag) but only using 3 letter rgb values
1018 instance = FCMColorManager("AC4")
1019 assert isinstance(instance.get(), str)
1020 # Hashtag is always part of output
1021 assert instance.get() == "#aacc44"
1022 assert bool(instance)
1023 # str() response does not include hashtag
1024 assert str(instance) == "aacc44"
1025
1026
1027 @pytest.mark.skipif(
1028 "cryptography" in sys.modules,
1029 reason="Requires that cryptography NOT be installed",
1030 )
1031 def test_plugin_fcm_cryptography_import_error():
1032 """NotifyFCM Cryptography loading failure."""
1033
1034 # Prepare a base keyfile reference to use
1035 path = os.path.join(PRIVATE_KEYFILE_DIR, "service_account.json")
1036
1037 # Attempt to instantiate our object
1038 obj = Apprise.instantiate(
1039 f"fcm://mock-project-id/device/#topic/?keyfile={path!s}"
1040 )
1041
1042 # It's not possible because our cryptography depedancy is missing
1043 assert obj is None
1044
1045
1046 @pytest.mark.skipif(
1047 "cryptography" not in sys.modules, reason="Requires cryptography"
1048 )
1049 @mock.patch("requests.post")
1050 def test_plugin_fcm_edge_cases(mock_post):
1051 """NotifyFCM() Edge Cases."""
1052
1053 # Prepare a good response
1054 response = mock.Mock()
1055 response.status_code = requests.codes.ok
1056 response.content = b""
1057 mock_post.return_value = response
1058
1059 # this tests an edge case where verify if the data_kwargs is a dictionary
1060 # or not. Below, we don't even define it, so it will be None (causing
1061 # the check to go). We'll still correctly instantiate a plugin:
1062 obj = NotifyFCM("project", "api:123", targets="device")
1063 assert obj is not None