test_text.py 12 KB

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