test_text.py 11 KB

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