Debian Codegraph @

tests/test_utils_format.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 from apprise import NotifyFormat
28 from apprise.utils.format import html_adjust, markdown_adjust, smart_split
29
30
31 def test_smart_split_prefers_newlines_over_spaces_and_punctuation():
32 """
33 Newlines should win even if there are spaces and punctuation before the
34 limit.
35 """
36 text = "line1\nline2 line3. line4"
37 # Long enough to include the newline and some of the next line
38 limit = 12
39
40 chunks = smart_split(text, limit, body_format=NotifyFormat.TEXT)
41
42 # First chunk should end immediately after the newline
43 assert chunks[0] == "line1\n"
44 # Nothing lost
45 assert "".join(chunks) == text
46
47
48 def test_smart_split_prefers_spaces_over_hard_split():
49 """
50 When there are no newlines, split on the last space/tab before falling back
51 to a hard character-limit split.
52 """
53 text = "word1 word2 word3"
54 # Force a split between word2 and word3
55 limit = 12 # "word1 word2 " is 12 characters
56
57 chunks = smart_split(text, limit, body_format=NotifyFormat.TEXT)
58
59 assert chunks == ["word1 word2 ", "word3"]
60 assert "".join(chunks) == text
61
62
63 def test_smart_split_can_split_after_punctuation_plus_whitespace():
64 """
65 Exercise the punctuation+whitespace pattern. In practice this collapses
66 to the same split point as the last space, but we verify the behaviour.
67 """
68 text = "Hello world. Again"
69 # Force the split around ". "
70
71 # "Hello world. " is 13 characters
72 limit = 13
73
74 chunks = smart_split(text, limit, body_format=NotifyFormat.TEXT)
75
76 # First chunk should end at the space after the period
77 assert chunks[0] == "Hello world. "
78 assert chunks[1] == "Again"
79 assert "".join(chunks) == text
80
81
82 def test_smart_split_avoids_splitting_inside_html_entity() -> None:
83 """
84 In HTML mode we must not end a chunk in the middle of '&...;'.
85
86 We do NOT assert exact chunk values. Instead we assert:
87 - TEXT mode can split inside the entity.
88 - HTML mode never has a chunk that contains '&' without a matching ';'
89 after it in the same chunk.
90 """
91 text = "1234&nbsp;5678"
92 limit = 8 # without adjustment, we would cut inside '&nbsp;'
93
94 # Plain text mode: allowed to split anywhere
95 chunks_text = smart_split(text, limit, body_format=NotifyFormat.TEXT)
96 assert "".join(chunks_text) == text
97
98 # Sanity: in TEXT mode we *do* split inside the entity
99 assert any(
100 "&" in chunk and ";" not in chunk[chunk.find("&") :]
101 for chunk in chunks_text
102 )
103
104 # HTML mode: entity-aware
105 chunks_html = smart_split(text, limit, body_format=NotifyFormat.HTML)
106 assert "".join(chunks_html) == text
107
108 # If a chunk contains '&', it must also contain the terminating ';'
109 # for that entity within the same chunk.
110 for chunk in chunks_html:
111 idx = chunk.find("&")
112 if idx == -1:
113 continue
114 semi = chunk.find(";", idx + 1)
115 assert semi != -1, f"Chunk ends inside HTML entity: {chunk!r}"
116
117
118 def test_smart_split_avoids_splitting_inside_markdown_link() -> None:
119 """
120 In MARKDOWN mode, do not split inside [text](url).
121
122 We only require that the full [link](...) lies in a single chunk and that
123 any '[' appearing in a chunk has a matching ')' in that same chunk.
124 """
125 link = "[link](https://example.com)"
126 text = "AAAA" + link
127 limit = len(link)
128
129 chunks = smart_split(text, limit, body_format=NotifyFormat.MARKDOWN)
130 assert "".join(chunks) == text
131
132 # Entire link must be contained in one chunk
133 assert any(link in chunk for chunk in chunks)
134
135 # If a chunk has '[', it must also contain its closing ')'
136 for chunk in chunks:
137 idx = chunk.find("[")
138 if idx == -1:
139 continue
140 semi = chunk.find(")", idx + 1)
141 assert semi != -1, f"Markdown link was split inside chunk: {chunk!r}"
142
143
144 def test_smart_split_avoids_splitting_inside_markdown_image() -> None:
145 """
146 In MARKDOWN mode, do not split inside the [alt](url) of an image.
147
148 The implementation currently splits "AAAA![alt](...)" as:
149 - "AAAA!"
150 - "[alt](...)"
151 which is acceptable, as the [alt](url) part is kept intact.
152 """
153 image = "![alt](https://example.com/image.png)"
154 text = "AAAA" + image
155 limit = len(image)
156
157 chunks = smart_split(text, limit, body_format=NotifyFormat.MARKDOWN)
158 assert "".join(chunks) == text
159
160 inner = "[alt](https://example.com/image.png)"
161
162 # The [alt](...) portion must appear fully within a single chunk
163 assert any(inner in chunk for chunk in chunks)
164
165 # As with links, any '[' in a chunk must have its matching ')' within
166 # the same chunk so we never split inside the [alt](url) part.
167 for chunk in chunks:
168 idx = chunk.find("[")
169 if idx == -1:
170 continue
171 semi = chunk.find(")", idx + 1)
172 assert semi != -1, f"Markdown image was split inside chunk: {chunk!r}"
173
174
175 def test_smart_split_empty_and_none_input() -> None:
176 """
177 Empty / None input should be returned as a single-element list unchanged.
178 """
179 assert smart_split("", 10, body_format=NotifyFormat.TEXT) == [""]
180 assert smart_split("", 0, body_format=NotifyFormat.TEXT) == [""]
181 assert smart_split("content", 0, body_format=NotifyFormat.TEXT) == [""]
182 # None short-circuits before len() is called
183 assert smart_split(None, 10, body_format=NotifyFormat.TEXT) == [""]
184
185
186 def test_smart_split_html_entity_exact_boundary() -> None:
187 """
188 Splitting exactly at an HTML entity boundary should not shift the split
189 point (no need to "fix up" a perfectly aligned boundary).
190 """
191 text = "AAAA&nbsp;BBBB"
192 limit = len("AAAA&nbsp;") # split exactly after the entity
193
194 chunks = smart_split(text, limit, body_format=NotifyFormat.HTML)
195
196 # We expect the entity to remain whole in the first chunk
197 assert chunks == ["AAAA&nbsp;", "BBBB"]
198 assert "".join(chunks) == text
199
200
201 def test_smart_split_markdown_link_exact_boundary() -> None:
202 """
203 Splitting exactly after a Markdown link should not cause any adjustment.
204 """
205 link = "[link](https://example.com)"
206 tail = " TAIL"
207 text = link + tail
208 limit = len(link) # split immediately after ')'
209
210 chunks = smart_split(text, limit, body_format=NotifyFormat.MARKDOWN)
211
212 # First chunk is exactly the link, second is the remainder
213 assert chunks[0] == link
214 assert "".join(chunks) == text
215
216 # Sanity: the link itself is not split across chunks
217 assert any(link in chunk for chunk in chunks)
218
219
220 def test_smart_split_whitespace_priority_with_tabs_and_newlines() -> None:
221 """
222 Exercise newline vs space/tab priority with a mix of whitespace.
223 """
224 text = "word1\tword2\nword3"
225
226 # Case 1: window ends just before the newline, so only tab is visible.
227 limit_without_newline = text.index("\n") # position of '\n'
228 chunks_no_nl = smart_split(
229 text, limit_without_newline, body_format=NotifyFormat.TEXT
230 )
231 # First chunk should end after the tab, since that is the last space/tab
232 assert chunks_no_nl[0] == "word1\t"
233 assert "".join(chunks_no_nl) == text
234
235 # Case 2: window includes the newline; newline should win over tab.
236 limit_with_newline = text.index("\n") + 1
237 chunks_with_nl = smart_split(
238 text, limit_with_newline, body_format=NotifyFormat.TEXT
239 )
240 # First chunk should now end after the newline
241 assert chunks_with_nl[0] == "word1\tword2\n"
242 assert "".join(chunks_with_nl) == text
243
244
245 def test_smart_split_very_short_limit() -> None:
246 """
247 Very small limits should still split deterministically without loss.
248 """
249 text = "ABC"
250 chunks = smart_split(text, 1, body_format=NotifyFormat.TEXT)
251
252 # One character per chunk
253 assert chunks == ["A", "B", "C"]
254 assert "".join(chunks) == text
255
256
257 def test_smart_split_very_long_limit() -> None:
258 """
259 Very large limits (>= len(text)) should return a single chunk.
260 """
261 text = "A short message for testing"
262 chunks = smart_split(text, 10_000, body_format=NotifyFormat.TEXT)
263
264 assert chunks == [text]
265 assert "".join(chunks) == text
266
267
268 def test_html_adjust_guard_paths_and_no_entity() -> None:
269 """
270 Cover the early-return guard in html_adjust and the path where there is
271 no '&' at all in the search window.
272 """
273 text = "abcdef"
274
275 # split_at <= window_start -> early-return unchanged
276 assert html_adjust(text, window_start=2, split_at=2) == 2
277
278 # split_at beyond the end of the text -> early-return unchanged
279 assert (
280 html_adjust(text, window_start=0, split_at=len(text) + 5)
281 == len(text) + 5
282 )
283
284 # No '&' in window, nothing to adjust
285 assert html_adjust(text, window_start=0, split_at=3) == 3
286
287
288 def test_html_adjust_inside_and_at_boundary_of_entity() -> None:
289 """
290 Exercise the path where html_adjust moves the split back to '&' when the
291 split falls inside an entity, and the path where the split is exactly at
292 the entity boundary and should not move.
293 """
294 text = "1234&nbsp;5678"
295 # indexes: 0..3 '1234', 4 '&', 5 'n', 6 'b', 7 's', 8 'p', 9 ';', 10 '5'...
296
297 # Split inside '&nbsp;' (at index 8) -> move back to '&' (index 4)
298 assert html_adjust(text, window_start=0, split_at=8) == 4
299
300 # Split exactly after the ';' (index 10) -> already outside entity
301 assert html_adjust(text, window_start=0, split_at=10) == 10
302
303
304 def test_markdown_adjust_guard_and_no_construct() -> None:
305 """
306 Cover the guard in markdown_adjust and the case where there is no
307 '[' or '!' in the window.
308 """
309 text = "plain text"
310
311 # split_at <= window_start -> early-return unchanged
312 assert markdown_adjust(text, window_start=4, split_at=4) == 4
313
314 # split_at past the end -> early-return unchanged
315 assert (
316 markdown_adjust(text, window_start=0, split_at=len(text) + 3)
317 == len(text) + 3
318 )
319
320 # No markdown constructs -> nothing to adjust
321 assert markdown_adjust(text, window_start=0, split_at=5) == 5
322
323
324 def test_markdown_adjust_inside_construct_moves_to_start() -> None:
325 """
326 Exercise the positive path in markdown_adjust where the split lands
327 inside a [text](url) construct and the function moves the split
328 back to the start of the construct.
329
330 The forward scan is capped at split_at + (split_at - window_start) + 1
331 to prevent O(n^2) work on adversarial input (see
332 test_markdown_adjust_dos_cap). This means split_at must be at least half
333 the link length so the cap reaches the closing ')'. Realistic splits from
334 smart_split() always satisfy this because the following applies for any
335 link that fits in a single chunk:
336 split_at - window_start >= limit >= link_length // 2
337 """
338 link = "[link](https://example.com)"
339 # Choose a split point in the latter half of the link so the symmetric
340 # forward-scan cap (split_at + window_size) reaches the closing ')'.
341 split_at = len(link) // 2 # index 13, inside "ps://example.com"
342 adjusted = markdown_adjust(link, window_start=0, split_at=split_at)
343
344 # Should move back to the '[' at index 0
345 assert adjusted == 0
346
347
348 def test_markdown_adjust_inside_angle_bracket_construct() -> None:
349 """Exercise the <URL|label> angle-bracket path in markdown_adjust.
350
351 When a split point lands ANYWHERE inside a '<url|label>' construct (as
352 used by Slack mrkdwn and Google Chat), the function must move it back to
353 the opening '<'. This covers three sub-cases:
354
355 (a) Split in the label portion (after the pipe).
356 (b) Split exactly on the pipe character.
357 (c) Split in the URL portion (before the pipe) -- previously the pipe
358 search stopped at split_at so no pipe was found; the fix extends
359 the search to forward_end so this case is now also protected.
360 """
361 # A Slack/Google Chat anchor -- '<' at 0, '|' at 21, '>' at 31.
362 text = "<https://example.com|click here>"
363 pipe_pos = text.index("|") # == 20
364
365 # (a) Split a few characters after the pipe, inside the label portion.
366 split_at = pipe_pos + 3
367 adjusted = markdown_adjust(text, window_start=0, split_at=split_at)
368 # Should move back to the '<' at index 0.
369 assert adjusted == 0
370
371 # Split right at the closing '>' -- still inside the construct.
372 split_at2 = text.index(">")
373 adjusted2 = markdown_adjust(text, window_start=0, split_at=split_at2)
374 # Also moves back to '<'.
375 assert adjusted2 == 0
376
377 # (b) Split exactly ON the '|' separator.
378 split_on_pipe = pipe_pos
379 assert markdown_adjust(text, 0, split_on_pipe) == 0
380
381 # (c) Split inside the URL portion (before '|').
382 # The pipe search now extends to forward_end, not just to split_at.
383 # forward_end = min(32, 17 + 17 + 1) = 32, which covers '>' at 31.
384 # Both pipe (20) and '>' (31) are within range; the construct is detected
385 # and the split moves to '<' at 0.
386 split_in_url = pipe_pos - 3 # index 17, inside "example.com"
387 assert markdown_adjust(text, 0, split_in_url) == 0
388
389 # Same scenario with a preamble before '<' so the move is actually
390 # useful -- '<' is no longer at window_start so smart_split would
391 # keep the adjusted position (not reset it).
392 # "<" at 4, "|" at 24, ">" at 35 in the prefixed string.
393 prefixed = "pre " + text
394 split_in_url2 = 20 # index 20, inside "example.com", before '|' at 24
395 # forward_end = min(36, 20+20+1) = 36 > 35 ('>').
396 assert markdown_adjust(prefixed, 0, split_in_url2) == 4 # '<' position
397
398 # When split_at is so small that forward_end doesn't reach the pipe,
399 # the construct is undetectable and the split falls through unchanged.
400 # forward_end = min(32, 5 + 5 + 1) = 11 < pipe_pos(20), so no pipe found.
401 # Even if we detected the '<' at 0, moving the split there would equal
402 # window_start so smart_split() would reset it anyway -- no net change.
403 split_too_small = 5
404 assert markdown_adjust(text, 0, split_too_small) == split_too_small
405
406 # '<' and '|' are both found, but split_at is past the closing '>'
407 # so the condition angle_start_idx < split_at <= angle_end_idx is
408 # False -- the function returns the split point unchanged.
409 split_past_end = len(text)
410 assert markdown_adjust(text, 0, split_past_end) == split_past_end
411
412
413 def test_markdown_adjust_dos_cap() -> None:
414 """markdown_adjust forward scan is capped to O(window_size).
415
416 An adversarial body of repeated unterminated '[' openers must not
417 cause O(n^2) work. We verify the cap by checking that a large body
418 produces the same split position as a small one (the cap does not
419 change the output for well-formed constructs within the window).
420 """
421 from timeit import default_timer
422
423 # 1 MB of repeated '[broken ' with no closing ')'.
424 body = "[broken " * 128_000
425 limit = 80
426 start = default_timer()
427 chunks = smart_split(body, limit, body_format=NotifyFormat.MARKDOWN)
428 elapsed = default_timer() - start
429
430 # Must complete well under 1 second (the DoS took ~14 s before the cap).
431 assert elapsed < 1.0
432 # All chunks must be non-empty and re-join to the original.
433 assert all(chunks)
434 assert "".join(chunks) == body
435
436
437 def test_smart_split_markdown_guard_split_at_start_is_reset() -> None:
438 """Cover smart_split guard 'if split_at <= start: split_at = orig_split'.
439
440 We force markdown_adjust to move the split back to the window start
441 (link_start_idx == start == 0), then verify smart_split resets to the
442 original split so progress is still made and chunks join back to the
443 original text.
444
445 The link "[link](url)" is 11 chars. With limit=7 the first hard split
446 lands at index 7 (inside the URL). The forward-scan cap is
447 7 + (7 - 0) + 1 = 15, which is > 10 (position of ")"), so markdown_adjust
448 finds the closer and moves split to link_start_idx=0. Since 0 == start,
449 smart_split resets to orig_split=7 and emits the next chunk from there.
450 """
451 text = "[link](url)" # 12 chars; ")" at index 11
452 limit = 7 # hard split at 7 (inside url); cap = 15 > 11 so ")" is found
453
454 chunks = smart_split(text, limit, body_format=NotifyFormat.MARKDOWN)
455
456 # We should never get stuck; all chunks must be non-empty.
457 assert len(chunks) >= 2
458 assert all(chunks)
459
460 # Re-joining all chunks must restore the original text.
461 assert "".join(chunks) == text
462
463
464 def test_markdown_adjust_image_bang_opener_path() -> None:
465 """Cover the '!' opener path in markdown_adjust."""
466 # Bang found, but no '[' after it, so the fallback path is taken.
467 text = "AAAAAA![b](c)"
468 assert markdown_adjust(text, window_start=0, split_at=7) == 6
469
470 # Stray '!' not followed by '[' -- bang found but condition is False;
471 # no link construct detected, split point returned unchanged.
472 text2 = "hello!world"
473 assert markdown_adjust(text2, window_start=0, split_at=6) == 6
474
475
476 def test_smart_split_uses_punctuation_branch_on_rare_whitespace() -> None:
477 """
478 When punctuation is followed by rare whitespace (vertical tab / form feed)
479 and there are no spaces/tabs/newlines, we should use the punctuation
480 + whitespace split branch.
481 """
482 vt = "\x0b" # vertical tab
483 text = f"Hello.{vt}World"
484 # Window includes 'Hello.' and the VT
485 limit = len("Hello.") + 1
486
487 chunks = smart_split(text, limit, body_format=NotifyFormat.TEXT)
488
489 assert "".join(chunks) == text
490 # We expect the first chunk to end after the rare whitespace
491 assert chunks[0] == f"Hello.{vt}"
492 assert chunks[1] == "World"