test_text.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import json
  2. import sys
  3. from unittest.mock import patch
  4. from django.core.exceptions import SuspiciousFileOperation
  5. from django.test import SimpleTestCase
  6. from django.utils import text
  7. from django.utils.functional import lazystr
  8. from django.utils.text import format_lazy
  9. from django.utils.translation import gettext_lazy, override
  10. IS_WIDE_BUILD = len("\U0001F4A9") == 1
  11. class TestUtilsText(SimpleTestCase):
  12. def test_get_text_list(self):
  13. self.assertEqual(text.get_text_list(["a", "b", "c", "d"]), "a, b, c or d")
  14. self.assertEqual(text.get_text_list(["a", "b", "c"], "and"), "a, b and c")
  15. self.assertEqual(text.get_text_list(["a", "b"], "and"), "a and b")
  16. self.assertEqual(text.get_text_list(["a"]), "a")
  17. self.assertEqual(text.get_text_list([]), "")
  18. with override("ar"):
  19. self.assertEqual(text.get_text_list(["a", "b", "c"]), "a، b أو c")
  20. def test_smart_split(self):
  21. testdata = [
  22. ('This is "a person" test.', ["This", "is", '"a person"', "test."]),
  23. ('This is "a person\'s" test.', ["This", "is", '"a person\'s"', "test."]),
  24. ('This is "a person\\"s" test.', ["This", "is", '"a person\\"s"', "test."]),
  25. ("\"a 'one", ['"a', "'one"]),
  26. ("all friends' tests", ["all", "friends'", "tests"]),
  27. (
  28. 'url search_page words="something else"',
  29. ["url", "search_page", 'words="something else"'],
  30. ),
  31. (
  32. "url search_page words='something else'",
  33. ["url", "search_page", "words='something else'"],
  34. ),
  35. (
  36. 'url search_page words "something else"',
  37. ["url", "search_page", "words", '"something else"'],
  38. ),
  39. (
  40. 'url search_page words-"something else"',
  41. ["url", "search_page", 'words-"something else"'],
  42. ),
  43. ("url search_page words=hello", ["url", "search_page", "words=hello"]),
  44. (
  45. 'url search_page words="something else',
  46. ["url", "search_page", 'words="something', "else"],
  47. ),
  48. ("cut:','|cut:' '", ["cut:','|cut:' '"]),
  49. (lazystr("a b c d"), ["a", "b", "c", "d"]), # Test for #20231
  50. ]
  51. for test, expected in testdata:
  52. with self.subTest(value=test):
  53. self.assertEqual(list(text.smart_split(test)), expected)
  54. def test_truncate_chars(self):
  55. truncator = text.Truncator("The quick brown fox jumped over the lazy dog.")
  56. self.assertEqual(
  57. "The quick brown fox jumped over the lazy dog.", truncator.chars(100)
  58. ),
  59. self.assertEqual("The quick brown fox …", truncator.chars(21))
  60. self.assertEqual("The quick brown fo.....", truncator.chars(23, "....."))
  61. self.assertEqual(".....", truncator.chars(4, "....."))
  62. nfc = text.Truncator("o\xfco\xfco\xfco\xfc")
  63. nfd = text.Truncator("ou\u0308ou\u0308ou\u0308ou\u0308")
  64. self.assertEqual("oüoüoüoü", nfc.chars(8))
  65. self.assertEqual("oüoüoüoü", nfd.chars(8))
  66. self.assertEqual("oü…", nfc.chars(3))
  67. self.assertEqual("oü…", nfd.chars(3))
  68. # Ensure the final length is calculated correctly when there are
  69. # combining characters with no precomposed form, and that combining
  70. # characters are not split up.
  71. truncator = text.Truncator("-B\u030AB\u030A----8")
  72. self.assertEqual("-B\u030A…", truncator.chars(3))
  73. self.assertEqual("-B\u030AB\u030A-…", truncator.chars(5))
  74. self.assertEqual("-B\u030AB\u030A----8", truncator.chars(8))
  75. # Ensure the length of the end text is correctly calculated when it
  76. # contains combining characters with no precomposed form.
  77. truncator = text.Truncator("-----")
  78. self.assertEqual("---B\u030A", truncator.chars(4, "B\u030A"))
  79. self.assertEqual("-----", truncator.chars(5, "B\u030A"))
  80. # Make a best effort to shorten to the desired length, but requesting
  81. # a length shorter than the ellipsis shouldn't break
  82. self.assertEqual("…", text.Truncator("asdf").chars(0))
  83. # lazy strings are handled correctly
  84. self.assertEqual(
  85. text.Truncator(lazystr("The quick brown fox")).chars(10), "The quick…"
  86. )
  87. @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000)
  88. def test_truncate_chars_html_size_limit(self):
  89. max_len = text.Truncator.MAX_LENGTH_HTML
  90. bigger_len = text.Truncator.MAX_LENGTH_HTML + 1
  91. valid_html = "<p>Joel is a slug</p>" # 14 chars
  92. perf_test_values = [
  93. ("</a" + "\t" * (max_len - 6) + "//>", None),
  94. ("</p" + "\t" * bigger_len + "//>", "</p" + "\t" * 6 + "…"),
  95. ("&" * bigger_len, "&" * 9 + "…"),
  96. ("_X<<<<<<<<<<<>", None),
  97. (valid_html * bigger_len, "<p>Joel is a…</p>"), # 10 chars
  98. ]
  99. for value, expected in perf_test_values:
  100. with self.subTest(value=value):
  101. truncator = text.Truncator(value)
  102. self.assertEqual(
  103. expected if expected else value, truncator.chars(10, html=True)
  104. )
  105. def test_truncate_words(self):
  106. truncator = text.Truncator("The quick brown fox jumped over the lazy dog.")
  107. self.assertEqual(
  108. "The quick brown fox jumped over the lazy dog.", truncator.words(10)
  109. )
  110. self.assertEqual("The quick brown fox…", truncator.words(4))
  111. self.assertEqual("The quick brown fox[snip]", truncator.words(4, "[snip]"))
  112. # lazy strings are handled correctly
  113. truncator = text.Truncator(
  114. lazystr("The quick brown fox jumped over the lazy dog.")
  115. )
  116. self.assertEqual("The quick brown fox…", truncator.words(4))
  117. def test_truncate_html_words(self):
  118. truncator = text.Truncator(
  119. '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>'
  120. "</strong></p>"
  121. )
  122. self.assertEqual(
  123. '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>'
  124. "</strong></p>",
  125. truncator.words(10, html=True),
  126. )
  127. self.assertEqual(
  128. '<p id="par"><strong><em>The quick brown fox…</em></strong></p>',
  129. truncator.words(4, html=True),
  130. )
  131. self.assertEqual(
  132. '<p id="par"><strong><em>The quick brown fox....</em></strong></p>',
  133. truncator.words(4, "....", html=True),
  134. )
  135. self.assertEqual(
  136. '<p id="par"><strong><em>The quick brown fox</em></strong></p>',
  137. truncator.words(4, "", html=True),
  138. )
  139. # Test with new line inside tag
  140. truncator = text.Truncator(
  141. '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over '
  142. "the lazy dog.</p>"
  143. )
  144. self.assertEqual(
  145. '<p>The quick <a href="xyz.html"\n id="mylink">brown…</a></p>',
  146. truncator.words(3, html=True),
  147. )
  148. # Test self-closing tags
  149. truncator = text.Truncator(
  150. "<br/>The <hr />quick brown fox jumped over the lazy dog."
  151. )
  152. self.assertEqual("<br/>The <hr />quick brown…", truncator.words(3, html=True))
  153. truncator = text.Truncator(
  154. "<br>The <hr/>quick <em>brown fox</em> jumped over the lazy dog."
  155. )
  156. self.assertEqual(
  157. "<br>The <hr/>quick <em>brown…</em>", truncator.words(3, html=True)
  158. )
  159. # Test html entities
  160. truncator = text.Truncator(
  161. "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>"
  162. )
  163. self.assertEqual(
  164. "<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo…</i>",
  165. truncator.words(3, html=True),
  166. )
  167. truncator = text.Truncator("<p>I &lt;3 python, what about you?</p>")
  168. self.assertEqual("<p>I &lt;3 python,…</p>", truncator.words(3, html=True))
  169. @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000)
  170. def test_truncate_words_html_size_limit(self):
  171. max_len = text.Truncator.MAX_LENGTH_HTML
  172. bigger_len = text.Truncator.MAX_LENGTH_HTML + 1
  173. valid_html = "<p>Joel is a slug</p>" # 4 words
  174. perf_test_values = [
  175. ("</a" + "\t" * (max_len - 6) + "//>", None),
  176. ("</p" + "\t" * bigger_len + "//>", "</p" + "\t" * (max_len - 3) + "…"),
  177. ("&" * max_len, None), # no change
  178. ("&" * bigger_len, "&" * max_len + "…"),
  179. ("_X<<<<<<<<<<<>", None),
  180. (valid_html * bigger_len, valid_html * 12 + "<p>Joel is…</p>"), # 50 words
  181. ]
  182. for value, expected in perf_test_values:
  183. with self.subTest(value=value):
  184. truncator = text.Truncator(value)
  185. self.assertEqual(
  186. expected if expected else value, truncator.words(50, html=True)
  187. )
  188. def test_wrap(self):
  189. digits = "1234 67 9"
  190. self.assertEqual(text.wrap(digits, 100), "1234 67 9")
  191. self.assertEqual(text.wrap(digits, 9), "1234 67 9")
  192. self.assertEqual(text.wrap(digits, 8), "1234 67\n9")
  193. self.assertEqual(text.wrap("short\na long line", 7), "short\na long\nline")
  194. self.assertEqual(
  195. text.wrap("do-not-break-long-words please? ok", 8),
  196. "do-not-break-long-words\nplease?\nok",
  197. )
  198. long_word = "l%sng" % ("o" * 20)
  199. self.assertEqual(text.wrap(long_word, 20), long_word)
  200. self.assertEqual(
  201. text.wrap("a %s word" % long_word, 10), "a\n%s\nword" % long_word
  202. )
  203. self.assertEqual(text.wrap(lazystr(digits), 100), "1234 67 9")
  204. def test_normalize_newlines(self):
  205. self.assertEqual(
  206. text.normalize_newlines("abc\ndef\rghi\r\n"), "abc\ndef\nghi\n"
  207. )
  208. self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n")
  209. self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi")
  210. self.assertEqual(text.normalize_newlines(""), "")
  211. self.assertEqual(
  212. text.normalize_newlines(lazystr("abc\ndef\rghi\r\n")), "abc\ndef\nghi\n"
  213. )
  214. def test_phone2numeric(self):
  215. numeric = text.phone2numeric("0800 flowers")
  216. self.assertEqual(numeric, "0800 3569377")
  217. lazy_numeric = lazystr(text.phone2numeric("0800 flowers"))
  218. self.assertEqual(lazy_numeric, "0800 3569377")
  219. def test_slugify(self):
  220. items = (
  221. # given - expected - Unicode?
  222. ("Hello, World!", "hello-world", False),
  223. ("spam & eggs", "spam-eggs", False),
  224. (" multiple---dash and space ", "multiple-dash-and-space", False),
  225. ("\t whitespace-in-value \n", "whitespace-in-value", False),
  226. ("underscore_in-value", "underscore_in-value", False),
  227. ("__strip__underscore-value___", "strip__underscore-value", False),
  228. ("--strip-dash-value---", "strip-dash-value", False),
  229. ("__strip-mixed-value---", "strip-mixed-value", False),
  230. ("_ -strip-mixed-value _-", "strip-mixed-value", False),
  231. ("spam & ıçüş", "spam-ıçüş", True),
  232. ("foo ıç bar", "foo-ıç-bar", True),
  233. (" foo ıç bar", "foo-ıç-bar", True),
  234. ("你好", "你好", True),
  235. ("İstanbul", "istanbul", True),
  236. )
  237. for value, output, is_unicode in items:
  238. with self.subTest(value=value):
  239. self.assertEqual(text.slugify(value, allow_unicode=is_unicode), output)
  240. # Interning the result may be useful, e.g. when fed to Path.
  241. with self.subTest("intern"):
  242. self.assertEqual(sys.intern(text.slugify("a")), "a")
  243. def test_unescape_string_literal(self):
  244. items = [
  245. ('"abc"', "abc"),
  246. ("'abc'", "abc"),
  247. ('"a "bc""', 'a "bc"'),
  248. ("''ab' c'", "'ab' c"),
  249. ]
  250. for value, output in items:
  251. with self.subTest(value=value):
  252. self.assertEqual(text.unescape_string_literal(value), output)
  253. self.assertEqual(text.unescape_string_literal(lazystr(value)), output)
  254. def test_unescape_string_literal_invalid_value(self):
  255. items = ["", "abc", "'abc\""]
  256. for item in items:
  257. msg = f"Not a string literal: {item!r}"
  258. with self.assertRaisesMessage(ValueError, msg):
  259. text.unescape_string_literal(item)
  260. def test_get_valid_filename(self):
  261. filename = "^&'@{}[],$=!-#()%+~_123.txt"
  262. self.assertEqual(text.get_valid_filename(filename), "-_123.txt")
  263. self.assertEqual(text.get_valid_filename(lazystr(filename)), "-_123.txt")
  264. msg = "Could not derive file name from '???'"
  265. with self.assertRaisesMessage(SuspiciousFileOperation, msg):
  266. text.get_valid_filename("???")
  267. # After sanitizing this would yield '..'.
  268. msg = "Could not derive file name from '$.$.$'"
  269. with self.assertRaisesMessage(SuspiciousFileOperation, msg):
  270. text.get_valid_filename("$.$.$")
  271. def test_compress_sequence(self):
  272. data = [{"key": i} for i in range(10)]
  273. seq = list(json.JSONEncoder().iterencode(data))
  274. seq = [s.encode() for s in seq]
  275. actual_length = len(b"".join(seq))
  276. out = text.compress_sequence(seq)
  277. compressed_length = len(b"".join(out))
  278. self.assertLess(compressed_length, actual_length)
  279. def test_format_lazy(self):
  280. self.assertEqual("django/test", format_lazy("{}/{}", "django", lazystr("test")))
  281. self.assertEqual("django/test", format_lazy("{0}/{1}", *("django", "test")))
  282. self.assertEqual(
  283. "django/test", format_lazy("{a}/{b}", **{"a": "django", "b": "test"})
  284. )
  285. self.assertEqual(
  286. "django/test", format_lazy("{a[0]}/{a[1]}", a=("django", "test"))
  287. )
  288. t = {}
  289. s = format_lazy("{0[a]}-{p[a]}", t, p=t)
  290. t["a"] = lazystr("django")
  291. self.assertEqual("django-django", s)
  292. t["a"] = "update"
  293. self.assertEqual("update-update", s)
  294. # The format string can be lazy. (string comes from contrib.admin)
  295. s = format_lazy(
  296. gettext_lazy("Added {name} “{object}”."),
  297. name="article",
  298. object="My first try",
  299. )
  300. with override("fr"):
  301. self.assertEqual("Ajout de article «\xa0My first try\xa0».", s)