Debian Codegraph @

tests/test_plugin_smsc.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 json
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.smsc import NotifySMSC
42
43 logging.disable(logging.CRITICAL)
44
45 # Attachment test directory
46 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
47
48 # Valid login/password
49 LOGIN = "mylogin"
50 PASSWORD = "mypassword"
51 # A valid E.164 phone number (without + prefix in stored form)
52 PHONE = "71234567890"
53 PHONE2 = "79876543210"
54
55
56 # Our Testing URLs
57 apprise_url_tests = (
58 # Missing everything
59 (
60 "smsc://",
61 {"instance": AppriseImproperlyConfigured},
62 ),
63 # Missing password
64 (
65 "smsc://login@+71234567890",
66 {"instance": AppriseImproperlyConfigured},
67 ),
68 # Missing login
69 (
70 "smsc://:password@+71234567890",
71 {"instance": AppriseImproperlyConfigured},
72 ),
73 # Valid single target
74 (
75 "smsc://login:password@+71234567890",
76 {
77 "instance": NotifySMSC,
78 "privacy_url": "smsc://l...n:****@71234567890/",
79 },
80 ),
81 # Valid two targets in path
82 (
83 "smsc://login:password@+71234567890/+79876543210",
84 {
85 "instance": NotifySMSC,
86 "privacy_url": "smsc://l...n:****@71234567890/79876543210/",
87 },
88 ),
89 # With sender ID
90 (
91 "smsc://login:password@+71234567890?sender=MySender",
92 {"instance": NotifySMSC},
93 ),
94 # With translit enabled
95 (
96 "smsc://login:password@+71234567890?translit=yes",
97 {"instance": NotifySMSC},
98 ),
99 # ?to= alias for additional targets
100 (
101 "smsc://login:password@+71234567890?to=+79876543210",
102 {"instance": NotifySMSC},
103 ),
104 # Invalid phone number (only one bad; loads with warning but works)
105 (
106 "smsc://login:password@+71234567890/notaphone",
107 {
108 "instance": NotifySMSC,
109 "privacy_url": "smsc://l...n:****@71234567890/",
110 },
111 ),
112 # Only invalid phone numbers -- loads but notify returns False
113 (
114 "smsc://login:password@notaphone",
115 {
116 "instance": NotifySMSC,
117 "notify_response": False,
118 },
119 ),
120 # HTTP 500 response
121 (
122 "smsc://login:password@+71234567890",
123 {
124 "instance": NotifySMSC,
125 "response": False,
126 "requests_response_code": requests.codes.internal_server_error,
127 },
128 ),
129 # Unknown HTTP status
130 (
131 "smsc://login:password@+71234567890",
132 {
133 "instance": NotifySMSC,
134 "response": False,
135 "requests_response_code": 999,
136 },
137 ),
138 # RequestException
139 (
140 "smsc://login:password@+71234567890",
141 {
142 "instance": NotifySMSC,
143 "test_requests_exceptions": True,
144 },
145 ),
146 )
147
148
149 def test_plugin_smsc_urls():
150 """NotifySMSC() Apprise URLs."""
151 AppriseURLTester(tests=apprise_url_tests).run_all()
152
153
154 @mock.patch("requests.post")
155 def test_plugin_smsc_init(mock_post):
156 """NotifySMSC() initialization and validation."""
157
158 # A login is required.
159 with pytest.raises(AppriseImproperlyConfigured):
160 NotifySMSC(targets=["+71234567890"])
161
162 # A password is required.
163 with pytest.raises(AppriseImproperlyConfigured):
164 NotifySMSC(user=LOGIN, targets=["+71234567890"])
165
166 # Whitespace-only sender is invalid (validate_regex strips to empty)
167 with pytest.raises(AppriseImproperlyConfigured):
168 NotifySMSC(
169 user=LOGIN,
170 password=PASSWORD,
171 targets=["+71234567890"],
172 sender=" ",
173 )
174
175 # Valid instance, default settings
176 obj = NotifySMSC(
177 user=LOGIN,
178 password=PASSWORD,
179 targets=["+71234567890"],
180 )
181 assert isinstance(obj, NotifySMSC)
182 assert obj.sender is None
183 assert obj.translit is False
184 assert len(obj) == 1
185
186 # Valid instance with sender and translit
187 obj = NotifySMSC(
188 user=LOGIN,
189 password=PASSWORD,
190 targets=["+71234567890"],
191 sender="MyBiz",
192 translit=True,
193 )
194 assert obj.sender == "MyBiz"
195 assert obj.translit is True
196
197 # No targets - __len__ returns 1 (not 0) per convention
198 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=[])
199 assert len(obj) == 1
200
201
202 @mock.patch("requests.post")
203 def test_plugin_smsc_url(mock_post):
204 """NotifySMSC() URL building and round-trip."""
205
206 obj = NotifySMSC(
207 user=LOGIN,
208 password=PASSWORD,
209 targets=["+71234567890", "+79876543210"],
210 sender="Apprise",
211 translit=True,
212 )
213
214 # url() must contain all relevant parts
215 generated = obj.url()
216 assert "smsc://" in generated
217 assert "71234567890" in generated
218 assert "79876543210" in generated
219 assert "sender=Apprise" in generated
220 assert "translit=yes" in generated
221
222 # privacy URL must mask the password and redact the user
223 priv = obj.url(privacy=True)
224 assert PASSWORD not in priv
225 assert "m...n" in priv
226
227 # url_identifier uniqueness
228 obj2 = NotifySMSC(
229 user=LOGIN,
230 password=PASSWORD,
231 targets=["+71234567890"],
232 )
233 assert obj.url_identifier == obj2.url_identifier
234
235 # Round-trip via parse_url
236 result = NotifySMSC.parse_url(obj.url())
237 assert result is not None
238 obj3 = NotifySMSC(**result)
239 assert obj3.url_identifier == obj.url_identifier
240 assert len(obj3.targets) == len(obj.targets)
241
242
243 @mock.patch("requests.post")
244 def test_plugin_smsc_send_sms(mock_post):
245 """NotifySMSC() SMS send - success and failure paths."""
246
247 def _mk_resp(data, code=requests.codes.ok):
248 r = mock.Mock()
249 r.status_code = code
250 r.content = json.dumps(data).encode()
251 return r
252
253 # Happy path
254 mock_post.return_value = _mk_resp({"id": "1234", "cnt": 1})
255
256 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
257 assert bool(obj.notify(body="Hello")) is True
258 assert mock_post.call_count == 1
259
260 # Verify POST went to the SMSC endpoint
261 call_url = mock_post.call_args[0][0]
262 assert urlparse(call_url).hostname == "smsc.ru"
263
264 # Verify payload fields
265 payload = mock_post.call_args[1]["data"]
266 assert payload["login"] == LOGIN
267 assert payload["psw"] == PASSWORD
268 assert "71234567890" in payload["phones"]
269 assert payload["mes"] == "Hello"
270
271 mock_post.reset_mock()
272
273 # API-level error in JSON response
274 mock_post.return_value = _mk_resp(
275 {"error": "Invalid login", "error_code": 2}
276 )
277 assert bool(obj.notify(body="Hello")) is False
278
279 mock_post.reset_mock()
280
281 # HTTP error status
282 mock_post.return_value = _mk_resp({}, code=requests.codes.bad_request)
283 assert bool(obj.notify(body="Hello")) is False
284
285 mock_post.reset_mock()
286
287 # Unknown HTTP status
288 mock_post.return_value = _mk_resp({}, code=999)
289 assert bool(obj.notify(body="Hello")) is False
290
291 mock_post.reset_mock()
292
293 # RequestException
294 mock_post.side_effect = requests.RequestException("bang")
295 assert bool(obj.notify(body="Hello")) is False
296
297 mock_post.reset_mock()
298 mock_post.side_effect = None
299
300 # Non-JSON response body (loads raises ValueError) -- still succeeds
301 # because HTTP 200 is authoritative; the loads exception handler fires
302 r = mock.Mock()
303 r.status_code = requests.codes.ok
304 r.content = b"OK"
305 mock_post.return_value = r
306 assert bool(obj.notify(body="Hello")) is True
307
308
309 @mock.patch("requests.post")
310 def test_plugin_smsc_no_targets(mock_post):
311 """NotifySMSC() returns False when no valid targets present."""
312
313 obj = NotifySMSC(
314 user=LOGIN,
315 password=PASSWORD,
316 targets=["notaphone"],
317 )
318 # notify() must return False without calling the API
319 assert bool(obj.notify(body="Hello")) is False
320 assert mock_post.call_count == 0
321
322
323 @mock.patch("requests.post")
324 def test_plugin_smsc_sender_translit(mock_post):
325 """NotifySMSC() sender and translit params appear in the request."""
326
327 def _mk_resp(data, code=requests.codes.ok):
328 r = mock.Mock()
329 r.status_code = code
330 r.content = json.dumps(data).encode()
331 return r
332
333 mock_post.return_value = _mk_resp({"id": "99", "cnt": 1})
334
335 obj = NotifySMSC(
336 user=LOGIN,
337 password=PASSWORD,
338 targets=["+71234567890"],
339 sender="MyBiz",
340 translit=True,
341 )
342 assert bool(obj.notify(body="Привет")) is True
343
344 payload = mock_post.call_args[1]["data"]
345 assert payload.get("sender") == "MyBiz"
346 assert payload.get("translit") == 1
347
348
349 @mock.patch("requests.post")
350 def test_plugin_smsc_send_mms_success(mock_post):
351 """NotifySMSC() MMS send succeeds with valid attachment."""
352
353 def _mk_resp(data, code=requests.codes.ok):
354 r = mock.Mock()
355 r.status_code = code
356 r.content = json.dumps(data).encode()
357 return r
358
359 mock_post.return_value = _mk_resp({"id": "5678", "cnt": 1})
360
361 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
362
363 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
364 assert bool(obj.notify(body="Image", attach=attach)) is True
365 assert mock_post.call_count == 1
366
367 # Confirm MMS flag is set in the payload
368 payload = mock_post.call_args[1]["data"]
369 assert payload.get("mms") == 1
370
371 # Confirm a file was included in the files parameter
372 files_arg = mock_post.call_args[1]["files"]
373 assert len(files_arg) == 1
374
375
376 @mock.patch("requests.post")
377 def test_plugin_smsc_mms_multi_attach(mock_post):
378 """NotifySMSC() MMS send with multiple attachments."""
379
380 def _mk_resp(data, code=requests.codes.ok):
381 r = mock.Mock()
382 r.status_code = code
383 r.content = json.dumps(data).encode()
384 return r
385
386 mock_post.return_value = _mk_resp({"id": "9999", "cnt": 1})
387
388 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
389
390 attach = AppriseAttachment(
391 [
392 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
393 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
394 ]
395 )
396 assert bool(obj.notify(body="Two files", attach=attach)) is True
397
398 files_arg = mock_post.call_args[1]["files"]
399 assert len(files_arg) == 2
400
401
402 @mock.patch("requests.post")
403 def test_plugin_smsc_mms_inaccessible(mock_post):
404 """NotifySMSC() MMS fails when attachment file is inaccessible."""
405
406 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
407
408 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
409
410 with mock.patch("os.path.isfile", return_value=False):
411 assert bool(obj.notify(body="Image", attach=attach)) is False
412
413 # The HTTP client must not have been called
414 assert mock_post.call_count == 0
415
416
417 @mock.patch("requests.post")
418 def test_plugin_smsc_mms_oserror(mock_post):
419 """NotifySMSC() MMS fails cleanly on OSError during open."""
420
421 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
422
423 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
424
425 with mock.patch("builtins.open", side_effect=OSError("disk error")):
426 assert bool(obj.notify(body="Image", attach=attach)) is False
427
428 assert mock_post.call_count == 0
429
430
431 @mock.patch("requests.post")
432 def test_plugin_smsc_mms_http_error(mock_post):
433 """NotifySMSC() MMS returns False on HTTP error response."""
434
435 r = mock.Mock()
436 r.status_code = requests.codes.internal_server_error
437 r.content = b""
438 mock_post.return_value = r
439
440 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
441
442 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
443 assert bool(obj.notify(body="Image", attach=attach)) is False
444
445
446 @mock.patch("requests.post")
447 def test_plugin_smsc_mms_api_error(mock_post):
448 """NotifySMSC() MMS returns False on API-level error."""
449
450 r = mock.Mock()
451 r.status_code = requests.codes.ok
452 r.content = json.dumps(
453 {"error": "Insufficient funds", "error_code": 3}
454 ).encode()
455 mock_post.return_value = r
456
457 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
458
459 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
460 assert bool(obj.notify(body="Image", attach=attach)) is False
461
462
463 @mock.patch("requests.post")
464 def test_plugin_smsc_mms_request_exception(mock_post):
465 """NotifySMSC() MMS returns False on RequestException."""
466
467 mock_post.side_effect = requests.RequestException("timeout")
468
469 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
470
471 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
472 assert bool(obj.notify(body="Image", attach=attach)) is False
473
474
475 @mock.patch("requests.post")
476 def test_plugin_smsc_mms_non_json(mock_post):
477 """NotifySMSC() MMS succeeds with non-JSON response body on HTTP 200."""
478
479 # A non-JSON success body exercises the response parsing fallback.
480 r = mock.Mock()
481 r.status_code = requests.codes.ok
482 r.content = b"OK"
483 mock_post.return_value = r
484
485 obj = NotifySMSC(user=LOGIN, password=PASSWORD, targets=["+71234567890"])
486
487 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
488 assert bool(obj.notify(body="Image", attach=attach)) is True
489
490
491 @mock.patch("requests.post")
492 def test_plugin_smsc_parse_url(mock_post):
493 """NotifySMSC() parse_url covers all input forms."""
494
495 # Standard form
496 result = NotifySMSC.parse_url(
497 "smsc://login:pass@+71234567890/+79876543210"
498 )
499 assert result is not None
500 obj = NotifySMSC(**result)
501 assert len(obj.targets) == 2
502
503 # ?to= alias
504 result = NotifySMSC.parse_url(
505 "smsc://login:pass@+71234567890?to=%2B79876543210"
506 )
507 assert result is not None
508 obj = NotifySMSC(**result)
509 assert len(obj.targets) == 2
510
511 # ?sender= and ?translit=
512 result = NotifySMSC.parse_url(
513 "smsc://login:pass@+71234567890?sender=Biz&translit=yes"
514 )
515 assert result is not None
516 obj = NotifySMSC(**result)
517 assert obj.sender == "Biz"
518 assert obj.translit is True
519
520 # Bad URL (None) returns None
521 result = NotifySMSC.parse_url(None)
522 assert result is None
523
524
525 @mock.patch("requests.post")
526 def test_plugin_smsc_apprise_integration(mock_post):
527 """NotifySMSC() integrates correctly with the Apprise engine."""
528
529 r = mock.Mock()
530 r.status_code = requests.codes.ok
531 r.content = json.dumps({"id": "42", "cnt": 1}).encode()
532 mock_post.return_value = r
533
534 a = Apprise()
535 assert a.add("smsc://login:password@+71234567890")
536 assert a.notify(body="Integration test", notify_type=NotifyType.INFO)
537 assert mock_post.call_count == 1