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