1
0

test_text_utils.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """Tests du découpage des messages et du retrait de la réflexion. Lancer depuis la racine du projet : python -m unittest"""
  2. import unittest
  3. from bot.text_utils import DISCORD_LIMIT, split_message, strip_reasoning
  4. # Presque un message entier : la ligne suivante, même courte, passe au morceau d'après.
  5. FULL = "a" * 1990 + "\n" + "b" * 5
  6. def code_block(language: str, count: int) -> str:
  7. """Un bloc de code de `count` lignes numérotées, fermé."""
  8. lines = "\n".join(f"print('ligne {i} du bloc')" for i in range(count))
  9. return f"```{language}\n{lines}\n```"
  10. class SplitMessageTest(unittest.TestCase):
  11. def assert_valid(self, chunks: list[str], limit: int = DISCORD_LIMIT) -> None:
  12. """Aucun morceau vide, aucun morceau au-delà de la limite, et chaque bloc de code refermé."""
  13. for chunk in chunks:
  14. self.assertTrue(chunk.strip(), chunks)
  15. self.assertLessEqual(len(chunk), limit, chunk)
  16. fences = [line for line in chunk.split("\n") if line.lstrip().startswith("```")]
  17. self.assertEqual(len(fences) % 2, 0, chunk)
  18. def test_short_text_unchanged(self):
  19. self.assertEqual(split_message("Bonjour !"), ["Bonjour !"])
  20. self.assertEqual(split_message("a" * DISCORD_LIMIT), ["a" * DISCORD_LIMIT])
  21. def test_surrounding_spaces_removed(self):
  22. self.assertEqual(split_message(" \n Bonjour !\n\n"), ["Bonjour !"])
  23. def test_empty_text(self):
  24. self.assertEqual(split_message(""), [])
  25. self.assertEqual(split_message(" \n\n "), [])
  26. def test_cut_between_lines(self):
  27. lines = [f"Ligne numéro {i}, avec un peu de texte pour la remplir." for i in range(100)]
  28. chunks = split_message("\n".join(lines))
  29. self.assertGreater(len(chunks), 1)
  30. self.assert_valid(chunks)
  31. # Aucune ligne n'est coupée en deux : on retrouve exactement les lignes de départ.
  32. self.assertEqual([line for chunk in chunks for line in chunk.split("\n")], lines)
  33. def test_code_block_closed_and_reopened(self):
  34. text = "Voici le code :\n" + code_block("python", 150) + "\nEt voilà."
  35. chunks = split_message(text)
  36. self.assertGreater(len(chunks), 1)
  37. self.assert_valid(chunks)
  38. self.assertTrue(chunks[0].endswith("\n```"))
  39. for chunk in chunks[1:]:
  40. self.assertTrue(chunk.startswith("```python\n"), chunk[:30])
  41. # Une fois les ``` ajoutés retirés, le code est entier et dans l'ordre.
  42. code = [line for chunk in chunks for line in chunk.split("\n") if line.startswith("print(")]
  43. self.assertEqual(code, [f"print('ligne {i} du bloc')" for i in range(150)])
  44. def test_code_block_without_language(self):
  45. chunks = split_message(code_block("", 150))
  46. self.assert_valid(chunks)
  47. for chunk in chunks:
  48. self.assertTrue(chunk.startswith("```\nprint("), chunk[:30])
  49. def test_closed_block_not_closed_again(self):
  50. # Le bloc se ferme dans le dernier morceau : rien n'est ajouté après lui.
  51. text = FULL + "\n" + code_block("js", 3) + "\nFin du message."
  52. self.assertEqual(split_message(text), [FULL, code_block("js", 3) + "\nFin du message."])
  53. def test_text_ending_with_closed_block(self):
  54. text = FULL + "\n" + code_block("js", 3)
  55. self.assertEqual(split_message(text), [FULL, code_block("js", 3)])
  56. def test_unclosed_block_left_as_is(self):
  57. # Un bloc que le modèle n'a pas fermé ne l'est pas artificiellement dans le dernier morceau.
  58. text = FULL + "\n```python\nprint('oups')"
  59. self.assertEqual(split_message(text), [FULL, "```python\nprint('oups')"])
  60. def test_no_chunk_with_reopened_fence_only(self):
  61. # Le bloc se ferme juste au début d'un nouveau morceau : pas de morceau « ```python » seul.
  62. text = code_block("python", 150)
  63. chunks = split_message(text)
  64. self.assert_valid(chunks)
  65. self.assertNotIn("```python", chunks)
  66. def test_long_line_cut_at_space(self):
  67. words = [f"mot{i}" for i in range(1000)]
  68. chunks = split_message(" ".join(words))
  69. self.assertGreater(len(chunks), 1)
  70. self.assert_valid(chunks)
  71. # Aucun mot n'est coupé en deux.
  72. self.assertEqual([word for chunk in chunks for word in chunk.split()], words)
  73. def test_long_line_without_space_cut_clean(self):
  74. text = "x" * 5000
  75. chunks = split_message(text)
  76. self.assert_valid(chunks)
  77. self.assertEqual("".join(chunks), text)
  78. def test_space_too_early_ignored(self):
  79. # Le seul espace est tout au début : couper là ferait un morceau minuscule, la coupe est nette.
  80. text = "ab " + "x" * 3000
  81. chunks = split_message(text)
  82. self.assert_valid(chunks)
  83. self.assertGreater(len(chunks[0]), DISCORD_LIMIT // 2)
  84. self.assertEqual("".join(chunks).replace(" ", ""), text.replace(" ", ""))
  85. def test_long_line_inside_code_block(self):
  86. text = "```python\n" + "y" * 4500 + "\n```"
  87. chunks = split_message(text)
  88. self.assert_valid(chunks)
  89. for chunk in chunks:
  90. self.assertTrue(chunk.startswith("```python\n"), chunk[:30])
  91. self.assertTrue(chunk.endswith("\n```"), chunk[-30:])
  92. self.assertEqual("".join(c.removeprefix("```python\n").removesuffix("\n```") for c in chunks), "y" * 4500)
  93. def test_small_limit(self):
  94. text = ("Un peu de texte avant le code.\n" + code_block("python", 12) + "\n"
  95. + "un mot " * 30 + "\n" + "z" * 120 + "\nFin.")
  96. for limit in (40, 60, 100):
  97. with self.subTest(limit=limit):
  98. chunks = split_message(text, limit)
  99. self.assertGreater(len(chunks), 1)
  100. self.assert_valid(chunks, limit)
  101. @unittest.expectedFailure
  102. def test_opening_fence_at_end_of_chunk(self):
  103. # BUG : quand la ligne d'ouverture d'un bloc (```py) remplit le morceau à 1, 2 ou 3 caractères
  104. # près, le morceau se termine par un bloc vide « ```py\n``` » qui dépasse la limite de 3 caractères
  105. # au plus : Discord refuserait ce message. La ligne d'ouverture devrait passer au morceau suivant.
  106. for before in range(1990, 2000):
  107. with self.subTest(before=before):
  108. text = "a" * before + "\n```py\n" + "b" * 10 + "\nfin\n```"
  109. chunks = split_message(text)
  110. self.assert_valid(chunks)
  111. self.assertFalse(chunks[0].endswith("```py\n```"), chunks[0][-20:])
  112. class StripReasoningTest(unittest.TestCase):
  113. def test_think_block_at_start_removed(self):
  114. self.assertEqual(strip_reasoning("<think>Il faut être poli.</think>\n\nBonjour !"), "Bonjour !")
  115. def test_other_tags_removed(self):
  116. for tag in ("think", "thinking", "reasoning", "function_calls", "invoke"):
  117. with self.subTest(tag=tag):
  118. self.assertEqual(strip_reasoning(f"<{tag}>réflexion</{tag}>Réponse"), "Réponse")
  119. def test_tag_with_attributes_and_case(self):
  120. text = '<INVOKE name="web_search">\n<parameter>météo</parameter>\n</invoke> Il fait beau.'
  121. self.assertEqual(strip_reasoning(text), "Il fait beau.")
  122. def test_multiline_block_and_leading_spaces(self):
  123. self.assertEqual(strip_reasoning("\n <thinking>\nune\ndeux\n</thinking>\nSalut"), "Salut")
  124. def test_several_blocks_at_start(self):
  125. text = "<think>un</think>\n<function_calls>appel</function_calls>\nRéponse"
  126. self.assertEqual(strip_reasoning(text), "Réponse")
  127. def test_tag_later_in_text_kept(self):
  128. text = "Les modèles écrivent parfois <think>ceci</think> avant de répondre."
  129. self.assertEqual(strip_reasoning(text), text)
  130. def test_tag_in_code_kept(self):
  131. text = "Exemple :\n```xml\n<thinking>texte</thinking>\n```"
  132. self.assertEqual(strip_reasoning(text), text)
  133. def test_unclosed_block_kept(self):
  134. # Sans balise de fin, rien n'est retiré : on ne sait pas où la réflexion s'arrête.
  135. self.assertEqual(strip_reasoning("<think>réflexion sans fin"), "<think>réflexion sans fin")
  136. def test_mismatched_tags_kept(self):
  137. self.assertEqual(strip_reasoning("<think>a</thinking> b"), "<think>a</thinking> b")
  138. def test_only_reasoning(self):
  139. self.assertEqual(strip_reasoning("<think>rien d'autre</think> "), "")
  140. def test_plain_text_stripped(self):
  141. self.assertEqual(strip_reasoning(" Bonjour !\n"), "Bonjour !")
  142. if __name__ == "__main__":
  143. unittest.main()