2
0

test_text.py 11 KB

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