Debian Codegraph @

tests/test_plugin_signal.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 from inspect import cleandoc
29 from json import loads
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 from unittest import mock
35
36 from helpers import AppriseURLTester
37 import pytest
38 import requests
39
40 from apprise import Apprise, AppriseAttachment, NotifyType
41 from apprise.config import ConfigBase
42 from apprise.plugins.base import NotifyFormat
43 from apprise.plugins.signal_api import NotifySignalAPI
44
45 logging.disable(logging.CRITICAL)
46
47 # Attachment Directory
48 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
49
50
51 @pytest.fixture
52 def request_mock(mocker):
53 """Prepare requests mock."""
54 mock_post = mocker.patch("requests.post")
55 mock_post.return_value = requests.Request()
56 mock_post.return_value.status_code = requests.codes.ok
57 mock_post.return_value.content = ""
58 return mock_post
59
60
61 # Our Testing URLs
62 apprise_url_tests = (
63 (
64 "signal://",
65 {
66 # No host specified
67 "instance": TypeError,
68 },
69 ),
70 (
71 "signal://:@/",
72 {
73 # invalid host
74 "instance": TypeError,
75 },
76 ),
77 (
78 "signal://localhost",
79 {
80 # Just a host provided
81 "instance": TypeError,
82 },
83 ),
84 (
85 "signal://localhost",
86 {
87 # key and secret provided and from but invalid from no
88 "instance": TypeError,
89 },
90 ),
91 (
92 "signal://localhost/123",
93 {
94 # invalid from phone
95 "instance": TypeError,
96 },
97 ),
98 (
99 "signal://localhost/{}/123/".format("1" * 11),
100 {
101 # invalid 'to' phone number
102 "instance": NotifySignalAPI,
103 # Notify will fail because it couldn't send to anyone
104 "response": False,
105 # Our expected url(privacy=True) startswith() response:
106 "privacy_url": "signal://localhost/+{}/123".format("1" * 11),
107 },
108 ),
109 (
110 "signal://localhost:8080/{}/".format("1" * 11),
111 {
112 # one phone number will notify ourselves
113 "instance": NotifySignalAPI,
114 },
115 ),
116 (
117 "signal://localhost:8082/+{}/@group.abcd/".format("2" * 11),
118 {
119 # a valid group
120 "instance": NotifySignalAPI,
121 # Our expected url(privacy=True) startswith() response:
122 "privacy_url": "signal://localhost:8082/+{}/@abcd".format(
123 "2" * 11
124 ),
125 },
126 ),
127 (
128 "signals://localhost/{}/{}?format=markdown".format("1" * 11, "3" * 11),
129 {
130 # Test our markdown flag
131 "instance": NotifySignalAPI,
132 },
133 ),
134 (
135 "signal://localhost:8080/+{}/group.abcd/".format("1" * 11),
136 {
137 # another valid group (without @ symbol)
138 "instance": NotifySignalAPI,
139 # Our expected url(privacy=True) startswith() response:
140 "privacy_url": "signal://localhost:8080/+{}/@abcd".format(
141 "1" * 11
142 ),
143 },
144 ),
145 (
146 "signal://localhost:8080/?from={}&to={},{}".format(
147 "1" * 11, "2" * 11, "3" * 11
148 ),
149 {
150 # use get args to acomplish the same thing
151 "instance": NotifySignalAPI,
152 },
153 ),
154 (
155 "signal://localhost:8080/?from={}&to={},{},{}".format(
156 "1" * 11, "2" * 11, "3" * 11, "5" * 3
157 ),
158 {
159 # 2 good targets and one invalid one
160 "instance": NotifySignalAPI,
161 },
162 ),
163 (
164 "signal://localhost:8080/{}/{}/?from={}".format(
165 "1" * 11, "2" * 11, "3" * 11
166 ),
167 {
168 # If we have from= specified, then all elements take on the to=
169 # value
170 "instance": NotifySignalAPI,
171 },
172 ),
173 (
174 "signals://user@localhost/{}/{}".format("1" * 11, "3" * 11),
175 {
176 # use get args to acomplish the same thing (use source instead of
177 # from)
178 "instance": NotifySignalAPI,
179 # Run through code with debug logging enabled
180 "force_debug": True,
181 },
182 ),
183 (
184 "signals://user:password@localhost/{}/{}".format("1" * 11, "3" * 11),
185 {
186 # use get args to acomplish the same thing (use source instead of
187 # from)
188 "instance": NotifySignalAPI,
189 },
190 ),
191 (
192 "signals://user:password@localhost/{}/{}".format("1" * 11, "3" * 11),
193 {
194 "instance": NotifySignalAPI,
195 # Test that a 201 response code is still accepted
196 "requests_response_code": 201,
197 },
198 ),
199 (
200 "signals://localhost/{}/{}/{}?batch=True".format(
201 "1" * 11, "3" * 11, "4" * 11
202 ),
203 {
204 # test batch mode
205 "instance": NotifySignalAPI,
206 },
207 ),
208 (
209 "signals://localhost/{}/{}/{}?status=True".format(
210 "1" * 11, "3" * 11, "4" * 11
211 ),
212 {
213 # test status switch
214 "instance": NotifySignalAPI,
215 },
216 ),
217 (
218 "signal://localhost/{}/{}".format("1" * 11, "4" * 11),
219 {
220 "instance": NotifySignalAPI,
221 # throw a bizarre code forcing us to fail to look it up
222 "response": False,
223 "requests_response_code": 999,
224 },
225 ),
226 (
227 "signal://localhost/{}/{}".format("1" * 11, "4" * 11),
228 {
229 "instance": NotifySignalAPI,
230 # Throws a series of i/o exceptions with this flag
231 # is set and tests that we gracefully handle them
232 "test_requests_exceptions": True,
233 },
234 ),
235 )
236
237
238 def test_plugin_signal_urls():
239 """NotifySignalAPI() Apprise URLs."""
240
241 # Run our general tests
242 AppriseURLTester(tests=apprise_url_tests).run_all()
243
244
245 def test_plugin_signal_edge_cases(request_mock):
246 """NotifySignalAPI() Edge Cases."""
247 # Initialize some generic (but valid) tokens
248 source = "+1 (555) 123-3456"
249 target = "+1 (555) 987-5432"
250 body = "test body"
251 title = "My Title"
252
253 # No apikey specified
254 with pytest.raises(TypeError):
255 NotifySignalAPI(source=None)
256
257 aobj = Apprise()
258 assert aobj.add(f"signals://localhost:231/{source}/{target}")
259 assert aobj.notify(title=title, body=body)
260
261 assert request_mock.call_count == 1
262
263 details = request_mock.call_args_list[0]
264 assert details[0][0] == "https://localhost:231/v2/send"
265 payload = loads(details[1]["data"])
266 assert payload["message"] == "My Title\r\ntest body"
267
268 # Reset our mock object
269 request_mock.reset_mock()
270
271 aobj = Apprise()
272 assert aobj.add(
273 f"signals://user@localhost:231/{source}/{target}?status=True"
274 )
275 assert aobj.notify(title=title, body=body)
276
277 assert request_mock.call_count == 1
278
279 details = request_mock.call_args_list[0]
280 assert details[0][0] == "https://localhost:231/v2/send"
281 payload = loads(details[1]["data"])
282 # Status flag is set
283 assert payload["message"] == "[i] My Title\r\ntest body"
284
285
286 def test_plugin_signal_yaml_config(request_mock):
287 """NotifySignalAPI() YAML Configuration."""
288
289 # Load our configuration
290 result, _ = ConfigBase.config_parse_yaml(
291 cleandoc("""
292 urls:
293 - signal://signal:8080/+1234567890:
294 - to: +0987654321
295 tag: signal
296 """)
297 )
298
299 # Verify we loaded correctly
300 assert isinstance(result, list)
301 assert len(result) == 1
302 assert len(result[0].tags) == 1
303 assert "signal" in result[0].tags
304
305 # Let's get our plugin
306 plugin = result[0]
307 assert len(plugin.targets) == 1
308 assert plugin.source == "+1234567890"
309 assert "+0987654321" in plugin.targets
310
311 #
312 # Test another way to get the same results
313 #
314
315 # Load our configuration
316 result, _config = ConfigBase.config_parse_yaml(
317 cleandoc("""
318 urls:
319 - signal://signal:8080/+1234567890/+0987654321:
320 - tag: signal
321 """)
322 )
323
324 # Verify we loaded correctly
325 assert isinstance(result, list)
326 assert len(result) == 1
327 assert len(result[0].tags) == 1
328 assert "signal" in result[0].tags
329
330 # Let's get our plugin
331 plugin = result[0]
332 assert len(plugin.targets) == 1
333 assert plugin.source == "+1234567890"
334 assert "+0987654321" in plugin.targets
335
336
337 def test_plugin_signal_based_on_feedback(request_mock):
338 """NotifySignalAPI() User Feedback Test."""
339 body = "test body"
340 title = "My Title"
341
342 aobj = Apprise()
343 aobj.add(
344 "signal://10.0.0.112:8080/+12512222222/+12513333333/"
345 "12514444444?batch=yes"
346 )
347
348 assert aobj.notify(title=title, body=body)
349
350 # If a batch, there is only 1 post
351 assert request_mock.call_count == 1
352
353 details = request_mock.call_args_list[0]
354 assert details[0][0] == "http://10.0.0.112:8080/v2/send"
355 payload = loads(details[1]["data"])
356 assert payload["message"] == "My Title\r\ntest body"
357 assert payload["number"] == "+12512222222"
358 assert len(payload["recipients"]) == 2
359 assert "+12513333333" in payload["recipients"]
360 # The + is appended
361 assert "+12514444444" in payload["recipients"]
362
363 # Reset our test and turn batch mode off
364 request_mock.reset_mock()
365
366 aobj = Apprise()
367 aobj.add(
368 "signal://10.0.0.112:8080/+12512222222/+12513333333/"
369 "12514444444?batch=no"
370 )
371
372 assert aobj.notify(title=title, body=body)
373
374 # If a batch, there is only 1 post
375 assert request_mock.call_count == 2
376
377 details = request_mock.call_args_list[0]
378 assert details[0][0] == "http://10.0.0.112:8080/v2/send"
379 payload = loads(details[1]["data"])
380 assert payload["message"] == "My Title\r\ntest body"
381 assert payload["number"] == "+12512222222"
382 assert len(payload["recipients"]) == 1
383 assert "+12513333333" in payload["recipients"]
384
385 details = request_mock.call_args_list[1]
386 assert details[0][0] == "http://10.0.0.112:8080/v2/send"
387 payload = loads(details[1]["data"])
388 assert payload["message"] == "My Title\r\ntest body"
389 assert payload["number"] == "+12512222222"
390 assert len(payload["recipients"]) == 1
391
392 # The + is appended
393 assert "+12514444444" in payload["recipients"]
394
395 request_mock.reset_mock()
396
397 # Test group names
398 aobj = Apprise()
399 aobj.add(
400 "signal://10.0.0.112:8080/+12513333333/@group1/@group2/"
401 "12514444444?batch=yes"
402 )
403
404 assert aobj.notify(title=title, body=body)
405
406 # If a batch, there is only 1 post
407 assert request_mock.call_count == 1
408
409 details = request_mock.call_args_list[0]
410 assert details[0][0] == "http://10.0.0.112:8080/v2/send"
411 payload = loads(details[1]["data"])
412 assert payload["message"] == "My Title\r\ntest body"
413 assert payload["number"] == "+12513333333"
414 assert len(payload["recipients"]) == 3
415 assert "+12514444444" in payload["recipients"]
416 # our groups
417 assert "group.group1" in payload["recipients"]
418 assert "group.group2" in payload["recipients"]
419 # Groups are stored properly
420 assert "/@group1" in aobj[0].url()
421 assert "/@group2" in aobj[0].url()
422 # Our target phone number is also in the path
423 assert "/+12514444444" in aobj[0].url()
424
425
426 def test_notify_signal_plugin_attachments(request_mock):
427 """NotifySignalAPI() Attachments."""
428
429 obj = Apprise.instantiate(
430 "signal://10.0.0.112:8080/+12512222222/+12513333333/"
431 "12514444444?batch=no"
432 )
433 assert isinstance(obj, NotifySignalAPI)
434
435 # Test Valid Attachment
436 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
437 attach = AppriseAttachment(path)
438 assert (
439 obj.notify(
440 body="body",
441 title="title",
442 notify_type=NotifyType.INFO,
443 attach=attach,
444 )
445 is True
446 )
447
448 # Test invalid attachment
449 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
450 assert (
451 obj.notify(
452 body="body",
453 title="title",
454 notify_type=NotifyType.INFO,
455 attach=path,
456 )
457 is False
458 )
459
460 # Test Valid Attachment (load 3)
461 path = (
462 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
463 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
464 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
465 )
466 attach = AppriseAttachment(path)
467
468 # Return our good configuration
469 with mock.patch("builtins.open", side_effect=OSError()):
470 # We can't send the message we can't open the attachment for reading
471 assert (
472 obj.notify(
473 body="body",
474 title="title",
475 notify_type=NotifyType.INFO,
476 attach=attach,
477 )
478 is False
479 )
480
481 # test the handling of our batch modes
482 obj = Apprise.instantiate(
483 "signal://10.0.0.112:8080/+12512222222/+12513333333/"
484 "12514444444?batch=yes"
485 )
486 assert isinstance(obj, NotifySignalAPI)
487
488 # Now send an attachment normally without issues
489 request_mock.reset_mock()
490 assert (
491 obj.notify(
492 body="body",
493 title="title",
494 notify_type=NotifyType.INFO,
495 attach=attach,
496 )
497 is True
498 )
499 assert request_mock.call_count == 1
500
501
502 def test_plugin_signal_text_mode_markdown_from_url(request_mock):
503 """NotifySignalAPI() sets text_mode=styled when ?format=markdown"""
504 source = "+1 (555) 123-3456"
505 target = "+1 (555) 987-5432"
506 body = "Body **bold** _italic_"
507 title = "Title"
508
509 aobj = Apprise()
510 # Use URL path tokens, add the markdown format via query string
511 assert aobj.add(
512 f"signals://localhost:231/{source}/{target}?format=markdown"
513 )
514 assert aobj.notify(title=title, body=body)
515
516 assert request_mock.call_count == 1
517 details = request_mock.call_args_list[0]
518
519 payload = loads(details[1]["data"])
520 # Core behaviour we are validating
521 assert payload.get("text_mode") == "styled"
522
523
524 def test_plugin_signal_text_mode_markdown_from_library(request_mock):
525 """NotifySignalAPI() sets text_mode=styled when class format=MARKDOWN"""
526 source = "+1 (555) 123-3456"
527 target = "+1 (555) 987-5432"
528
529 obj = NotifySignalAPI(
530 host="localhost",
531 port=231,
532 secure=True,
533 source=source,
534 targets=[target],
535 format=NotifyFormat.MARKDOWN,
536 )
537
538 assert obj.notify(title="Title", body="Body **bold** _italic_") is True
539
540 assert request_mock.call_count == 1
541 details = request_mock.call_args_list[0]
542
543 payload = loads(details[1]["data"])
544 # Core behaviour we are validating
545 assert payload.get("text_mode") == "styled"