Debian Codegraph @

tests/test_plugin_evolution.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 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.exception import AppriseImproperlyConfigured
38 from apprise.plugins.evolution import NotifyEvolution
39
40 logging.disable(logging.CRITICAL)
41
42 # ---------------------------------------------------------------------------
43 # URL-based tests — exercised by AppriseURLTester
44 # ---------------------------------------------------------------------------
45
46 apprise_url_tests = (
47 # No host — parse_url returns None
48 (
49 "evolution://",
50 {
51 "instance": None,
52 },
53 ),
54 # No host, explicit empty credentials
55 (
56 "evolution://:@/",
57 {
58 "instance": None,
59 },
60 ),
61 # Missing apikey (no user field)
62 (
63 "evolution://hostname/myinstance/5511999999999",
64 {
65 "instance": AppriseImproperlyConfigured,
66 },
67 ),
68 # Missing instance (single path entry treated as instance; no phone left)
69 (
70 "evolution://myapikey@hostname/5511999999999",
71 {
72 "instance": AppriseImproperlyConfigured,
73 },
74 ),
75 # Missing phone number
76 (
77 "evolution://myapikey@hostname/myinstance",
78 {
79 "instance": AppriseImproperlyConfigured,
80 },
81 ),
82 # Invalid phone number
83 (
84 "evolution://myapikey@hostname/myinstance/notaphone",
85 {
86 "instance": AppriseImproperlyConfigured,
87 },
88 ),
89 # Valid HTTP — minimal
90 (
91 "evolution://myapikey@hostname/myinstance/5511999999999",
92 {
93 "instance": NotifyEvolution,
94 "privacy_url": (
95 "evolution://m...y@hostname/myinstance/5511999999999"
96 ),
97 },
98 ),
99 # Valid HTTPS
100 (
101 "evolutions://myapikey@hostname/myinstance/5511999999999",
102 {
103 "instance": NotifyEvolution,
104 "privacy_url": (
105 "evolutions://m...y@hostname/myinstance/5511999999999"
106 ),
107 },
108 ),
109 # Custom port
110 (
111 "evolution://myapikey@hostname:8080/myinstance/5511999999999",
112 {
113 "instance": NotifyEvolution,
114 "privacy_url": (
115 "evolution://m...y@hostname:8080/myinstance/5511999999999"
116 ),
117 },
118 ),
119 # Multiple targets
120 (
121 "evolution://myapikey@hostname/myinstance/5511999999999/5521888888888",
122 {
123 "instance": NotifyEvolution,
124 },
125 ),
126 # Target via ?to=
127 (
128 "evolution://myapikey@hostname/myinstance/5511999999999"
129 "?to=5521888888888",
130 {
131 "instance": NotifyEvolution,
132 },
133 ),
134 # Force HTTP error
135 (
136 "evolution://myapikey@hostname/myinstance/5511999999999",
137 {
138 "instance": NotifyEvolution,
139 "response": False,
140 "requests_response_code": requests.codes.internal_server_error,
141 },
142 ),
143 # Unknown HTTP response code
144 (
145 "evolution://myapikey@hostname/myinstance/5511999999999",
146 {
147 "instance": NotifyEvolution,
148 "response": False,
149 "requests_response_code": 999,
150 },
151 ),
152 # Connection exceptions
153 (
154 "evolution://myapikey@hostname/myinstance/5511999999999",
155 {
156 "instance": NotifyEvolution,
157 "test_requests_exceptions": True,
158 },
159 ),
160 )
161
162
163 def test_plugin_evolution_urls():
164 """NotifyEvolution() Apprise URLs."""
165 AppriseURLTester(tests=apprise_url_tests).run_all()
166
167
168 # ---------------------------------------------------------------------------
169 # Edge cases
170 # ---------------------------------------------------------------------------
171
172
173 def test_plugin_evolution_parse_url_no_path():
174 """NotifyEvolution.parse_url() returns instance=None when path is empty."""
175 result = NotifyEvolution.parse_url("evolution://key@host")
176 assert result is not None
177 assert result["instance"] is None
178
179
180 def test_plugin_evolution_edge_cases():
181 """NotifyEvolution() direct instantiation edge cases."""
182
183 # No apikey
184 with pytest.raises(AppriseImproperlyConfigured):
185 NotifyEvolution(
186 apikey=None, instance="inst", targets=["5511999999999"]
187 )
188
189 # Blank apikey
190 with pytest.raises(AppriseImproperlyConfigured):
191 NotifyEvolution(
192 apikey=" ", instance="inst", targets=["5511999999999"]
193 )
194
195 # No instance
196 with pytest.raises(AppriseImproperlyConfigured):
197 NotifyEvolution(apikey="key", instance=None, targets=["5511999999999"])
198
199 # No targets
200 with pytest.raises(AppriseImproperlyConfigured):
201 NotifyEvolution(apikey="key", instance="inst", targets=[])
202
203 # All targets invalid
204 with pytest.raises(AppriseImproperlyConfigured):
205 NotifyEvolution(
206 apikey="key", instance="inst", targets=["notaphone", "xx"]
207 )
208
209
210 # ---------------------------------------------------------------------------
211 # send() payload and header verification
212 # ---------------------------------------------------------------------------
213
214
215 @mock.patch("requests.post")
216 def test_plugin_evolution_send(mock_post):
217 """NotifyEvolution() verifies POST payload and headers."""
218
219 mock_post.return_value = requests.Request()
220 mock_post.return_value.status_code = requests.codes.ok
221
222 obj = Apprise.instantiate(
223 "evolution://MYAPIKEY@localhost:8080/myinstance/5511999999999"
224 )
225 assert isinstance(obj, NotifyEvolution)
226
227 assert bool(obj.notify(body="Hello World", title="Test")) is True
228 assert mock_post.call_count == 1
229
230 # Verify URL
231 call = mock_post.call_args
232 assert "localhost:8080" in call[0][0]
233 assert "/message/sendText/myinstance" in call[0][0]
234
235 # Verify headers
236 headers = call[1]["headers"]
237 assert headers["apikey"] == "MYAPIKEY"
238 assert headers["Content-Type"] == "application/json"
239
240 # Verify payload
241 payload = loads(call[1]["data"])
242 assert payload["number"] == "5511999999999"
243 assert "Hello World" in payload["text"]
244
245
246 @mock.patch("requests.post")
247 def test_plugin_evolution_multiple_targets(mock_post):
248 """NotifyEvolution() sends one request per target."""
249
250 mock_post.return_value = requests.Request()
251 mock_post.return_value.status_code = requests.codes.ok
252
253 obj = Apprise.instantiate(
254 "evolution://key@host/inst/5511111111111/5522222222222/5533333333333"
255 )
256 assert isinstance(obj, NotifyEvolution)
257 assert len(obj) == 3
258
259 assert bool(obj.notify(body="msg")) is True
260 assert mock_post.call_count == 3
261
262 numbers = [loads(c[1]["data"])["number"] for c in mock_post.call_args_list]
263 assert "5511111111111" in numbers
264 assert "5522222222222" in numbers
265 assert "5533333333333" in numbers
266
267
268 @mock.patch("requests.post")
269 def test_plugin_evolution_partial_failure(mock_post):
270 """NotifyEvolution() returns False if any target fails."""
271
272 r_ok = requests.Request()
273 r_ok.status_code = requests.codes.ok
274 r_ok.content = b""
275
276 r_err = requests.Request()
277 r_err.status_code = requests.codes.internal_server_error
278 r_err.content = b"error"
279
280 mock_post.side_effect = [r_ok, r_err]
281
282 obj = Apprise.instantiate(
283 "evolution://key@host/inst/5511111111111/5522222222222"
284 )
285 assert bool(obj.notify(body="msg")) is False
286 assert mock_post.call_count == 2
287
288
289 @mock.patch("requests.post")
290 def test_plugin_evolution_title_in_body(mock_post):
291 """NotifyEvolution() merges the title into the body via Apprise."""
292
293 mock_post.return_value = requests.Request()
294 mock_post.return_value.status_code = requests.codes.ok
295
296 obj = Apprise.instantiate("evolution://key@host/inst/5511999999999")
297 assert bool(obj.notify(body="body text", title="My Title")) is True
298
299 payload = loads(mock_post.call_args[1]["data"])
300 assert "My Title" in payload["text"]
301 assert "body text" in payload["text"]
302
303
304 @mock.patch("requests.post")
305 def test_plugin_evolution_https(mock_post):
306 """NotifyEvolution() uses HTTPS when evolutions:// schema is given."""
307
308 mock_post.return_value = requests.Request()
309 mock_post.return_value.status_code = requests.codes.ok
310
311 obj = Apprise.instantiate(
312 "evolutions://[email protected]/inst/5511999999999"
313 )
314 assert isinstance(obj, NotifyEvolution)
315 assert obj.secure is True
316
317 assert bool(obj.notify(body="secure msg")) is True
318 url = mock_post.call_args[0][0]
319 assert url.startswith("https://")
320
321
322 @mock.patch("requests.post")
323 def test_plugin_evolution_html_to_markdown_hardening(mock_post):
324 """Test edge cases in the CommonMark-to-WhatsApp dialect
325 adaptation."""
326
327 mock_post.return_value = requests.Request()
328 mock_post.return_value.status_code = requests.codes.ok
329 mock_post.return_value.content = b"{}"
330 mock_post.return_value.text = "{}"
331
332 def notify(body):
333 """Send one HTML body through the configured Evolution plugin."""
334 aobj = Apprise()
335 assert aobj.add("evolutions://key@host/inst/5511999999999")
336 assert (
337 bool(aobj.notify(body=body, body_format=NotifyFormat.HTML)) is True
338 )
339 payload = loads(mock_post.call_args_list[-1][1]["data"])
340 mock_post.reset_mock()
341 return payload["text"]
342
343 # Convert CommonMark emphasis to WhatsApp delimiters.
344 assert notify("<b>hello</b> <i>world</i>") == "*hello* _world_"
345
346 # Adjacent nested tags flatten to CommonMark italic around bold.
347 assert notify("<b><i>x</i></b>") == "_*x*_"
348
349 # Non-adjacent nesting and sibling spans are unaffected.
350 assert notify("<b>bold <i>italic</i> still bold</b>") == (
351 "*bold _italic_ still bold*"
352 )
353 # Adjacent bold tags retain their ambiguous middle markers as literals.
354 assert notify("<b>A</b><b>B</b>") == "*A****B*"
355
356 # Map inline and fenced code to WhatsApp's monospace syntax.
357 assert notify("<code>inline</code>") == "```inline```"
358 assert notify("<pre><code>block code</code></pre>") == (
359 "```\nblock code\n```"
360 )
361
362 # Preserve link labels beside WhatsApp's auto-linked URL.
363 assert (
364 notify('<a href="https://example.com/x">click here</a>')
365 == "click here (https://example.com/x)"
366 )
367
368 # Direct WhatsApp Markdown remains unchanged.
369 aobj = Apprise()
370 assert aobj.add("evolutions://key@host/inst/5511999999999")
371 assert bool(aobj.notify(body="*already* whatsapp-bound markdown")) is True
372 payload = loads(mock_post.call_args_list[-1][1]["data"])
373 assert payload["text"] == "*already* whatsapp-bound markdown"
374 mock_post.reset_mock()
375
376 # Drop CommonMark escapes unsupported by WhatsApp.
377 assert notify("<p>literal * asterisk</p>") == "literal * asterisk"
378
379 f = NotifyEvolution._commonmark_to_whatsapp
380
381 # Preserve unmatched backticks as literal text.
382 assert f("text ``unterminated") == "text ``unterminated"
383
384 # Collapse runs of three or more backticks without dropping spaces.
385 # Three backticks collapse to two.
386 assert f("`` code```here ``") == "``` code``here ```"
387 # Longer backtick runs also collapse to two in one substitution.
388 assert f("````` content```` end `````") == "``` content`` end ```"
389
390 # Preserve an opener with no closer.
391 assert f("****x") == "****x"
392
393 # Preserve unmatched markers in a complete body.
394 assert f("**unterminated") == "**unterminated"
395 assert f("**") == "**"
396
397 # User-provided Private Use text must not collide with placeholders.
398 marker = chr(0xE000)
399 attack = f"before {marker}0{marker} after"
400 assert f(attack) == attack
401 assert f(f"*bold* {attack}") == f"_bold_ {attack}"
402
403 # Preserve an incomplete link as literal text.
404 assert f("[text](<https://example.com/unterminated") == (
405 "[text](<https://example.com/unterminated"
406 )
407
408 # Resolve CommonMark escapes inside WhatsApp link destinations.
409 assert f("[click](<https://e/x\\>y>)") == "click (https://e/x>y)"
410
411 # A link with no text at all -- the bare URL is kept on its own
412 # rather than emitting a dangling " (url)".
413 assert f("[](<https://example.com/x>)") == "https://example.com/x"
414
415 # Convert a leading title heading to bold.
416 assert f("# Heading\nbody") == "*Heading*\nbody"
417
418 # A genuine heading appearing later in the body (e.g. from an HTML
419 # <h2> elsewhere in the source, not just a merged title) also
420 # converts -- headings are not limited to the first line.
421 assert f("intro\n## Real heading\nmore text") == (
422 "intro\n*Real heading*\nmore text"
423 )
424
425 # A "#"-prefixed line inside a fenced code block must stay literal.
426 assert f("intro\n```\n# not a heading\ncode\n```\nend") == (
427 "intro\n```\n# not a heading\ncode\n```\nend"
428 )
429
430 # Same for an inline code span.
431 assert f("see `# not code` here") == "see ```# not code``` here"
432
433 # A genuine heading appearing after a code span that has already
434 # closed must still convert. The span cursor has to advance past
435 # the already-finished span, instead of treating the heading as
436 # still inside it.
437 assert f("`code` end\n# Heading\nmore") == (
438 "```code``` end\n*Heading*\nmore"
439 )
440
441 # The framework merges titles as headings, which WhatsApp renders bold.
442 aobj = Apprise()
443 assert aobj.add("evolutions://key@host/inst/5511999999999")
444 assert (
445 bool(
446 aobj.notify(
447 body="<b>hello</b>",
448 title="My Title",
449 body_format=NotifyFormat.HTML,
450 )
451 )
452 is True
453 )
454 payload = loads(mock_post.call_args_list[-1][1]["data"])
455 assert payload["text"] == "*My Title*\n*hello*"
456 mock_post.reset_mock()
457
458 # Title that reduces to an empty string after stripping leading heading
459 # and list characters (html_to_markdown converts " - " to "-").
460 # The heading is skipped and the title field is cleared regardless.
461 assert (
462 bool(
463 aobj.notify(
464 body="<b>hello</b>",
465 title=" - ",
466 body_format=NotifyFormat.HTML,
467 )
468 )
469 is True
470 )
471 payload = loads(mock_post.call_args_list[-1][1]["data"])
472 assert payload["text"] == "*hello*"
473 mock_post.reset_mock()
474
475
476 @mock.patch("requests.post")
477 def test_plugin_evolution_markdown_dialect_conversion(
478 mock_post,
479 ):
480 """Declared Markdown gets WhatsApp dialect completion."""
481
482 mock_post.return_value = requests.Request()
483 mock_post.return_value.status_code = requests.codes.ok
484 mock_post.return_value.content = b"{}"
485
486 aobj = Apprise()
487 assert aobj.add("evolution://key@host/inst/5511999999999")
488
489 assert (
490 bool(
491 aobj.notify(
492 body="*bold* [click here](<https://example.com/x>)",
493 body_format=NotifyFormat.MARKDOWN,
494 )
495 )
496 is True
497 )
498 payload = loads(mock_post.call_args_list[-1][1]["data"])
499 assert payload["text"] == "_bold_ click here (https://example.com/x)"
500
501 # Directly verify the hook leaves unsupported formats unchanged.
502 inst = aobj[0]
503 body = "*bold*"
504 assert inst.dialect_convert(body, NotifyFormat.HTML) == body
505
506
507 def test_plugin_evolution_bare_link_and_autolink_dialect():
508 """Bare-paren links and standalone autolinks convert safely."""
509
510 # Bare destinations convert without treating URL punctuation as emphasis.
511 assert (
512 NotifyEvolution._commonmark_to_whatsapp("[click here](https://a*b)")
513 == "click here (https://a*b)"
514 )
515
516 # A destination containing whitespace remains literal.
517 assert (
518 NotifyEvolution._commonmark_to_whatsapp("[label](has space)")
519 == "[label](has space)"
520 )
521
522 # An unfinished destination also remains literal.
523 assert (
524 NotifyEvolution._commonmark_to_whatsapp("[label](unterminated")
525 == "[label](unterminated"
526 )
527
528 # WhatsApp autolinks the URL after its brackets are removed.
529 assert (
530 NotifyEvolution._commonmark_to_whatsapp("see <https://a*b> now")
531 == "see https://a*b now"
532 )
533
534 # A "<" that never forms a valid scheme is passed through literally.
535 assert NotifyEvolution._commonmark_to_whatsapp("a < b") == "a < b"
536
537 # An unfinished autolink stays literal, including its inner ``*``.
538 assert (
539 NotifyEvolution._commonmark_to_whatsapp("see <https://a*b end")
540 == "see <https://a*b end"
541 )
542
543
544 def test_plugin_evolution_nested_angle_link():
545 """Keep the outer link when a nested angle link is invalid."""
546
547 # Retire only the invalid inner label so the outer link still converts.
548 body = "[OUTER [INNER](<badstuff)](https://example.com)"
549 assert NotifyEvolution._commonmark_to_whatsapp(body) == (
550 "OUTER [INNER](<badstuff) (https://example.com)"
551 )
552
553
554 def test_plugin_evolution_stray_bracket_retires_opener():
555 """A "]" with no "(" must retire its "[" instead of leaving it
556 pending for a later, unrelated link to reuse."""
557
558 # No "(" ever follows the first "]", so "[label]" is not a link and
559 # must not be spliced into the later, unrelated "](https://...)".
560 body = "[label] and ](https://example.com) end"
561 assert (
562 NotifyEvolution._commonmark_to_whatsapp(body)
563 == "[label] and ](https://example.com) end"
564 )
565
566
567 @mock.patch("requests.post")
568 def test_plugin_evolution_overflow_split_code_fence(mock_post):
569 """Ensure split code never leaves a dangling WhatsApp fence."""
570
571 mock_post.return_value = requests.Request()
572 mock_post.return_value.status_code = requests.codes.ok
573 mock_post.return_value.content = b"{}"
574
575 aobj = Apprise()
576 assert aobj.add("evolutions://key@host/inst/5511999999999?overflow=split")
577
578 content = "line.with.dots-and-dashes_under " * 2000
579 assert (
580 bool(
581 aobj.notify(
582 body=f"<pre>{content}</pre>", body_format=NotifyFormat.HTML
583 )
584 )
585 is True
586 )
587 texts = [loads(c[1]["data"])["text"] for c in mock_post.call_args_list]
588 assert len(texts) >= 2
589 for text in texts:
590 # Each delivered chunk must avoid an unmatched WhatsApp code fence.
591 assert "```" not in text