Debian Codegraph @

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