Debian Codegraph @

tests/test_plugin_ringcentral.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 # Disable logging for a cleaner testing output
29 import logging
30 import os
31 from unittest import mock
32
33 from helpers import AppriseURLTester
34 import pytest
35 import requests
36
37 from apprise import Apprise, AppriseAttachment
38 from apprise.plugins.ringcentral import (
39 NotifyRingCentral,
40 RingCentralAuthMode,
41 RingCentralEnvironment,
42 )
43
44 logging.disable(logging.CRITICAL)
45
46 # Path to static test attachment files
47 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
48
49 # Shared valid credential constants used across tests
50 CLIENT_ID = "client_id"
51 CLIENT_SECRET = "client-secret"
52 SOURCE = "+15551233456"
53 JWT_TOKEN = "a" * 80
54
55
56 # A realistic RingCentral token response (covers both auth and SMS fields)
57 GOOD_RESPONSE = {
58 # OAuth token fields
59 "access_token": "abc123",
60 "token_type": "bearer",
61 "expires_in": 3600,
62 "scope": "Faxes SMS TeamMessaging A2PSMS",
63 "owner_id": "123",
64 "endpoint_id": "akfJbWJYQ7GEUev2CaR37k",
65 # SMS response fields
66 "uri": (
67 "https://platform.ringcentral.com/restapi/v1.0/"
68 "account/123/extension/123/message-store/123"
69 ),
70 "id": 123,
71 "to": [{"phoneNumber": "+14223453486", "name": "Chris"}],
72 "from": {"phoneNumber": "+14223452386", "name": "Chris"},
73 "type": "SMS",
74 "messageStatus": "Queued",
75 }
76
77 # Our Testing URLs
78 apprise_url_tests = (
79 (
80 "ringc://",
81 {
82 # No credentials at all
83 "instance": TypeError,
84 },
85 ),
86 (
87 "ringc://:@/",
88 {
89 # No credentials at all
90 "instance": TypeError,
91 },
92 ),
93 (
94 "ringc://password@client_id/18005554321",
95 {
96 # No client secret
97 "instance": TypeError,
98 },
99 ),
100 (
101 "ringc://18005554321:jwt{}@client_id".format("a" * 60),
102 {
103 # JWT provided but no client secret
104 "instance": TypeError,
105 },
106 ),
107 (
108 "ringc://18005554321:jwt{}@%21%21%21/secret".format("b" * 60),
109 {
110 # Invalid client_id
111 "instance": TypeError,
112 },
113 ),
114 (
115 "ringc://18005554321:jwt{}@client_id/%21%21%21/".format("c" * 60),
116 {
117 # Invalid client secret
118 "instance": TypeError,
119 },
120 ),
121 (
122 "ringc://18005554321:password@client_id/secret?mode=invalid",
123 {
124 # Invalid auth mode
125 "instance": TypeError,
126 },
127 ),
128 (
129 "ringc://18005554321:password@client_id/secret?env=invalid",
130 {
131 # Invalid environment
132 "instance": TypeError,
133 },
134 ),
135 (
136 "ringc://18005554321:jwt=@client_id/secret?mode=jwt",
137 {
138 # Invalid JWT token (contains disallowed chars)
139 "instance": TypeError,
140 },
141 ),
142 # Valid JWT mode with explicit ?mode=jwt
143 (
144 "ringc://18005554321:jwt{}@client_id/secret/1555123456?mode=jwt".format(
145 "c" * 60
146 ),
147 {
148 "instance": NotifyRingCentral,
149 "requests_response_text": GOOD_RESPONSE,
150 "privacy_url": "ringc://18005554321:[email protected]/****/1555123456/"
151 "?env=prod&mode=jwt",
152 },
153 ),
154 # Valid JWT mode auto-detected from token length (>60 chars)
155 (
156 "ringc://18005554321:jwt{}@client_id/secret/1555123456".format(
157 "c" * 60
158 ),
159 {
160 "instance": NotifyRingCentral,
161 "requests_response_text": GOOD_RESPONSE,
162 },
163 ),
164 # Invalid phone number in targets (gets dropped, loopback used)
165 (
166 "ringc://18005554321:jwt{}@client_id/secret/245/?env=sandbox".format(
167 "c" * 60
168 ),
169 {
170 "instance": NotifyRingCentral,
171 "requests_response_text": GOOD_RESPONSE,
172 },
173 ),
174 # BASIC auth mode
175 (
176 "ringc://18005554321:password@client_id/secret",
177 {
178 "instance": NotifyRingCentral,
179 "requests_response_text": GOOD_RESPONSE,
180 },
181 ),
182 # Query param form with ?token= and ?secret=
183 (
184 "ringc://_?token={}&secret={}&from={}".format(
185 "a" * 8, "b" * 16, "5" * 11
186 ),
187 {
188 "requests_response_text": GOOD_RESPONSE,
189 "instance": NotifyRingCentral,
190 },
191 ),
192 # Query param form with ?source= instead of ?from=
193 (
194 "ringc://_?token={}&secret={}&source={}".format(
195 "a" * 8, "b" * 16, "5" * 11
196 ),
197 {
198 "requests_response_text": GOOD_RESPONSE,
199 "instance": NotifyRingCentral,
200 },
201 ),
202 # Query param form with ?to= target
203 (
204 "ringc://_?token={}&secret={}&from={}&to={}".format(
205 "a" * 8, "b" * 16, "5" * 11, "7" * 13
206 ),
207 {
208 "requests_response_text": GOOD_RESPONSE,
209 "instance": NotifyRingCentral,
210 },
211 ),
212 # HTTP 999 (unknown response code)
213 (
214 "ringc://18005554321:jwt{}@client_id/secret".format("c" * 60),
215 {
216 "instance": NotifyRingCentral,
217 "requests_response_text": GOOD_RESPONSE,
218 "response": False,
219 "requests_response_code": 999,
220 },
221 ),
222 # RequestException handling
223 (
224 "ringc://18005554321:jwt{}@client_id/secret".format("c" * 60),
225 {
226 "instance": NotifyRingCentral,
227 "requests_response_text": GOOD_RESPONSE,
228 "test_requests_exceptions": True,
229 },
230 ),
231 )
232
233
234 def test_plugin_ringc_urls():
235 """NotifyRingCentral() Apprise URLs."""
236 AppriseURLTester(tests=apprise_url_tests).run_all()
237
238
239 @mock.patch("requests.post")
240 def test_plugin_ringc_init(mock_post):
241 """NotifyRingCentral() init edge cases."""
242
243 def _mk_resp(d, code=requests.codes.ok):
244 r = mock.Mock()
245 r.status_code = code
246 r.content = d
247 return r
248
249 mock_post.return_value = _mk_resp(b"{}")
250
251 # No client_id
252 with pytest.raises(TypeError):
253 NotifyRingCentral(
254 client_id=None,
255 client_secret=CLIENT_SECRET,
256 source=SOURCE,
257 )
258
259 # Blank client_id
260 with pytest.raises(TypeError):
261 NotifyRingCentral(
262 client_id=" ",
263 client_secret=CLIENT_SECRET,
264 source=SOURCE,
265 )
266
267 # No client_secret
268 with pytest.raises(TypeError):
269 NotifyRingCentral(
270 client_id=CLIENT_ID,
271 client_secret=None,
272 source=SOURCE,
273 )
274
275 # Blank client_secret
276 with pytest.raises(TypeError):
277 NotifyRingCentral(
278 client_id=CLIENT_ID,
279 client_secret=" ",
280 source=SOURCE,
281 )
282
283 # Invalid source phone
284 with pytest.raises(TypeError):
285 NotifyRingCentral(
286 client_id=CLIENT_ID,
287 client_secret=CLIENT_SECRET,
288 source="notaphone",
289 )
290
291 # Invalid auth mode
292 with pytest.raises(TypeError):
293 NotifyRingCentral(
294 client_id=CLIENT_ID,
295 client_secret=CLIENT_SECRET,
296 source=SOURCE,
297 mode="bad_mode",
298 )
299
300 # Invalid environment
301 with pytest.raises(TypeError):
302 NotifyRingCentral(
303 client_id=CLIENT_ID,
304 client_secret=CLIENT_SECRET,
305 source=SOURCE,
306 environment="invalid",
307 )
308
309 # Invalid JWT token in JWT mode
310 with pytest.raises(TypeError):
311 NotifyRingCentral(
312 client_id=CLIENT_ID,
313 client_secret=CLIENT_SECRET,
314 source=SOURCE,
315 token="bad token!",
316 mode=RingCentralAuthMode.JWT,
317 )
318
319 # Valid BASIC mode (token is a plain password -- no regex check)
320 obj = NotifyRingCentral(
321 client_id=CLIENT_ID,
322 client_secret=CLIENT_SECRET,
323 source=SOURCE,
324 token="some-password",
325 )
326 assert obj.mode == RingCentralAuthMode.BASIC
327
328 # Valid JWT mode
329 obj = NotifyRingCentral(
330 client_id=CLIENT_ID,
331 client_secret=CLIENT_SECRET,
332 source=SOURCE,
333 token=JWT_TOKEN,
334 mode=RingCentralAuthMode.JWT,
335 )
336 assert obj.mode == RingCentralAuthMode.JWT
337
338
339 @mock.patch("requests.post")
340 def test_plugin_ringc_url_and_identifier(mock_post):
341 """NotifyRingCentral() url() and url_identifier."""
342
343 def _mk_resp(d, code=requests.codes.ok):
344 r = mock.Mock()
345 r.status_code = code
346 r.content = d
347 return r
348
349 mock_post.return_value = _mk_resp(b"{}")
350
351 # BASIC mode with targets
352 obj = NotifyRingCentral(
353 client_id=CLIENT_ID,
354 client_secret=CLIENT_SECRET,
355 source=SOURCE,
356 token="secret",
357 targets=["15559998888"],
358 )
359 assert obj.url_identifier == (
360 "ringc",
361 CLIENT_ID,
362 CLIENT_SECRET,
363 "secret",
364 SOURCE.lstrip("+"),
365 )
366
367 full_url = obj.url()
368 assert "ringc://" in full_url
369 assert "mode=basic" in full_url
370 # ext= no longer emitted in URL
371 assert "ext=" not in full_url
372
373 privacy_url = obj.url(privacy=True)
374 assert "****" in privacy_url
375
376 # Round-trip
377 result = NotifyRingCentral.parse_url(full_url)
378 assert result is not None
379 obj2 = NotifyRingCentral(**result)
380 assert obj.url_identifier == obj2.url_identifier
381 assert len(obj.targets) == len(obj2.targets)
382
383 # JWT mode
384 obj_jwt = NotifyRingCentral(
385 client_id=CLIENT_ID,
386 client_secret=CLIENT_SECRET,
387 source=SOURCE,
388 token=JWT_TOKEN,
389 mode=RingCentralAuthMode.JWT,
390 )
391 full_url_jwt = obj_jwt.url()
392 assert "mode=jwt" in full_url_jwt
393 privacy_url_jwt = obj_jwt.url(privacy=True)
394 assert "mode=jwt" in privacy_url_jwt
395
396 # Round-trip JWT
397 result_jwt = NotifyRingCentral.parse_url(full_url_jwt)
398 assert result_jwt is not None
399 obj_jwt2 = NotifyRingCentral(**result_jwt)
400 assert obj_jwt.url_identifier == obj_jwt2.url_identifier
401
402 # __len__
403 assert len(obj) == 1 # one target
404 obj_no_targets = NotifyRingCentral(
405 client_id=CLIENT_ID,
406 client_secret=CLIENT_SECRET,
407 source=SOURCE,
408 token="pw",
409 )
410 assert len(obj_no_targets) == 1 # no targets -> loopback -> 1
411
412
413 @mock.patch("requests.post")
414 def test_plugin_ringc_send_success(mock_post):
415 """NotifyRingCentral() successful send."""
416 from json import dumps as jdumps
417
418 good_auth = mock.Mock()
419 good_auth.status_code = requests.codes.ok
420 good_auth.content = jdumps(GOOD_RESPONSE).encode()
421
422 good_sms = mock.Mock()
423 good_sms.status_code = requests.codes.ok
424 good_sms.content = jdumps(GOOD_RESPONSE).encode()
425
426 mock_post.side_effect = [good_auth, good_sms]
427
428 obj = NotifyRingCentral(
429 client_id=CLIENT_ID,
430 client_secret=CLIENT_SECRET,
431 source=SOURCE,
432 token="password",
433 targets=["15559998888"],
434 )
435 assert obj.notify(body="Test message") is True
436 assert mock_post.call_count == 2
437
438 # Second call reuses cached token (no new auth call)
439 good_sms2 = mock.Mock()
440 good_sms2.status_code = requests.codes.ok
441 good_sms2.content = jdumps(GOOD_RESPONSE).encode()
442 mock_post.side_effect = [good_sms2]
443 assert obj.notify(body="Second message") is True
444 assert mock_post.call_count == 3
445
446
447 @mock.patch("requests.post")
448 def test_plugin_ringc_send_multi_target(mock_post):
449 """NotifyRingCentral() send to multiple targets."""
450 from json import dumps as jdumps
451
452 def _ok():
453 r = mock.Mock()
454 r.status_code = requests.codes.ok
455 r.content = jdumps(GOOD_RESPONSE).encode()
456 return r
457
458 # auth + 2 targets = 3 calls
459 mock_post.side_effect = [_ok(), _ok(), _ok()]
460
461 obj = NotifyRingCentral(
462 client_id=CLIENT_ID,
463 client_secret=CLIENT_SECRET,
464 source=SOURCE,
465 token="password",
466 targets=["15559998881", "15559998882"],
467 )
468 assert obj.notify(body="Multi-target") is True
469 assert mock_post.call_count == 3
470
471
472 @mock.patch("requests.post")
473 def test_plugin_ringc_send_loopback(mock_post):
474 """NotifyRingCentral() with no targets sends to source (loopback)."""
475 from json import dumps as jdumps
476
477 good = mock.Mock()
478 good.status_code = requests.codes.ok
479 good.content = jdumps(GOOD_RESPONSE).encode()
480
481 # auth + 1 loopback send
482 mock_post.side_effect = [good, good]
483
484 obj = NotifyRingCentral(
485 client_id=CLIENT_ID,
486 client_secret=CLIENT_SECRET,
487 source=SOURCE,
488 token="password",
489 )
490 assert obj.notify(body="Loopback") is True
491 assert mock_post.call_count == 2
492
493
494 @mock.patch("requests.post")
495 def test_plugin_ringc_auth_failure(mock_post):
496 """NotifyRingCentral() returns False when auth fails."""
497 bad = mock.Mock()
498 bad.status_code = requests.codes.internal_server_error
499 bad.content = b"{}"
500 mock_post.return_value = bad
501
502 obj = NotifyRingCentral(
503 client_id=CLIENT_ID,
504 client_secret=CLIENT_SECRET,
505 source=SOURCE,
506 token="password",
507 )
508 assert obj.notify(body="Test") is False
509
510
511 @mock.patch("requests.post")
512 def test_plugin_ringc_auth_no_access_token(mock_post):
513 """NotifyRingCentral() returns False when 200 OK has no access_token."""
514 # A 200 OK response that lacks access_token is not a usable login;
515 # previously this would proceed with "Bearer None" as the auth header
516 empty_auth = mock.Mock()
517 empty_auth.status_code = requests.codes.ok
518 empty_auth.content = b"{}"
519 mock_post.return_value = empty_auth
520
521 obj = NotifyRingCentral(
522 client_id=CLIENT_ID,
523 client_secret=CLIENT_SECRET,
524 source=SOURCE,
525 token="password",
526 )
527 assert obj.notify(body="Test") is False
528
529
530 @mock.patch("requests.post")
531 def test_plugin_ringc_send_http_error(mock_post):
532 """NotifyRingCentral() handles HTTP error on send."""
533 from json import dumps as jdumps
534
535 good_auth = mock.Mock()
536 good_auth.status_code = requests.codes.ok
537 good_auth.content = jdumps(GOOD_RESPONSE).encode()
538
539 bad_sms = mock.Mock()
540 bad_sms.status_code = requests.codes.internal_server_error
541 bad_sms.content = b"{}"
542
543 mock_post.side_effect = [good_auth, bad_sms]
544
545 obj = NotifyRingCentral(
546 client_id=CLIENT_ID,
547 client_secret=CLIENT_SECRET,
548 source=SOURCE,
549 token="password",
550 targets=["15559998888"],
551 )
552 assert obj.notify(body="Test") is False
553
554
555 @mock.patch("requests.post")
556 def test_plugin_ringc_send_unknown_code(mock_post):
557 """NotifyRingCentral() handles unknown HTTP response code."""
558 from json import dumps as jdumps
559
560 good_auth = mock.Mock()
561 good_auth.status_code = requests.codes.ok
562 good_auth.content = jdumps(GOOD_RESPONSE).encode()
563
564 bad_sms = mock.Mock()
565 bad_sms.status_code = 999
566 bad_sms.content = b"{}"
567
568 mock_post.side_effect = [good_auth, bad_sms]
569
570 obj = NotifyRingCentral(
571 client_id=CLIENT_ID,
572 client_secret=CLIENT_SECRET,
573 source=SOURCE,
574 token="password",
575 targets=["15559998888"],
576 )
577 assert obj.notify(body="Test") is False
578
579
580 @mock.patch("requests.post")
581 def test_plugin_ringc_request_exception(mock_post):
582 """NotifyRingCentral() handles RequestException."""
583 mock_post.side_effect = requests.RequestException("Connection refused")
584
585 obj = NotifyRingCentral(
586 client_id=CLIENT_ID,
587 client_secret=CLIENT_SECRET,
588 source=SOURCE,
589 token="password",
590 targets=["15559998888"],
591 )
592 assert obj.notify(body="Test") is False
593
594
595 @mock.patch("requests.post")
596 def test_plugin_ringc_send_partial_failure(mock_post):
597 """NotifyRingCentral() returns False when any target fails."""
598 from json import dumps as jdumps
599
600 good_auth = mock.Mock()
601 good_auth.status_code = requests.codes.ok
602 good_auth.content = jdumps(GOOD_RESPONSE).encode()
603
604 good_sms = mock.Mock()
605 good_sms.status_code = requests.codes.ok
606 good_sms.content = jdumps(GOOD_RESPONSE).encode()
607
608 bad_sms = mock.Mock()
609 bad_sms.status_code = requests.codes.internal_server_error
610 bad_sms.content = b"{}"
611
612 # auth + good send + bad send
613 mock_post.side_effect = [good_auth, good_sms, bad_sms]
614
615 obj = NotifyRingCentral(
616 client_id=CLIENT_ID,
617 client_secret=CLIENT_SECRET,
618 source=SOURCE,
619 token="password",
620 targets=["15559998881", "15559998882"],
621 )
622 assert obj.notify(body="Partial") is False
623
624
625 @mock.patch("requests.post")
626 def test_plugin_ringc_jwt_mode(mock_post):
627 """NotifyRingCentral() JWT auth mode."""
628 from json import dumps as jdumps
629
630 good = mock.Mock()
631 good.status_code = requests.codes.ok
632 good.content = jdumps(GOOD_RESPONSE).encode()
633
634 mock_post.side_effect = [good, good]
635
636 obj = NotifyRingCentral(
637 client_id=CLIENT_ID,
638 client_secret=CLIENT_SECRET,
639 source=SOURCE,
640 token=JWT_TOKEN,
641 mode=RingCentralAuthMode.JWT,
642 targets=["15559998888"],
643 )
644 assert obj.mode == RingCentralAuthMode.JWT
645 assert obj.notify(body="JWT test") is True
646
647 # Verify the auth call used the JWT grant type
648 auth_call = mock_post.call_args_list[0]
649 assert "jwt-bearer" in str(auth_call)
650
651
652 @mock.patch("requests.post")
653 def test_plugin_ringc_sandbox_environment(mock_post):
654 """NotifyRingCentral() sandbox environment routing."""
655 from json import dumps as jdumps
656
657 good = mock.Mock()
658 good.status_code = requests.codes.ok
659 good.content = jdumps(GOOD_RESPONSE).encode()
660
661 mock_post.side_effect = [good, good]
662
663 # Sandbox environment with SMS (no attachments)
664 obj = NotifyRingCentral(
665 client_id=CLIENT_ID,
666 client_secret=CLIENT_SECRET,
667 source=SOURCE,
668 token="password",
669 environment=RingCentralEnvironment.SANDBOX,
670 targets=["15559998888"],
671 )
672 assert obj.environment == RingCentralEnvironment.SANDBOX
673 assert obj.notify(body="Sandbox test") is True
674
675 # Verify .devtest appears in the URL and /sms is used (no attachments)
676 notify_call = mock_post.call_args_list[1]
677 assert ".devtest" in notify_call[0][0]
678 assert "/sms" in notify_call[0][0]
679
680
681 @mock.patch("requests.post")
682 def test_plugin_ringc_mms_attachment(mock_post):
683 """NotifyRingCentral() auto-selects MMS endpoint when attach present."""
684 from json import dumps as jdumps
685
686 good = mock.Mock()
687 good.status_code = requests.codes.ok
688 good.content = jdumps(GOOD_RESPONSE).encode()
689
690 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
691
692 # auth + MMS send = 2 calls
693 mock_post.side_effect = [good, good]
694
695 obj = NotifyRingCentral(
696 client_id=CLIENT_ID,
697 client_secret=CLIENT_SECRET,
698 source=SOURCE,
699 token="password",
700 targets=["15559998888"],
701 )
702 assert obj.notify(body="MMS test", attach=attach) is True
703 assert mock_post.call_count == 2
704
705 # Verify the MMS endpoint was used
706 notify_call = mock_post.call_args_list[1]
707 assert "/mms" in notify_call[0][0]
708
709 # Inaccessible attachment causes failure (token is still cached)
710 mock_post.reset_mock()
711
712 with mock.patch("os.path.isfile", return_value=False):
713 bad_attach = AppriseAttachment(
714 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
715 )
716 assert obj.notify(body="Bad attach", attach=bad_attach) is False
717
718 # No HTTP calls should have been made (failed at attachment check)
719 assert mock_post.call_count == 0
720
721 # OSError from open() is caught and treated as a failed attachment
722 mock_post.reset_mock()
723
724 with mock.patch("builtins.open", side_effect=OSError("disk error")):
725 assert obj.notify(body="OSError test", attach=attach) is False
726
727 assert mock_post.call_count == 0
728
729 # MMS send HTTP error (attachment opens fine but server rejects)
730 mock_post.reset_mock()
731 bad_mms = mock.Mock()
732 bad_mms.status_code = requests.codes.internal_server_error
733 bad_mms.content = b"{}"
734 mock_post.side_effect = [bad_mms]
735
736 assert obj.notify(body="MMS HTTP fail", attach=attach) is False
737 assert mock_post.call_count == 1
738
739
740 @mock.patch("requests.post")
741 def test_plugin_ringc_parse_url(mock_post):
742 """NotifyRingCentral() URL parsing edge cases."""
743
744 mock_post.return_value = mock.Mock()
745 mock_post.return_value.status_code = requests.codes.ok
746 mock_post.return_value.content = b"{}"
747
748 # URL with all params in query string; client_id goes in the host
749 url = "ringc://client_id?token={}&secret={}&from={}".format(
750 "a" * 8, "b" * 16, "5" * 11
751 )
752 result = NotifyRingCentral.parse_url(url)
753 assert result is not None
754 assert result["client_id"] == "client_id"
755 assert result["token"] == "a" * 8
756 assert result["client_secret"] == "b" * 16
757 obj = NotifyRingCentral(**result)
758 assert isinstance(obj, NotifyRingCentral)
759
760 # Reverse URL form: token@client_id/secret/source
761 url2 = "ringc://{}@client_id/secret/15551234567".format("c" * 8)
762 result2 = NotifyRingCentral.parse_url(url2)
763 assert result2 is not None
764 assert result2["source"] == "15551234567"
765
766 # ?to= appends targets
767 url3 = "ringc://15559990000:password@client_id/secret?to=15551234567"
768 result3 = NotifyRingCentral.parse_url(url3)
769 assert result3 is not None
770 assert "15551234567" in result3["targets"]
771
772 # ?env= override
773 url4 = "ringc://15559990000:password@client_id/secret?env=sandbox"
774 result4 = NotifyRingCentral.parse_url(url4)
775 assert result4 is not None
776 assert result4["environment"] == "sandbox"
777
778 # ?source= override (alias for ?from=)
779 url5 = "ringc://client_id?token=abc&secret=xyz&source=15559990000"
780 result5 = NotifyRingCentral.parse_url(url5)
781 assert result5 is not None
782 assert result5["source"] == "15559990000"
783
784 # ?mode= override
785 url6 = "ringc://15559990000:password@client_id/secret?mode=basic"
786 result6 = NotifyRingCentral.parse_url(url6)
787 assert result6 is not None
788 assert result6["mode"] == "basic"
789
790 # JWT auto-detection from token length (>60 chars) in URL userinfo
791 url7 = "ringc://15559990000:{}@client_id/secret".format("x" * 70)
792 result7 = NotifyRingCentral.parse_url(url7)
793 assert result7 is not None
794 assert result7["mode"] == RingCentralAuthMode.JWT
795
796 # Short token -> BASIC mode auto-detection
797 url8 = "ringc://15559990000:shortpw@client_id/secret"
798 result8 = NotifyRingCentral.parse_url(url8)
799 assert result8 is not None
800 assert result8["mode"] == RingCentralAuthMode.BASIC
801
802 # JWT auto-detection via ?token= query param; ?token= must be applied
803 # before mode detection so a long JWT supplied via query param is
804 # correctly classified as JWT, not BASIC
805 url9 = "ringc://client_id?token={}&secret=secret&from=15559990000".format(
806 "y" * 70
807 )
808 result9 = NotifyRingCentral.parse_url(url9)
809 assert result9 is not None
810 assert result9["mode"] == RingCentralAuthMode.JWT
811 assert result9["token"] == "y" * 70
812
813 # Invalid URL returns None
814 assert NotifyRingCentral.parse_url(None) is None
815
816
817 @mock.patch("requests.post")
818 def test_plugin_ringc_logout(mock_post):
819 """NotifyRingCentral() logout sends revocation request."""
820 from json import dumps as jdumps
821
822 good = mock.Mock()
823 good.status_code = requests.codes.ok
824 good.content = jdumps(GOOD_RESPONSE).encode()
825
826 bad_revoke = mock.Mock()
827 bad_revoke.status_code = requests.codes.internal_server_error
828 bad_revoke.content = b"{}"
829
830 # login succeeds, then logout fails gracefully
831 mock_post.side_effect = [good, good, bad_revoke]
832
833 obj = NotifyRingCentral(
834 client_id=CLIENT_ID,
835 client_secret=CLIENT_SECRET,
836 source=SOURCE,
837 token="password",
838 targets=["15559998888"],
839 )
840 assert obj.notify(body="Test") is True
841 assert obj._access_token is not None
842
843 # Explicit logout (token is still valid, sends revoke)
844 obj.logout()
845 assert obj._access_token is None
846
847 # Logout a second time (nothing to revoke -- no-op)
848 obj.logout()
849 assert mock_post.call_count == 3
850
851
852 @mock.patch("requests.post")
853 def test_plugin_ringc_del_exception(mock_post):
854 """NotifyRingCentral() __del__ handles OSError from logout."""
855 mock_post.return_value = mock.Mock()
856 mock_post.return_value.status_code = requests.codes.ok
857 mock_post.return_value.content = b"{}"
858
859 with mock.patch(
860 "apprise.plugins.ringcentral.NotifyRingCentral.logout",
861 side_effect=OSError(),
862 ):
863 obj = NotifyRingCentral(
864 client_id=CLIENT_ID,
865 client_secret="valid-secret",
866 source=SOURCE,
867 )
868 # __del__ must not propagate the exception
869 del obj
870
871
872 @mock.patch("requests.post")
873 def test_plugin_ringc_invalid_json_response(mock_post):
874 """NotifyRingCentral() handles non-JSON response bodies."""
875 from json import dumps as jdumps
876
877 good_auth = mock.Mock()
878 good_auth.status_code = requests.codes.ok
879 good_auth.content = jdumps(GOOD_RESPONSE).encode()
880
881 bad_json = mock.Mock()
882 bad_json.status_code = requests.codes.ok
883 bad_json.content = b"not-json"
884
885 mock_post.side_effect = [good_auth, bad_json]
886
887 obj = NotifyRingCentral(
888 client_id=CLIENT_ID,
889 client_secret=CLIENT_SECRET,
890 source=SOURCE,
891 token="password",
892 targets=["15559998888"],
893 )
894 # Should succeed (status 200 regardless of body parseability)
895 assert obj.notify(body="Test") is True
896
897
898 @mock.patch("requests.post")
899 def test_plugin_ringc_dropped_targets(mock_post):
900 """NotifyRingCentral() drops invalid phone numbers silently."""
901 mock_post.return_value = mock.Mock()
902 mock_post.return_value.status_code = requests.codes.ok
903 mock_post.return_value.content = b"{}"
904
905 obj = NotifyRingCentral(
906 client_id=CLIENT_ID,
907 client_secret=CLIENT_SECRET,
908 source=SOURCE,
909 token="password",
910 targets=["abc", "15559998888"],
911 )
912 # "abc" is invalid and should be dropped
913 assert len(obj.targets) == 1
914 assert "15559998888" in obj.targets[0]
915
916
917 @mock.patch("requests.post")
918 def test_plugin_ringc_apprise_integration(mock_post):
919 """NotifyRingCentral() works through the Apprise interface."""
920 from json import dumps as jdumps
921
922 good = mock.Mock()
923 good.status_code = requests.codes.ok
924 good.content = jdumps(GOOD_RESPONSE).encode()
925
926 mock_post.return_value = good
927
928 a = Apprise()
929 url = "ringc://18005554321:{}@client_id/secret/15559998888".format(
930 "c" * 60
931 )
932 assert a.add(url) is True
933 assert a.notify(body="Apprise integration test") is True