Debian Codegraph @

tests/test_plugin_evolution.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 json import loads
29 import logging
30 from unittest import mock
31
32 from helpers import AppriseURLTester
33 import pytest
34 import requests
35
36 from apprise import Apprise, NotifyFormat
37 from apprise.plugins.evolution import NotifyEvolution
38
39 logging.disable(logging.CRITICAL)
40
41 # ---------------------------------------------------------------------------
42 # URL-based tests — exercised by AppriseURLTester
43 # ---------------------------------------------------------------------------
44
45 apprise_url_tests = (
46 # No host — parse_url returns None
47 (
48 "evolution://",
49 {
50 "instance": None,
51 },
52 ),
53 # No host, explicit empty credentials
54 (
55 "evolution://:@/",
56 {
57 "instance": None,
58 },
59 ),
60 # Missing apikey (no user field)
61 (
62 "evolution://hostname/myinstance/5511999999999",
63 {
64 "instance": TypeError,
65 },
66 ),
67 # Missing instance (single path entry treated as instance; no phone left)
68 (
69 "evolution://myapikey@hostname/5511999999999",
70 {
71 "instance": TypeError,
72 },
73 ),
74 # Missing phone number
75 (
76 "evolution://myapikey@hostname/myinstance",
77 {
78 "instance": TypeError,
79 },
80 ),
81 # Invalid phone number
82 (
83 "evolution://myapikey@hostname/myinstance/notaphone",
84 {
85 "instance": TypeError,
86 },
87 ),
88 # Valid HTTP — minimal
89 (
90 "evolution://myapikey@hostname/myinstance/5511999999999",
91 {
92 "instance": NotifyEvolution,
93 "privacy_url": (
94 "evolution://m...y@hostname/myinstance/5511999999999"
95 ),
96 },
97 ),
98 # Valid HTTPS
99 (
100 "evolutions://myapikey@hostname/myinstance/5511999999999",
101 {
102 "instance": NotifyEvolution,
103 "privacy_url": (
104 "evolutions://m...y@hostname/myinstance/5511999999999"
105 ),
106 },
107 ),
108 # Custom port
109 (
110 "evolution://myapikey@hostname:8080/myinstance/5511999999999",
111 {
112 "instance": NotifyEvolution,
113 "privacy_url": (
114 "evolution://m...y@hostname:8080/myinstance/5511999999999"
115 ),
116 },
117 ),
118 # Multiple targets
119 (
120 "evolution://myapikey@hostname/myinstance/5511999999999/5521888888888",
121 {
122 "instance": NotifyEvolution,
123 },
124 ),
125 # Target via ?to=
126 (
127 "evolution://myapikey@hostname/myinstance/5511999999999"
128 "?to=5521888888888",
129 {
130 "instance": NotifyEvolution,
131 },
132 ),
133 # Force HTTP error
134 (
135 "evolution://myapikey@hostname/myinstance/5511999999999",
136 {
137 "instance": NotifyEvolution,
138 "response": False,
139 "requests_response_code": requests.codes.internal_server_error,
140 },
141 ),
142 # Unknown HTTP response code
143 (
144 "evolution://myapikey@hostname/myinstance/5511999999999",
145 {
146 "instance": NotifyEvolution,
147 "response": False,
148 "requests_response_code": 999,
149 },
150 ),
151 # Connection exceptions
152 (
153 "evolution://myapikey@hostname/myinstance/5511999999999",
154 {
155 "instance": NotifyEvolution,
156 "test_requests_exceptions": True,
157 },
158 ),
159 )
160
161
162 def test_plugin_evolution_urls():
163 """NotifyEvolution() Apprise URLs."""
164 AppriseURLTester(tests=apprise_url_tests).run_all()
165
166
167 # ---------------------------------------------------------------------------
168 # Edge cases
169 # ---------------------------------------------------------------------------
170
171
172 def test_plugin_evolution_parse_url_no_path():
173 """NotifyEvolution.parse_url() returns instance=None when path is empty."""
174 result = NotifyEvolution.parse_url("evolution://key@host")
175 assert result is not None
176 assert result["instance"] is None
177
178
179 def test_plugin_evolution_edge_cases():
180 """NotifyEvolution() direct instantiation edge cases."""
181
182 # No apikey
183 with pytest.raises(TypeError):
184 NotifyEvolution(
185 apikey=None, instance="inst", targets=["5511999999999"]
186 )
187
188 # Blank apikey
189 with pytest.raises(TypeError):
190 NotifyEvolution(
191 apikey=" ", instance="inst", targets=["5511999999999"]
192 )
193
194 # No instance
195 with pytest.raises(TypeError):
196 NotifyEvolution(apikey="key", instance=None, targets=["5511999999999"])
197
198 # No targets
199 with pytest.raises(TypeError):
200 NotifyEvolution(apikey="key", instance="inst", targets=[])
201
202 # All targets invalid
203 with pytest.raises(TypeError):
204 NotifyEvolution(
205 apikey="key", instance="inst", targets=["notaphone", "xx"]
206 )
207
208
209 # ---------------------------------------------------------------------------
210 # send() payload and header verification
211 # ---------------------------------------------------------------------------
212
213
214 @mock.patch("requests.post")
215 def test_plugin_evolution_send(mock_post):
216 """NotifyEvolution() verifies POST payload and headers."""
217
218 mock_post.return_value = requests.Request()
219 mock_post.return_value.status_code = requests.codes.ok
220
221 obj = Apprise.instantiate(
222 "evolution://MYAPIKEY@localhost:8080/myinstance/5511999999999"
223 )
224 assert isinstance(obj, NotifyEvolution)
225
226 assert obj.notify(body="Hello World", title="Test") is True
227 assert mock_post.call_count == 1
228
229 # Verify URL
230 call = mock_post.call_args
231 assert "localhost:8080" in call[0][0]
232 assert "/message/sendText/myinstance" in call[0][0]
233
234 # Verify headers
235 headers = call[1]["headers"]
236 assert headers["apikey"] == "MYAPIKEY"
237 assert headers["Content-Type"] == "application/json"
238
239 # Verify payload
240 payload = loads(call[1]["data"])
241 assert payload["number"] == "5511999999999"
242 assert "Hello World" in payload["text"]
243
244
245 @mock.patch("requests.post")
246 def test_plugin_evolution_multiple_targets(mock_post):
247 """NotifyEvolution() sends one request per target."""
248
249 mock_post.return_value = requests.Request()
250 mock_post.return_value.status_code = requests.codes.ok
251
252 obj = Apprise.instantiate(
253 "evolution://key@host/inst/5511111111111/5522222222222/5533333333333"
254 )
255 assert isinstance(obj, NotifyEvolution)
256 assert len(obj) == 3
257
258 assert obj.notify(body="msg") is True
259 assert mock_post.call_count == 3
260
261 numbers = [loads(c[1]["data"])["number"] for c in mock_post.call_args_list]
262 assert "5511111111111" in numbers
263 assert "5522222222222" in numbers
264 assert "5533333333333" in numbers
265
266
267 @mock.patch("requests.post")
268 def test_plugin_evolution_partial_failure(mock_post):
269 """NotifyEvolution() returns False if any target fails."""
270
271 r_ok = requests.Request()
272 r_ok.status_code = requests.codes.ok
273 r_ok.content = b""
274
275 r_err = requests.Request()
276 r_err.status_code = requests.codes.internal_server_error
277 r_err.content = b"error"
278
279 mock_post.side_effect = [r_ok, r_err]
280
281 obj = Apprise.instantiate(
282 "evolution://key@host/inst/5511111111111/5522222222222"
283 )
284 assert obj.notify(body="msg") is False
285 assert mock_post.call_count == 2
286
287
288 @mock.patch("requests.post")
289 def test_plugin_evolution_title_in_body(mock_post):
290 """NotifyEvolution() merges the title into the body via Apprise."""
291
292 mock_post.return_value = requests.Request()
293 mock_post.return_value.status_code = requests.codes.ok
294
295 obj = Apprise.instantiate("evolution://key@host/inst/5511999999999")
296 assert obj.notify(body="body text", title="My Title") is True
297
298 payload = loads(mock_post.call_args[1]["data"])
299 assert "My Title" in payload["text"]
300 assert "body text" in payload["text"]
301
302
303 @mock.patch("requests.post")
304 def test_plugin_evolution_https(mock_post):
305 """NotifyEvolution() uses HTTPS when evolutions:// schema is given."""
306
307 mock_post.return_value = requests.Request()
308 mock_post.return_value.status_code = requests.codes.ok
309
310 obj = Apprise.instantiate(
311 "evolutions://[email protected]/inst/5511999999999"
312 )
313 assert isinstance(obj, NotifyEvolution)
314 assert obj.secure is True
315
316 assert obj.notify(body="secure msg") is True
317 url = mock_post.call_args[0][0]
318 assert url.startswith("https://")
319
320
321 @mock.patch("requests.post")
322 def test_plugin_evolution_html_to_markdown_hardening(mock_post):
323 """Test edge cases in the CommonMark-to-WhatsApp dialect
324 adaptation."""
325
326 mock_post.return_value = requests.Request()
327 mock_post.return_value.status_code = requests.codes.ok
328 mock_post.return_value.content = b"{}"
329 mock_post.return_value.text = "{}"
330
331 def notify(body):
332 aobj = Apprise()
333 assert aobj.add("evolutions://key@host/inst/5511999999999")
334 assert aobj.notify(body=body, body_format=NotifyFormat.HTML) is True
335 payload = loads(mock_post.call_args_list[-1][1]["data"])
336 mock_post.reset_mock()
337 return payload["text"]
338
339 # Convert CommonMark emphasis to WhatsApp delimiters.
340 assert notify("<b>hello</b> <i>world</i>") == "*hello* _world_"
341
342 # Preserve adjacent nested emphasis.
343 assert notify("<b><i>x</i></b>") == "*_x_*"
344
345 # Non-adjacent nesting and sibling spans are unaffected.
346 assert notify("<b>bold <i>italic</i> still bold</b>") == (
347 "*bold _italic_ still bold*"
348 )
349 assert notify("<b>A</b><b>B</b>") == "*A**B*"
350
351 # Map inline and fenced code to WhatsApp's monospace syntax.
352 assert notify("<code>inline</code>") == "```inline```"
353 assert notify("<pre><code>block code</code></pre>") == (
354 "```\nblock code\n```"
355 )
356
357 # Preserve link labels beside WhatsApp's auto-linked URL.
358 assert (
359 notify('<a href="https://example.com/x">click here</a>')
360 == "click here (https://example.com/x)"
361 )
362
363 # Direct WhatsApp Markdown remains unchanged.
364 aobj = Apprise()
365 assert aobj.add("evolutions://key@host/inst/5511999999999")
366 assert aobj.notify(body="*already* whatsapp-bound markdown") is True
367 payload = loads(mock_post.call_args_list[-1][1]["data"])
368 assert payload["text"] == "*already* whatsapp-bound markdown"
369 mock_post.reset_mock()
370
371 # Drop CommonMark escapes unsupported by WhatsApp.
372 assert notify("<p>literal * asterisk</p>") == "literal * asterisk"
373
374 f = NotifyEvolution._commonmark_to_whatsapp
375
376 # Preserve unmatched backticks as literal text.
377 assert f("text ``unterminated") == "text ``unterminated"
378
379 # Collapse runs of three or more backticks without dropping spaces.
380 # Three backticks collapse to two.
381 assert f("`` code```here ``") == "``` code``here ```"
382 # Longer backtick runs also collapse to two in one substitution.
383 assert f("````` content```` end `````") == "``` content`` end ```"
384
385 # Collapse empty entities without affecting following content.
386 assert f("****x") == "x"
387
388 # Close nonempty unterminated emphasis and drop empty spans.
389 assert f("**unterminated") == "*unterminated*"
390 assert f("**") == ""
391
392 # Preserve an incomplete link as literal text.
393 assert f("[text](<https://example.com/unterminated") == (
394 "[text](<https://example.com/unterminated"
395 )
396
397 # Resolve CommonMark escapes inside WhatsApp link destinations.
398 assert f("[click](<https://e/x\\>y>)") == "click (https://e/x>y)"
399
400 # A link with no text at all -- the bare URL is kept on its own
401 # rather than emitting a dangling " (url)".
402 assert f("[](<https://example.com/x>)") == "https://example.com/x"
403
404 # HTML body with a title: title is merged into the body as a heading
405 # before the WhatsApp dialect conversion runs (covers _build_send_calls
406 # title-merge branch).
407 aobj = Apprise()
408 assert aobj.add("evolutions://key@host/inst/5511999999999")
409 assert (
410 aobj.notify(
411 body="<b>hello</b>",
412 title="My Title",
413 body_format=NotifyFormat.HTML,
414 )
415 is True
416 )
417 payload = loads(mock_post.call_args_list[-1][1]["data"])
418 assert payload["text"] == "*My Title*\n*hello*"
419 mock_post.reset_mock()
420
421 # Title that reduces to an empty string after stripping leading heading
422 # and list characters (html_to_markdown converts " - " to "-").
423 # The heading is skipped and the title field is cleared regardless.
424 assert (
425 aobj.notify(
426 body="<b>hello</b>",
427 title=" - ",
428 body_format=NotifyFormat.HTML,
429 )
430 is True
431 )
432 payload = loads(mock_post.call_args_list[-1][1]["data"])
433 assert payload["text"] == "*hello*"
434 mock_post.reset_mock()