Debian Codegraph @

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