Debian Codegraph @

t/unit/utils/test_saferepr.py

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