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