From f60fdccac210371ebfb039741b95f1cb69f4a64b Mon Sep 17 00:00:00 2001 From: emme1t <149944796+emme1t@users.noreply.github.com> Date: Fri, 11 Sep 2026 23:53:59 -0700 Subject: [PATCH] Preserve fitting post-replacement output during modern truncation --- slugify/slugify.py | 3 +++ test_release.py | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/slugify/slugify.py b/slugify/slugify.py index f4e5faf..aedcf8d 100644 --- a/slugify/slugify.py +++ b/slugify/slugify.py @@ -119,6 +119,9 @@ def _modern_truncate(text: str, max_length: int, word_boundary: bool, separator: """ if max_length <= 0: return text.replace(DEFAULT_SEPARATOR, separator) + output_length = len(text) + text.count(DEFAULT_SEPARATOR) * (len(separator) - 1) + if output_length <= max_length: + return text.replace(DEFAULT_SEPARATOR, separator) tokens = text.split(DEFAULT_SEPARATOR) if word_boundary: words: list[str] = [] diff --git a/test_release.py b/test_release.py index 0978362..2f0fbd5 100644 --- a/test_release.py +++ b/test_release.py @@ -40,6 +40,19 @@ def test_modern_separator_does_not_strip_word_content(self): self.assertEqual(slugify('xy xy', separator='xy', max_length=5), 'xyxyx') self.assertEqual(slugify('a b c', separator='::', max_length=3), 'a') + def test_modern_fitting_post_replacements_preserve_delimiters(self): + for replacement in ('one--two', '-one-two-', 'one---two'): + for separator in ('-', '::', ''): + expected = replacement.replace('-', separator) + for boundary, order, limit in itertools.product( + (False, True), (False, True), (len(expected), len(expected) + 10)): + with self.subTest(replacement=replacement, separator=separator, + boundary=boundary, order=order, limit=limit): + self.assertEqual(slugify('x', replacements=[('x', replacement)], + replacement_stage='post', allow_unicode=True, + separator=separator, max_length=limit, + word_boundary=boundary, save_order=order), expected) + def test_cli_preserves_legacy_default_shape(self): expected = dict(text='', entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, save_order=False, separator='-',