Debian Codegraph @

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