test_saferepr.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import, unicode_literals
  3. import re
  4. import struct
  5. from decimal import Decimal
  6. from pprint import pprint
  7. import pytest
  8. from case import skip
  9. from celery.five import (items, long_t, python_2_unicode_compatible, text_t,
  10. values)
  11. from celery.utils.saferepr import saferepr
  12. D_NUMBERS = {
  13. b'integer': 1,
  14. b'float': 1.3,
  15. b'decimal': Decimal('1.3'),
  16. b'long': long_t(4),
  17. b'complex': complex(13.3),
  18. }
  19. D_INT_KEYS = {v: k for k, v in items(D_NUMBERS)}
  20. QUICK_BROWN_FOX = 'The quick brown fox jumps over the lazy dog.'
  21. B_QUICK_BROWN_FOX = b'The quick brown fox jumps over the lazy dog.'
  22. D_TEXT = {
  23. b'foo': QUICK_BROWN_FOX,
  24. b'bar': B_QUICK_BROWN_FOX,
  25. b'baz': B_QUICK_BROWN_FOX,
  26. b'xuzzy': B_QUICK_BROWN_FOX,
  27. }
  28. L_NUMBERS = list(values(D_NUMBERS))
  29. D_TEXT_LARGE = {
  30. b'bazxuzzyfoobarlongverylonglong': QUICK_BROWN_FOX * 30,
  31. }
  32. D_ALL = {
  33. b'numbers': D_NUMBERS,
  34. b'intkeys': D_INT_KEYS,
  35. b'text': D_TEXT,
  36. b'largetext': D_TEXT_LARGE,
  37. }
  38. D_D_TEXT = {b'rest': D_TEXT}
  39. RE_OLD_SET_REPR = re.compile(r'(?<!frozen)set\([\[|\{](.+?)[\}\]]\)')
  40. RE_OLD_SET_REPR_REPLACE = r'{\1}'
  41. RE_OLD_SET_CUSTOM_REPR = re.compile(r'((?:frozen)?set\d?\()\[(.+?)\](\))')
  42. RE_OLD_SET_CUSTOM_REPR_REPLACE = r'\1{\2}\3'
  43. RE_EMPTY_SET_REPR = re.compile(r'((?:frozen)?set\d?)\(\[\]\)')
  44. RE_EMPTY_SET_REPR_REPLACE = r'\1()'
  45. RE_LONG_SUFFIX = re.compile(r'(\d)+L')
  46. def old_repr(s):
  47. return text_t(RE_LONG_SUFFIX.sub(
  48. r'\1',
  49. RE_EMPTY_SET_REPR.sub(
  50. RE_EMPTY_SET_REPR_REPLACE,
  51. RE_OLD_SET_REPR.sub(
  52. RE_OLD_SET_REPR_REPLACE,
  53. RE_OLD_SET_CUSTOM_REPR.sub(
  54. RE_OLD_SET_CUSTOM_REPR_REPLACE,
  55. repr(s).replace("u'", "'"),
  56. )
  57. ),
  58. ),
  59. )).replace('set([])', 'set()')
  60. class list2(list):
  61. pass
  62. @python_2_unicode_compatible
  63. class list3(list):
  64. def __repr__(self):
  65. return list.__repr__(self)
  66. class tuple2(tuple):
  67. pass
  68. @python_2_unicode_compatible
  69. class tuple3(tuple):
  70. def __repr__(self):
  71. return tuple.__repr__(self)
  72. class set2(set):
  73. pass
  74. @python_2_unicode_compatible
  75. class set3(set):
  76. def __repr__(self):
  77. return set.__repr__(self)
  78. class frozenset2(frozenset):
  79. pass
  80. @python_2_unicode_compatible
  81. class frozenset3(frozenset):
  82. def __repr__(self):
  83. return frozenset.__repr__(self)
  84. class dict2(dict):
  85. pass
  86. @python_2_unicode_compatible
  87. class dict3(dict):
  88. def __repr__(self):
  89. return dict.__repr__(self)
  90. class test_saferepr:
  91. @pytest.mark.parametrize('value', list(values(D_NUMBERS)))
  92. def test_safe_types(self, value):
  93. assert saferepr(value) == old_repr(value)
  94. def test_numbers_dict(self):
  95. assert saferepr(D_NUMBERS) == old_repr(D_NUMBERS)
  96. def test_numbers_list(self):
  97. assert saferepr(L_NUMBERS) == old_repr(L_NUMBERS)
  98. def test_numbers_keys(self):
  99. assert saferepr(D_INT_KEYS) == old_repr(D_INT_KEYS)
  100. def test_text(self):
  101. assert saferepr(D_TEXT) == old_repr(D_TEXT).replace("u'", "'")
  102. def test_text_maxlen(self):
  103. assert saferepr(D_D_TEXT, 100).endswith("...', ...}}")
  104. def test_maxlevels(self):
  105. saferepr(D_ALL, maxlevels=1)
  106. def test_recursion(self):
  107. d = {1: 2, 3: {4: 5}}
  108. d[3][6] = d
  109. res = saferepr(d)
  110. assert 'Recursion on' in res
  111. @pytest.mark.parametrize('value', [
  112. 0, 0, 0 + 0j, 0.0, '', b'',
  113. (), tuple2(), tuple3(),
  114. [], list2(), list3(),
  115. set(), set2(), set3(),
  116. frozenset(), frozenset2(), frozenset3(),
  117. {}, dict2(), dict3(),
  118. test_recursion, pprint,
  119. -6, -6, -6 - 6j, -1.5, 'x', b'x', (3,), [3], {3: 6},
  120. (1, 2), [3, 4], {5: 6},
  121. tuple2((1, 2)), tuple3((1, 2)), tuple3(range(100)),
  122. [3, 4], list2([3, 4]), list3([3, 4]), list3(range(100)),
  123. {7}, set2({7}), set3({7}),
  124. frozenset({8}), frozenset2({8}), frozenset3({8}),
  125. dict2({5: 6}), dict3({5: 6}),
  126. range(10, -11, -1)
  127. ])
  128. def test_same_as_repr(self, value):
  129. # Simple objects, small containers, and classes that overwrite __repr__
  130. # For those the result should be the same as repr().
  131. # Ahem. The docs don't say anything about that -- this appears to
  132. # be testing an implementation quirk. Starting in Python 2.5, it's
  133. # not true for dicts: pprint always sorts dicts by key now; before,
  134. # it sorted a dict display if and only if the display required
  135. # multiple lines. For that reason, dicts with more than one element
  136. # aren't tested here.
  137. native = old_repr(value)
  138. assert saferepr(value) == native
  139. @skip.if_python3()
  140. def test_bytes_with_unicode(self):
  141. class X(object):
  142. def __repr__(self):
  143. return 'æ e i a æ å'.encode(
  144. 'utf-8', errors='backslash replace')
  145. val = X()
  146. assert repr(val)
  147. assert saferepr(val)
  148. @skip.unless_python3()
  149. def test_unicode_bytes(self):
  150. val = 'øystein'.encode('utf-8')
  151. assert saferepr(val) == "b'øystein'"
  152. @skip.unless_python3()
  153. def test_unicode_bytes__long(self):
  154. val = 'øystein'.encode('utf-8') * 1024
  155. assert saferepr(val, maxlen=128).endswith("...'")
  156. @skip.unless_python3()
  157. def test_binary_bytes(self):
  158. val = struct.pack('>QQQ', 12223, 1234, 3123)
  159. if hasattr(bytes, 'hex'): # Python 3.5+
  160. assert '2fbf' in saferepr(val, maxlen=128)
  161. else: # Python 3.4
  162. assert saferepr(val, maxlen=128)
  163. @skip.unless_python3()
  164. def test_binary_bytes__long(self):
  165. val = struct.pack('>QQQ', 12223, 1234, 3123) * 1024
  166. result = saferepr(val, maxlen=128)
  167. if hasattr(bytes, 'hex'): # Python 3.5+
  168. assert '2fbf' in result
  169. assert result.endswith("...'")
  170. else: # Python 3.4
  171. assert result
  172. def test_repr_raises(self):
  173. class O(object):
  174. def __repr__(self):
  175. raise KeyError('foo')
  176. assert 'Unrepresentable' in saferepr(O())
  177. def test_bytes_with_unicode_py2_and_3(self):
  178. assert saferepr([b'foo', 'a®rgs'.encode('utf-8')])