##// END OF EJS Templates
Merge pull request #13714 from frenzymadness/fix_xxlimited...
Matthias Bussonnier -
r27711:b9c796a6 merge
parent child Browse files
Show More
@@ -1,536 +1,539 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Tests for IPython.lib.pretty."""
2 """Tests for IPython.lib.pretty."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 from collections import Counter, defaultdict, deque, OrderedDict, UserList
8 from collections import Counter, defaultdict, deque, OrderedDict, UserList
9 import os
9 import os
10 import pytest
10 import pytest
11 import types
11 import types
12 import string
12 import string
13 import sys
13 import sys
14 import unittest
14 import unittest
15
15
16 import pytest
16 import pytest
17
17
18 from IPython.lib import pretty
18 from IPython.lib import pretty
19
19
20 from io import StringIO
20 from io import StringIO
21
21
22
22
23 class MyList(object):
23 class MyList(object):
24 def __init__(self, content):
24 def __init__(self, content):
25 self.content = content
25 self.content = content
26 def _repr_pretty_(self, p, cycle):
26 def _repr_pretty_(self, p, cycle):
27 if cycle:
27 if cycle:
28 p.text("MyList(...)")
28 p.text("MyList(...)")
29 else:
29 else:
30 with p.group(3, "MyList(", ")"):
30 with p.group(3, "MyList(", ")"):
31 for (i, child) in enumerate(self.content):
31 for (i, child) in enumerate(self.content):
32 if i:
32 if i:
33 p.text(",")
33 p.text(",")
34 p.breakable()
34 p.breakable()
35 else:
35 else:
36 p.breakable("")
36 p.breakable("")
37 p.pretty(child)
37 p.pretty(child)
38
38
39
39
40 class MyDict(dict):
40 class MyDict(dict):
41 def _repr_pretty_(self, p, cycle):
41 def _repr_pretty_(self, p, cycle):
42 p.text("MyDict(...)")
42 p.text("MyDict(...)")
43
43
44 class MyObj(object):
44 class MyObj(object):
45 def somemethod(self):
45 def somemethod(self):
46 pass
46 pass
47
47
48
48
49 class Dummy1(object):
49 class Dummy1(object):
50 def _repr_pretty_(self, p, cycle):
50 def _repr_pretty_(self, p, cycle):
51 p.text("Dummy1(...)")
51 p.text("Dummy1(...)")
52
52
53 class Dummy2(Dummy1):
53 class Dummy2(Dummy1):
54 _repr_pretty_ = None
54 _repr_pretty_ = None
55
55
56 class NoModule(object):
56 class NoModule(object):
57 pass
57 pass
58
58
59 NoModule.__module__ = None
59 NoModule.__module__ = None
60
60
61 class Breaking(object):
61 class Breaking(object):
62 def _repr_pretty_(self, p, cycle):
62 def _repr_pretty_(self, p, cycle):
63 with p.group(4,"TG: ",":"):
63 with p.group(4,"TG: ",":"):
64 p.text("Breaking(")
64 p.text("Breaking(")
65 p.break_()
65 p.break_()
66 p.text(")")
66 p.text(")")
67
67
68 class BreakingRepr(object):
68 class BreakingRepr(object):
69 def __repr__(self):
69 def __repr__(self):
70 return "Breaking(\n)"
70 return "Breaking(\n)"
71
71
72 class BadRepr(object):
72 class BadRepr(object):
73 def __repr__(self):
73 def __repr__(self):
74 return 1/0
74 return 1/0
75
75
76
76
77 def test_indentation():
77 def test_indentation():
78 """Test correct indentation in groups"""
78 """Test correct indentation in groups"""
79 count = 40
79 count = 40
80 gotoutput = pretty.pretty(MyList(range(count)))
80 gotoutput = pretty.pretty(MyList(range(count)))
81 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
81 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
82
82
83 assert gotoutput == expectedoutput
83 assert gotoutput == expectedoutput
84
84
85
85
86 def test_dispatch():
86 def test_dispatch():
87 """
87 """
88 Test correct dispatching: The _repr_pretty_ method for MyDict
88 Test correct dispatching: The _repr_pretty_ method for MyDict
89 must be found before the registered printer for dict.
89 must be found before the registered printer for dict.
90 """
90 """
91 gotoutput = pretty.pretty(MyDict())
91 gotoutput = pretty.pretty(MyDict())
92 expectedoutput = "MyDict(...)"
92 expectedoutput = "MyDict(...)"
93
93
94 assert gotoutput == expectedoutput
94 assert gotoutput == expectedoutput
95
95
96
96
97 def test_callability_checking():
97 def test_callability_checking():
98 """
98 """
99 Test that the _repr_pretty_ method is tested for callability and skipped if
99 Test that the _repr_pretty_ method is tested for callability and skipped if
100 not.
100 not.
101 """
101 """
102 gotoutput = pretty.pretty(Dummy2())
102 gotoutput = pretty.pretty(Dummy2())
103 expectedoutput = "Dummy1(...)"
103 expectedoutput = "Dummy1(...)"
104
104
105 assert gotoutput == expectedoutput
105 assert gotoutput == expectedoutput
106
106
107
107
108 @pytest.mark.parametrize(
108 @pytest.mark.parametrize(
109 "obj,expected_output",
109 "obj,expected_output",
110 zip(
110 zip(
111 [
111 [
112 set(),
112 set(),
113 frozenset(),
113 frozenset(),
114 set([1]),
114 set([1]),
115 frozenset([1]),
115 frozenset([1]),
116 set([1, 2]),
116 set([1, 2]),
117 frozenset([1, 2]),
117 frozenset([1, 2]),
118 set([-1, -2, -3]),
118 set([-1, -2, -3]),
119 ],
119 ],
120 [
120 [
121 "set()",
121 "set()",
122 "frozenset()",
122 "frozenset()",
123 "{1}",
123 "{1}",
124 "frozenset({1})",
124 "frozenset({1})",
125 "{1, 2}",
125 "{1, 2}",
126 "frozenset({1, 2})",
126 "frozenset({1, 2})",
127 "{-3, -2, -1}",
127 "{-3, -2, -1}",
128 ],
128 ],
129 ),
129 ),
130 )
130 )
131 def test_sets(obj, expected_output):
131 def test_sets(obj, expected_output):
132 """
132 """
133 Test that set and frozenset use Python 3 formatting.
133 Test that set and frozenset use Python 3 formatting.
134 """
134 """
135 got_output = pretty.pretty(obj)
135 got_output = pretty.pretty(obj)
136 assert got_output == expected_output
136 assert got_output == expected_output
137
137
138
138
139 def test_pprint_heap_allocated_type():
139 def test_pprint_heap_allocated_type():
140 """
140 """
141 Test that pprint works for heap allocated types.
141 Test that pprint works for heap allocated types.
142 """
142 """
143 module_name = "xxlimited" if sys.version_info < (3, 10) else "xxlimited_35"
143 module_name = "xxlimited" if sys.version_info < (3, 10) else "xxlimited_35"
144 expected_output = (
145 "xxlimited.Null" if sys.version_info < (3, 10, 6) else "xxlimited_35.Null"
146 )
144 xxlimited = pytest.importorskip(module_name)
147 xxlimited = pytest.importorskip(module_name)
145 output = pretty.pretty(xxlimited.Null)
148 output = pretty.pretty(xxlimited.Null)
146 assert output == "xxlimited.Null"
149 assert output == expected_output
147
150
148
151
149 def test_pprint_nomod():
152 def test_pprint_nomod():
150 """
153 """
151 Test that pprint works for classes with no __module__.
154 Test that pprint works for classes with no __module__.
152 """
155 """
153 output = pretty.pretty(NoModule)
156 output = pretty.pretty(NoModule)
154 assert output == "NoModule"
157 assert output == "NoModule"
155
158
156
159
157 def test_pprint_break():
160 def test_pprint_break():
158 """
161 """
159 Test that p.break_ produces expected output
162 Test that p.break_ produces expected output
160 """
163 """
161 output = pretty.pretty(Breaking())
164 output = pretty.pretty(Breaking())
162 expected = "TG: Breaking(\n ):"
165 expected = "TG: Breaking(\n ):"
163 assert output == expected
166 assert output == expected
164
167
165 def test_pprint_break_repr():
168 def test_pprint_break_repr():
166 """
169 """
167 Test that p.break_ is used in repr
170 Test that p.break_ is used in repr
168 """
171 """
169 output = pretty.pretty([[BreakingRepr()]])
172 output = pretty.pretty([[BreakingRepr()]])
170 expected = "[[Breaking(\n )]]"
173 expected = "[[Breaking(\n )]]"
171 assert output == expected
174 assert output == expected
172
175
173 output = pretty.pretty([[BreakingRepr()]*2])
176 output = pretty.pretty([[BreakingRepr()]*2])
174 expected = "[[Breaking(\n ),\n Breaking(\n )]]"
177 expected = "[[Breaking(\n ),\n Breaking(\n )]]"
175 assert output == expected
178 assert output == expected
176
179
177 def test_bad_repr():
180 def test_bad_repr():
178 """Don't catch bad repr errors"""
181 """Don't catch bad repr errors"""
179 with pytest.raises(ZeroDivisionError):
182 with pytest.raises(ZeroDivisionError):
180 pretty.pretty(BadRepr())
183 pretty.pretty(BadRepr())
181
184
182 class BadException(Exception):
185 class BadException(Exception):
183 def __str__(self):
186 def __str__(self):
184 return -1
187 return -1
185
188
186 class ReallyBadRepr(object):
189 class ReallyBadRepr(object):
187 __module__ = 1
190 __module__ = 1
188 @property
191 @property
189 def __class__(self):
192 def __class__(self):
190 raise ValueError("I am horrible")
193 raise ValueError("I am horrible")
191
194
192 def __repr__(self):
195 def __repr__(self):
193 raise BadException()
196 raise BadException()
194
197
195 def test_really_bad_repr():
198 def test_really_bad_repr():
196 with pytest.raises(BadException):
199 with pytest.raises(BadException):
197 pretty.pretty(ReallyBadRepr())
200 pretty.pretty(ReallyBadRepr())
198
201
199
202
200 class SA(object):
203 class SA(object):
201 pass
204 pass
202
205
203 class SB(SA):
206 class SB(SA):
204 pass
207 pass
205
208
206 class TestsPretty(unittest.TestCase):
209 class TestsPretty(unittest.TestCase):
207
210
208 def test_super_repr(self):
211 def test_super_repr(self):
209 # "<super: module_name.SA, None>"
212 # "<super: module_name.SA, None>"
210 output = pretty.pretty(super(SA))
213 output = pretty.pretty(super(SA))
211 self.assertRegex(output, r"<super: \S+.SA, None>")
214 self.assertRegex(output, r"<super: \S+.SA, None>")
212
215
213 # "<super: module_name.SA, <module_name.SB at 0x...>>"
216 # "<super: module_name.SA, <module_name.SB at 0x...>>"
214 sb = SB()
217 sb = SB()
215 output = pretty.pretty(super(SA, sb))
218 output = pretty.pretty(super(SA, sb))
216 self.assertRegex(output, r"<super: \S+.SA,\s+<\S+.SB at 0x\S+>>")
219 self.assertRegex(output, r"<super: \S+.SA,\s+<\S+.SB at 0x\S+>>")
217
220
218
221
219 def test_long_list(self):
222 def test_long_list(self):
220 lis = list(range(10000))
223 lis = list(range(10000))
221 p = pretty.pretty(lis)
224 p = pretty.pretty(lis)
222 last2 = p.rsplit('\n', 2)[-2:]
225 last2 = p.rsplit('\n', 2)[-2:]
223 self.assertEqual(last2, [' 999,', ' ...]'])
226 self.assertEqual(last2, [' 999,', ' ...]'])
224
227
225 def test_long_set(self):
228 def test_long_set(self):
226 s = set(range(10000))
229 s = set(range(10000))
227 p = pretty.pretty(s)
230 p = pretty.pretty(s)
228 last2 = p.rsplit('\n', 2)[-2:]
231 last2 = p.rsplit('\n', 2)[-2:]
229 self.assertEqual(last2, [' 999,', ' ...}'])
232 self.assertEqual(last2, [' 999,', ' ...}'])
230
233
231 def test_long_tuple(self):
234 def test_long_tuple(self):
232 tup = tuple(range(10000))
235 tup = tuple(range(10000))
233 p = pretty.pretty(tup)
236 p = pretty.pretty(tup)
234 last2 = p.rsplit('\n', 2)[-2:]
237 last2 = p.rsplit('\n', 2)[-2:]
235 self.assertEqual(last2, [' 999,', ' ...)'])
238 self.assertEqual(last2, [' 999,', ' ...)'])
236
239
237 def test_long_dict(self):
240 def test_long_dict(self):
238 d = { n:n for n in range(10000) }
241 d = { n:n for n in range(10000) }
239 p = pretty.pretty(d)
242 p = pretty.pretty(d)
240 last2 = p.rsplit('\n', 2)[-2:]
243 last2 = p.rsplit('\n', 2)[-2:]
241 self.assertEqual(last2, [' 999: 999,', ' ...}'])
244 self.assertEqual(last2, [' 999: 999,', ' ...}'])
242
245
243 def test_unbound_method(self):
246 def test_unbound_method(self):
244 output = pretty.pretty(MyObj.somemethod)
247 output = pretty.pretty(MyObj.somemethod)
245 self.assertIn('MyObj.somemethod', output)
248 self.assertIn('MyObj.somemethod', output)
246
249
247
250
248 class MetaClass(type):
251 class MetaClass(type):
249 def __new__(cls, name):
252 def __new__(cls, name):
250 return type.__new__(cls, name, (object,), {'name': name})
253 return type.__new__(cls, name, (object,), {'name': name})
251
254
252 def __repr__(self):
255 def __repr__(self):
253 return "[CUSTOM REPR FOR CLASS %s]" % self.name
256 return "[CUSTOM REPR FOR CLASS %s]" % self.name
254
257
255
258
256 ClassWithMeta = MetaClass('ClassWithMeta')
259 ClassWithMeta = MetaClass('ClassWithMeta')
257
260
258
261
259 def test_metaclass_repr():
262 def test_metaclass_repr():
260 output = pretty.pretty(ClassWithMeta)
263 output = pretty.pretty(ClassWithMeta)
261 assert output == "[CUSTOM REPR FOR CLASS ClassWithMeta]"
264 assert output == "[CUSTOM REPR FOR CLASS ClassWithMeta]"
262
265
263
266
264 def test_unicode_repr():
267 def test_unicode_repr():
265 u = u"üniçodé"
268 u = u"üniçodé"
266 ustr = u
269 ustr = u
267
270
268 class C(object):
271 class C(object):
269 def __repr__(self):
272 def __repr__(self):
270 return ustr
273 return ustr
271
274
272 c = C()
275 c = C()
273 p = pretty.pretty(c)
276 p = pretty.pretty(c)
274 assert p == u
277 assert p == u
275 p = pretty.pretty([c])
278 p = pretty.pretty([c])
276 assert p == "[%s]" % u
279 assert p == "[%s]" % u
277
280
278
281
279 def test_basic_class():
282 def test_basic_class():
280 def type_pprint_wrapper(obj, p, cycle):
283 def type_pprint_wrapper(obj, p, cycle):
281 if obj is MyObj:
284 if obj is MyObj:
282 type_pprint_wrapper.called = True
285 type_pprint_wrapper.called = True
283 return pretty._type_pprint(obj, p, cycle)
286 return pretty._type_pprint(obj, p, cycle)
284 type_pprint_wrapper.called = False
287 type_pprint_wrapper.called = False
285
288
286 stream = StringIO()
289 stream = StringIO()
287 printer = pretty.RepresentationPrinter(stream)
290 printer = pretty.RepresentationPrinter(stream)
288 printer.type_pprinters[type] = type_pprint_wrapper
291 printer.type_pprinters[type] = type_pprint_wrapper
289 printer.pretty(MyObj)
292 printer.pretty(MyObj)
290 printer.flush()
293 printer.flush()
291 output = stream.getvalue()
294 output = stream.getvalue()
292
295
293 assert output == "%s.MyObj" % __name__
296 assert output == "%s.MyObj" % __name__
294 assert type_pprint_wrapper.called is True
297 assert type_pprint_wrapper.called is True
295
298
296
299
297 def test_collections_userlist():
300 def test_collections_userlist():
298 # Create userlist with cycle
301 # Create userlist with cycle
299 a = UserList()
302 a = UserList()
300 a.append(a)
303 a.append(a)
301
304
302 cases = [
305 cases = [
303 (UserList(), "UserList([])"),
306 (UserList(), "UserList([])"),
304 (
307 (
305 UserList(i for i in range(1000, 1020)),
308 UserList(i for i in range(1000, 1020)),
306 "UserList([1000,\n"
309 "UserList([1000,\n"
307 " 1001,\n"
310 " 1001,\n"
308 " 1002,\n"
311 " 1002,\n"
309 " 1003,\n"
312 " 1003,\n"
310 " 1004,\n"
313 " 1004,\n"
311 " 1005,\n"
314 " 1005,\n"
312 " 1006,\n"
315 " 1006,\n"
313 " 1007,\n"
316 " 1007,\n"
314 " 1008,\n"
317 " 1008,\n"
315 " 1009,\n"
318 " 1009,\n"
316 " 1010,\n"
319 " 1010,\n"
317 " 1011,\n"
320 " 1011,\n"
318 " 1012,\n"
321 " 1012,\n"
319 " 1013,\n"
322 " 1013,\n"
320 " 1014,\n"
323 " 1014,\n"
321 " 1015,\n"
324 " 1015,\n"
322 " 1016,\n"
325 " 1016,\n"
323 " 1017,\n"
326 " 1017,\n"
324 " 1018,\n"
327 " 1018,\n"
325 " 1019])",
328 " 1019])",
326 ),
329 ),
327 (a, "UserList([UserList(...)])"),
330 (a, "UserList([UserList(...)])"),
328 ]
331 ]
329 for obj, expected in cases:
332 for obj, expected in cases:
330 assert pretty.pretty(obj) == expected
333 assert pretty.pretty(obj) == expected
331
334
332
335
333 # TODO : pytest.mark.parametrise once nose is gone.
336 # TODO : pytest.mark.parametrise once nose is gone.
334 def test_collections_defaultdict():
337 def test_collections_defaultdict():
335 # Create defaultdicts with cycles
338 # Create defaultdicts with cycles
336 a = defaultdict()
339 a = defaultdict()
337 a.default_factory = a
340 a.default_factory = a
338 b = defaultdict(list)
341 b = defaultdict(list)
339 b['key'] = b
342 b['key'] = b
340
343
341 # Dictionary order cannot be relied on, test against single keys.
344 # Dictionary order cannot be relied on, test against single keys.
342 cases = [
345 cases = [
343 (defaultdict(list), 'defaultdict(list, {})'),
346 (defaultdict(list), 'defaultdict(list, {})'),
344 (defaultdict(list, {'key': '-' * 50}),
347 (defaultdict(list, {'key': '-' * 50}),
345 "defaultdict(list,\n"
348 "defaultdict(list,\n"
346 " {'key': '--------------------------------------------------'})"),
349 " {'key': '--------------------------------------------------'})"),
347 (a, 'defaultdict(defaultdict(...), {})'),
350 (a, 'defaultdict(defaultdict(...), {})'),
348 (b, "defaultdict(list, {'key': defaultdict(...)})"),
351 (b, "defaultdict(list, {'key': defaultdict(...)})"),
349 ]
352 ]
350 for obj, expected in cases:
353 for obj, expected in cases:
351 assert pretty.pretty(obj) == expected
354 assert pretty.pretty(obj) == expected
352
355
353
356
354 # TODO : pytest.mark.parametrise once nose is gone.
357 # TODO : pytest.mark.parametrise once nose is gone.
355 def test_collections_ordereddict():
358 def test_collections_ordereddict():
356 # Create OrderedDict with cycle
359 # Create OrderedDict with cycle
357 a = OrderedDict()
360 a = OrderedDict()
358 a['key'] = a
361 a['key'] = a
359
362
360 cases = [
363 cases = [
361 (OrderedDict(), 'OrderedDict()'),
364 (OrderedDict(), 'OrderedDict()'),
362 (OrderedDict((i, i) for i in range(1000, 1010)),
365 (OrderedDict((i, i) for i in range(1000, 1010)),
363 'OrderedDict([(1000, 1000),\n'
366 'OrderedDict([(1000, 1000),\n'
364 ' (1001, 1001),\n'
367 ' (1001, 1001),\n'
365 ' (1002, 1002),\n'
368 ' (1002, 1002),\n'
366 ' (1003, 1003),\n'
369 ' (1003, 1003),\n'
367 ' (1004, 1004),\n'
370 ' (1004, 1004),\n'
368 ' (1005, 1005),\n'
371 ' (1005, 1005),\n'
369 ' (1006, 1006),\n'
372 ' (1006, 1006),\n'
370 ' (1007, 1007),\n'
373 ' (1007, 1007),\n'
371 ' (1008, 1008),\n'
374 ' (1008, 1008),\n'
372 ' (1009, 1009)])'),
375 ' (1009, 1009)])'),
373 (a, "OrderedDict([('key', OrderedDict(...))])"),
376 (a, "OrderedDict([('key', OrderedDict(...))])"),
374 ]
377 ]
375 for obj, expected in cases:
378 for obj, expected in cases:
376 assert pretty.pretty(obj) == expected
379 assert pretty.pretty(obj) == expected
377
380
378
381
379 # TODO : pytest.mark.parametrise once nose is gone.
382 # TODO : pytest.mark.parametrise once nose is gone.
380 def test_collections_deque():
383 def test_collections_deque():
381 # Create deque with cycle
384 # Create deque with cycle
382 a = deque()
385 a = deque()
383 a.append(a)
386 a.append(a)
384
387
385 cases = [
388 cases = [
386 (deque(), 'deque([])'),
389 (deque(), 'deque([])'),
387 (deque(i for i in range(1000, 1020)),
390 (deque(i for i in range(1000, 1020)),
388 'deque([1000,\n'
391 'deque([1000,\n'
389 ' 1001,\n'
392 ' 1001,\n'
390 ' 1002,\n'
393 ' 1002,\n'
391 ' 1003,\n'
394 ' 1003,\n'
392 ' 1004,\n'
395 ' 1004,\n'
393 ' 1005,\n'
396 ' 1005,\n'
394 ' 1006,\n'
397 ' 1006,\n'
395 ' 1007,\n'
398 ' 1007,\n'
396 ' 1008,\n'
399 ' 1008,\n'
397 ' 1009,\n'
400 ' 1009,\n'
398 ' 1010,\n'
401 ' 1010,\n'
399 ' 1011,\n'
402 ' 1011,\n'
400 ' 1012,\n'
403 ' 1012,\n'
401 ' 1013,\n'
404 ' 1013,\n'
402 ' 1014,\n'
405 ' 1014,\n'
403 ' 1015,\n'
406 ' 1015,\n'
404 ' 1016,\n'
407 ' 1016,\n'
405 ' 1017,\n'
408 ' 1017,\n'
406 ' 1018,\n'
409 ' 1018,\n'
407 ' 1019])'),
410 ' 1019])'),
408 (a, 'deque([deque(...)])'),
411 (a, 'deque([deque(...)])'),
409 ]
412 ]
410 for obj, expected in cases:
413 for obj, expected in cases:
411 assert pretty.pretty(obj) == expected
414 assert pretty.pretty(obj) == expected
412
415
413
416
414 # TODO : pytest.mark.parametrise once nose is gone.
417 # TODO : pytest.mark.parametrise once nose is gone.
415 def test_collections_counter():
418 def test_collections_counter():
416 class MyCounter(Counter):
419 class MyCounter(Counter):
417 pass
420 pass
418 cases = [
421 cases = [
419 (Counter(), 'Counter()'),
422 (Counter(), 'Counter()'),
420 (Counter(a=1), "Counter({'a': 1})"),
423 (Counter(a=1), "Counter({'a': 1})"),
421 (MyCounter(a=1), "MyCounter({'a': 1})"),
424 (MyCounter(a=1), "MyCounter({'a': 1})"),
422 ]
425 ]
423 for obj, expected in cases:
426 for obj, expected in cases:
424 assert pretty.pretty(obj) == expected
427 assert pretty.pretty(obj) == expected
425
428
426 # TODO : pytest.mark.parametrise once nose is gone.
429 # TODO : pytest.mark.parametrise once nose is gone.
427 def test_mappingproxy():
430 def test_mappingproxy():
428 MP = types.MappingProxyType
431 MP = types.MappingProxyType
429 underlying_dict = {}
432 underlying_dict = {}
430 mp_recursive = MP(underlying_dict)
433 mp_recursive = MP(underlying_dict)
431 underlying_dict[2] = mp_recursive
434 underlying_dict[2] = mp_recursive
432 underlying_dict[3] = underlying_dict
435 underlying_dict[3] = underlying_dict
433
436
434 cases = [
437 cases = [
435 (MP({}), "mappingproxy({})"),
438 (MP({}), "mappingproxy({})"),
436 (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
439 (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
437 (MP({k: k.upper() for k in string.ascii_lowercase}),
440 (MP({k: k.upper() for k in string.ascii_lowercase}),
438 "mappingproxy({'a': 'A',\n"
441 "mappingproxy({'a': 'A',\n"
439 " 'b': 'B',\n"
442 " 'b': 'B',\n"
440 " 'c': 'C',\n"
443 " 'c': 'C',\n"
441 " 'd': 'D',\n"
444 " 'd': 'D',\n"
442 " 'e': 'E',\n"
445 " 'e': 'E',\n"
443 " 'f': 'F',\n"
446 " 'f': 'F',\n"
444 " 'g': 'G',\n"
447 " 'g': 'G',\n"
445 " 'h': 'H',\n"
448 " 'h': 'H',\n"
446 " 'i': 'I',\n"
449 " 'i': 'I',\n"
447 " 'j': 'J',\n"
450 " 'j': 'J',\n"
448 " 'k': 'K',\n"
451 " 'k': 'K',\n"
449 " 'l': 'L',\n"
452 " 'l': 'L',\n"
450 " 'm': 'M',\n"
453 " 'm': 'M',\n"
451 " 'n': 'N',\n"
454 " 'n': 'N',\n"
452 " 'o': 'O',\n"
455 " 'o': 'O',\n"
453 " 'p': 'P',\n"
456 " 'p': 'P',\n"
454 " 'q': 'Q',\n"
457 " 'q': 'Q',\n"
455 " 'r': 'R',\n"
458 " 'r': 'R',\n"
456 " 's': 'S',\n"
459 " 's': 'S',\n"
457 " 't': 'T',\n"
460 " 't': 'T',\n"
458 " 'u': 'U',\n"
461 " 'u': 'U',\n"
459 " 'v': 'V',\n"
462 " 'v': 'V',\n"
460 " 'w': 'W',\n"
463 " 'w': 'W',\n"
461 " 'x': 'X',\n"
464 " 'x': 'X',\n"
462 " 'y': 'Y',\n"
465 " 'y': 'Y',\n"
463 " 'z': 'Z'})"),
466 " 'z': 'Z'})"),
464 (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
467 (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
465 (underlying_dict,
468 (underlying_dict,
466 "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
469 "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
467 ]
470 ]
468 for obj, expected in cases:
471 for obj, expected in cases:
469 assert pretty.pretty(obj) == expected
472 assert pretty.pretty(obj) == expected
470
473
471
474
472 # TODO : pytest.mark.parametrise once nose is gone.
475 # TODO : pytest.mark.parametrise once nose is gone.
473 def test_simplenamespace():
476 def test_simplenamespace():
474 SN = types.SimpleNamespace
477 SN = types.SimpleNamespace
475
478
476 sn_recursive = SN()
479 sn_recursive = SN()
477 sn_recursive.first = sn_recursive
480 sn_recursive.first = sn_recursive
478 sn_recursive.second = sn_recursive
481 sn_recursive.second = sn_recursive
479 cases = [
482 cases = [
480 (SN(), "namespace()"),
483 (SN(), "namespace()"),
481 (SN(x=SN()), "namespace(x=namespace())"),
484 (SN(x=SN()), "namespace(x=namespace())"),
482 (SN(a_long_name=[SN(s=string.ascii_lowercase)]*3, a_short_name=None),
485 (SN(a_long_name=[SN(s=string.ascii_lowercase)]*3, a_short_name=None),
483 "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
486 "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
484 " namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
487 " namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
485 " namespace(s='abcdefghijklmnopqrstuvwxyz')],\n"
488 " namespace(s='abcdefghijklmnopqrstuvwxyz')],\n"
486 " a_short_name=None)"),
489 " a_short_name=None)"),
487 (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
490 (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
488 ]
491 ]
489 for obj, expected in cases:
492 for obj, expected in cases:
490 assert pretty.pretty(obj) == expected
493 assert pretty.pretty(obj) == expected
491
494
492
495
493 def test_pretty_environ():
496 def test_pretty_environ():
494 dict_repr = pretty.pretty(dict(os.environ))
497 dict_repr = pretty.pretty(dict(os.environ))
495 # reindent to align with 'environ' prefix
498 # reindent to align with 'environ' prefix
496 dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ')))
499 dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ')))
497 env_repr = pretty.pretty(os.environ)
500 env_repr = pretty.pretty(os.environ)
498 assert env_repr == "environ" + dict_indented
501 assert env_repr == "environ" + dict_indented
499
502
500
503
501 def test_function_pretty():
504 def test_function_pretty():
502 "Test pretty print of function"
505 "Test pretty print of function"
503 # posixpath is a pure python module, its interface is consistent
506 # posixpath is a pure python module, its interface is consistent
504 # across Python distributions
507 # across Python distributions
505 import posixpath
508 import posixpath
506
509
507 assert pretty.pretty(posixpath.join) == "<function posixpath.join(a, *p)>"
510 assert pretty.pretty(posixpath.join) == "<function posixpath.join(a, *p)>"
508
511
509 # custom function
512 # custom function
510 def meaning_of_life(question=None):
513 def meaning_of_life(question=None):
511 if question:
514 if question:
512 return 42
515 return 42
513 return "Don't panic"
516 return "Don't panic"
514
517
515 assert "meaning_of_life(question=None)" in pretty.pretty(meaning_of_life)
518 assert "meaning_of_life(question=None)" in pretty.pretty(meaning_of_life)
516
519
517
520
518 class OrderedCounter(Counter, OrderedDict):
521 class OrderedCounter(Counter, OrderedDict):
519 'Counter that remembers the order elements are first encountered'
522 'Counter that remembers the order elements are first encountered'
520
523
521 def __repr__(self):
524 def __repr__(self):
522 return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
525 return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
523
526
524 def __reduce__(self):
527 def __reduce__(self):
525 return self.__class__, (OrderedDict(self),)
528 return self.__class__, (OrderedDict(self),)
526
529
527 class MySet(set): # Override repr of a basic type
530 class MySet(set): # Override repr of a basic type
528 def __repr__(self):
531 def __repr__(self):
529 return 'mine'
532 return 'mine'
530
533
531 def test_custom_repr():
534 def test_custom_repr():
532 """A custom repr should override a pretty printer for a parent type"""
535 """A custom repr should override a pretty printer for a parent type"""
533 oc = OrderedCounter("abracadabra")
536 oc = OrderedCounter("abracadabra")
534 assert "OrderedCounter(OrderedDict" in pretty.pretty(oc)
537 assert "OrderedCounter(OrderedDict" in pretty.pretty(oc)
535
538
536 assert pretty.pretty(MySet()) == "mine"
539 assert pretty.pretty(MySet()) == "mine"
General Comments 0
You need to be logged in to leave comments. Login now