Debian Codegraph @

tests/test_plugin_eight00com.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 from json import loads
30 import logging
31 import os
32 from unittest import mock
33 from urllib.parse import urlparse
34
35 from helpers import AppriseURLTester
36 import pytest
37 import requests
38
39 from apprise import Apprise, AppriseAttachment, NotifyType
40 from apprise.exception import AppriseImproperlyConfigured
41 from apprise.plugins.eight00com import NotifyEight00com
42
43 logging.disable(logging.CRITICAL)
44
45 # Attachment Directory
46 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
47
48 # Our Testing URLs
49 apprise_url_tests = (
50 (
51 "eight00com://",
52 {
53 # Missing token
54 "instance": AppriseImproperlyConfigured,
55 },
56 ),
57 (
58 "eight00com://:@/",
59 {
60 # Empty token
61 "instance": AppriseImproperlyConfigured,
62 },
63 ),
64 (
65 "eight00com://GOODTOKEN@badphone",
66 {
67 # Non-numeric source phone number
68 "instance": AppriseImproperlyConfigured,
69 },
70 ),
71 (
72 "eight00com://GOODTOKEN@9876543210/12",
73 {
74 # Target too short to be a valid phone number; it is
75 # dropped, leaving no targets -> notify_response False
76 "instance": NotifyEight00com,
77 "notify_response": False,
78 },
79 ),
80 (
81 "eight00com://{}@{}".format("t" * 10, "8" * 10),
82 {
83 # Valid token + source only; defaults to texting ourselves
84 "instance": NotifyEight00com,
85 },
86 ),
87 (
88 "eight00com://{}@{}/{}".format("t" * 10, "8" * 10, "5" * 11),
89 {
90 # Valid token, source, and one target
91 "instance": NotifyEight00com,
92 "privacy_url": (
93 "eight00com://t...t@{}/{}".format("8" * 10, "5" * 11)
94 ),
95 },
96 ),
97 (
98 "eight00com://{}@{}/{}/{}".format(
99 "t" * 10, "8" * 10, "5" * 11, "6" * 11
100 ),
101 {
102 # Multiple targets
103 "instance": NotifyEight00com,
104 },
105 ),
106 (
107 "eight00com://?token={}&from={}".format("t" * 10, "8" * 10),
108 {
109 # Token and source via query params
110 "instance": NotifyEight00com,
111 },
112 ),
113 (
114 "eight00com://?token={}&from={}&to={}".format(
115 "t" * 10, "8" * 10, "5" * 11
116 ),
117 {
118 # Token, source, and target all via query params
119 "instance": NotifyEight00com,
120 },
121 ),
122 (
123 "eight00com://{}@{}".format("t" * 10, "8" * 10),
124 {
125 "instance": NotifyEight00com,
126 # HTTP 500 -> failure
127 "response": False,
128 "requests_response_code": requests.codes.internal_server_error,
129 },
130 ),
131 (
132 "eight00com://{}@{}".format("t" * 10, "8" * 10),
133 {
134 "instance": NotifyEight00com,
135 # Unknown HTTP code -> failure
136 "response": False,
137 "requests_response_code": 999,
138 },
139 ),
140 (
141 "eight00com://{}@{}".format("t" * 10, "8" * 10),
142 {
143 "instance": NotifyEight00com,
144 # Simulate network I/O exceptions
145 "test_requests_exceptions": True,
146 },
147 ),
148 )
149
150
151 def test_plugin_eight00com_urls():
152 """NotifyEight00com() Apprise URLs."""
153 AppriseURLTester(tests=apprise_url_tests).run_all()
154
155
156 @mock.patch("requests.post")
157 def test_plugin_eight00com_init(mock_post):
158 """NotifyEight00com() initialization and edge cases."""
159
160 # Prepare a generic success response
161 response = requests.Request()
162 response.status_code = requests.codes.ok
163 mock_post.return_value = response
164
165 # A token is required.
166 with pytest.raises(AppriseImproperlyConfigured):
167 NotifyEight00com(token=None, source="8005551234")
168
169 # An empty token is invalid.
170 with pytest.raises(AppriseImproperlyConfigured):
171 NotifyEight00com(token="", source="8005551234")
172
173 # The source must be a valid phone number.
174 with pytest.raises(AppriseImproperlyConfigured):
175 NotifyEight00com(token="mytoken", source="notaphone")
176
177 # Valid with source only: defaults to texting ourselves
178 obj = NotifyEight00com(token="mytoken", source="8005551234")
179 assert obj.targets == ["8005551234"]
180 assert len(obj) == 1
181
182 # Invalid target is dropped with a warning logged
183 obj = NotifyEight00com(
184 token="mytoken",
185 source="8005551234",
186 targets=["12"],
187 )
188 assert obj.targets == []
189 # __len__ returns 1 minimum (consistent with httpsms pattern)
190 assert len(obj) == 1
191
192 # Multiple valid targets
193 obj = NotifyEight00com(
194 token="mytoken",
195 source="8005551234",
196 targets=["5551234567", "6661234567"],
197 )
198 assert len(obj.targets) == 2
199 assert len(obj) == 2
200
201
202 @mock.patch("requests.post")
203 def test_plugin_eight00com_sms(mock_post):
204 """NotifyEight00com() SMS send path."""
205
206 response = requests.Request()
207 response.status_code = requests.codes.ok
208 response.content = b"{}"
209 mock_post.return_value = response
210
211 # Single target
212 obj = NotifyEight00com(
213 token="mytoken",
214 source="8005551234",
215 targets=["5559876543"],
216 )
217 assert bool(obj.notify(body="Test", title="Title")) is True
218 assert mock_post.call_count == 1
219
220 # Verify payload
221 payload = loads(mock_post.call_args[1]["data"])
222 assert payload["sender"] == "+8005551234"
223 assert payload["recipient"] == "+5559876543"
224 assert payload["message"] == "Title\r\nTest"
225
226 # Verify Authorization header
227 headers = mock_post.call_args[1]["headers"]
228 assert headers["Authorization"] == "Bearer mytoken"
229
230 mock_post.reset_mock()
231
232 # Two targets -> two POST calls
233 obj = NotifyEight00com(
234 token="mytoken",
235 source="8005551234",
236 targets=["5559876543", "4445551234"],
237 )
238 assert bool(obj.notify(body="Hello")) is True
239 assert mock_post.call_count == 2
240
241 mock_post.reset_mock()
242
243 # HTTP 500 -> failure
244 response.status_code = requests.codes.internal_server_error
245 obj = NotifyEight00com(
246 token="mytoken",
247 source="8005551234",
248 targets=["5559876543"],
249 )
250 assert bool(obj.notify(body="Test")) is False
251
252 mock_post.reset_mock()
253
254 # Unknown status code -> failure
255 response.status_code = 999
256 assert bool(obj.notify(body="Test")) is False
257
258 mock_post.reset_mock()
259
260 # RequestException -> failure
261 mock_post.side_effect = requests.RequestException("Connection error")
262 response.status_code = requests.codes.ok
263 assert bool(obj.notify(body="Test")) is False
264
265 mock_post.side_effect = None
266
267 # No targets after bad-number drops -> failure without HTTP call
268 obj = NotifyEight00com(
269 token="mytoken",
270 source="8005551234",
271 targets=["12"],
272 )
273 mock_post.reset_mock()
274 assert bool(obj.notify(body="Test")) is False
275 assert mock_post.call_count == 0
276
277
278 @mock.patch("requests.post")
279 def test_plugin_eight00com_url_round_trip(mock_post):
280 """NotifyEight00com() URL round-trip and privacy_url."""
281
282 response = requests.Request()
283 response.status_code = requests.codes.ok
284 mock_post.return_value = response
285
286 # Round-trip with one target
287 obj1 = NotifyEight00com(
288 token="secrettoken",
289 source="8005551234",
290 targets=["5559876543"],
291 )
292 result = NotifyEight00com.parse_url(obj1.url())
293 obj2 = NotifyEight00com(**result)
294 assert obj1.url_identifier == obj2.url_identifier
295 assert len(obj1.targets) == len(obj2.targets)
296
297 # Privacy URL masks the token
298 privacy = obj1.url(privacy=True)
299 assert "secrettoken" not in privacy
300 assert "s...n" in privacy
301
302 # Round-trip with no explicit target (self-send omits path)
303 obj3 = NotifyEight00com(token="mytoken", source="8005551234")
304 result = NotifyEight00com.parse_url(obj3.url())
305 obj4 = NotifyEight00com(**result)
306 assert obj3.url_identifier == obj4.url_identifier
307 # Self-send: targets are preserved
308 assert obj3.targets == obj4.targets
309
310 # url_identifier is schema / source / token -- not targets
311 assert obj1.url_identifier == (
312 "eight00com",
313 "8005551234",
314 "secrettoken",
315 )
316
317
318 @mock.patch("requests.post")
319 def test_plugin_eight00com_parse_url(mock_post):
320 """NotifyEight00com() parse_url edge cases."""
321
322 response = requests.Request()
323 response.status_code = requests.codes.ok
324 mock_post.return_value = response
325
326 # Standard form: token@source/target
327 result = NotifyEight00com.parse_url(
328 "eight00com://mytoken@8005551234/5559876543"
329 )
330 assert result["token"] == "mytoken"
331 assert result["source"] == "8005551234"
332 assert "5559876543" in result["targets"]
333
334 # ?token= override
335 result = NotifyEight00com.parse_url(
336 "eight00com://8005551234?token=newtoken&from=8009876543&to=5551234567"
337 )
338 assert result["token"] == "newtoken"
339 assert result["source"] == "8009876543"
340
341 # ?from= causes host to become a target instead of source
342 result = NotifyEight00com.parse_url(
343 "eight00com://mytoken@9998887776?from=8005551234"
344 )
345 assert result["token"] == "mytoken"
346 assert result["source"] == "8005551234"
347 # The host (9998887776) becomes a target
348 assert "9998887776" in " ".join(result["targets"])
349
350 # ?to= adds targets
351 result = NotifyEight00com.parse_url(
352 "eight00com://mytoken@8005551234?to=5559876543"
353 )
354 assert "5559876543" in " ".join(result["targets"])
355
356 # Unparseable URL -> None
357 assert NotifyEight00com.parse_url(None) is None
358
359
360 @mock.patch("requests.post")
361 def test_plugin_eight00com_attach_success(mock_post):
362 """NotifyEight00com() attachment send -- success path."""
363
364 response = requests.Request()
365 response.status_code = requests.codes.ok
366 mock_post.return_value = response
367
368 obj = NotifyEight00com(
369 token="mytoken",
370 source="8005551234",
371 targets=["5559876543"],
372 )
373
374 attach = AppriseAttachment.instantiate(
375 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
376 )
377 assert (
378 bool(
379 obj.notify(
380 body="Test MMS",
381 title="",
382 notify_type=NotifyType.INFO,
383 attach=attach,
384 )
385 )
386 is True
387 )
388
389 # Exactly one POST for one target
390 assert mock_post.call_count == 1
391
392 # Confirm the MMS fields were sent as multipart (files kwarg set)
393 call_kwargs = mock_post.call_args[1]
394 assert call_kwargs["files"] is not None
395 assert call_kwargs["data"]["sender"] == "+8005551234"
396 assert call_kwargs["data"]["recipient"] == "+5559876543"
397 assert call_kwargs["data"]["message"] == "Test MMS"
398
399 # Confirm authorization header is present
400 assert call_kwargs["headers"]["Authorization"] == "Bearer mytoken"
401
402 # Verify the URL host is correct
403 call_url = mock_post.call_args[0][0]
404 assert urlparse(call_url).hostname == "api.800.com"
405
406
407 @mock.patch("requests.post")
408 def test_plugin_eight00com_attach_multi(mock_post):
409 """NotifyEight00com() MMS with multiple attachments."""
410
411 response = requests.Request()
412 response.status_code = requests.codes.ok
413 mock_post.return_value = response
414
415 obj = NotifyEight00com(
416 token="mytoken",
417 source="8005551234",
418 targets=["5559876543"],
419 )
420
421 attach = AppriseAttachment()
422 attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
423 attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
424
425 assert (
426 bool(
427 obj.notify(
428 body="Multi-attachment MMS",
429 attach=attach,
430 )
431 )
432 is True
433 )
434 assert mock_post.call_count == 1
435
436 # Two media[] tuples in the files list
437 files = mock_post.call_args[1]["files"]
438 assert len(files) == 2
439 assert all(f[0] == "media[]" for f in files)
440
441
442 @mock.patch("requests.post")
443 def test_plugin_eight00com_attach_inaccessible(mock_post):
444 """NotifyEight00com() attachment -- inaccessible file guard."""
445
446 response = requests.Request()
447 response.status_code = requests.codes.ok
448 mock_post.return_value = response
449
450 obj = NotifyEight00com(
451 token="mytoken",
452 source="8005551234",
453 targets=["5559876543"],
454 )
455
456 attach = AppriseAttachment.instantiate(
457 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
458 )
459
460 # Simulate the file being inaccessible (os.path.isfile -> False)
461 with mock.patch("os.path.isfile", return_value=False):
462 assert bool(obj.notify(body="Test", attach=attach)) is False
463
464 # No HTTP call should have been made
465 assert mock_post.call_count == 0
466
467
468 @mock.patch("requests.post")
469 def test_plugin_eight00com_attach_oserror(mock_post):
470 """NotifyEight00com() attachment -- OSError on open guard."""
471
472 response = requests.Request()
473 response.status_code = requests.codes.ok
474 mock_post.return_value = response
475
476 obj = NotifyEight00com(
477 token="mytoken",
478 source="8005551234",
479 targets=["5559876543"],
480 )
481
482 attach = AppriseAttachment.instantiate(
483 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
484 )
485
486 with mock.patch("builtins.open", side_effect=OSError("IO fail")):
487 assert bool(obj.notify(body="Test", attach=attach)) is False
488
489 # No HTTP call should have been made
490 assert mock_post.call_count == 0
491
492
493 @mock.patch("requests.post")
494 def test_plugin_eight00com_attach_http_error(mock_post):
495 """NotifyEight00com() attachment -- server HTTP error response."""
496
497 response = requests.Request()
498 response.status_code = requests.codes.internal_server_error
499 response.content = b"{}"
500 mock_post.return_value = response
501
502 obj = NotifyEight00com(
503 token="mytoken",
504 source="8005551234",
505 targets=["5559876543"],
506 )
507
508 attach = AppriseAttachment.instantiate(
509 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
510 )
511 assert bool(obj.notify(body="Test", attach=attach)) is False
512 assert mock_post.call_count == 1
513
514
515 @mock.patch("requests.post")
516 def test_plugin_eight00com_attach_request_exception(mock_post):
517 """NotifyEight00com() attachment -- RequestException guard."""
518
519 mock_post.side_effect = requests.RequestException("Connection error")
520
521 obj = NotifyEight00com(
522 token="mytoken",
523 source="8005551234",
524 targets=["5559876543"],
525 )
526
527 attach = AppriseAttachment.instantiate(
528 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
529 )
530 assert bool(obj.notify(body="Test", attach=attach)) is False
531
532
533 @mock.patch("requests.post")
534 def test_plugin_eight00com_attach_partial_failure(mock_post):
535 """NotifyEight00com() MMS partial target failure."""
536
537 def _side_effect(*args, **kwargs):
538 # First call succeeds, second fails
539 if mock_post.call_count == 1:
540 resp = requests.Request()
541 resp.status_code = requests.codes.ok
542 return resp
543
544 resp = requests.Request()
545 resp.status_code = requests.codes.internal_server_error
546 resp.content = b"{}"
547 return resp
548
549 mock_post.side_effect = _side_effect
550
551 obj = NotifyEight00com(
552 token="mytoken",
553 source="8005551234",
554 targets=["5559876543", "4441234567"],
555 )
556
557 attach = AppriseAttachment.instantiate(
558 os.path.join(TEST_VAR_DIR, "apprise-test.gif")
559 )
560 # One success and one failure -> overall False
561 assert bool(obj.notify(body="Test", attach=attach)) is False
562 assert mock_post.call_count == 2
563
564
565 @mock.patch("requests.post")
566 def test_plugin_eight00com_apprise_integration(mock_post):
567 """NotifyEight00com() integration with Apprise."""
568
569 response = requests.Request()
570 response.status_code = requests.codes.ok
571 mock_post.return_value = response
572
573 # Load via URL
574 a = Apprise()
575 assert a.add("eight00com://mytoken@8005551234/5559876543") is True
576 assert bool(a.notify(body="Integration test")) is True
577 assert mock_post.call_count == 1
578
579 mock_post.reset_mock()
580
581 # Load via URL with ?to= and ?from=
582 a2 = Apprise()
583 assert (
584 a2.add("eight00com://?token=mytoken&from=8005551234&to=5559876543")
585 is True
586 )
587 assert bool(a2.notify(body="Integration test 2")) is True
588 assert mock_post.call_count == 1