Debian Codegraph @

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