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