##// END OF EJS Templates
remove nose from test pretty
Matthias Bussonnier -
Show More
@@ -1,492 +1,502 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 import pytest
15 import pytest
16
16
17 from IPython.lib import pretty
17 from IPython.lib import pretty
18 from IPython.testing.decorators import skip_without, skip_iptest_but_not_pytest
18 from IPython.testing.decorators import skip_without, skip_iptest_but_not_pytest
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 assert 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 assert 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 assert gotoutput == expectedoutput
107
107
108
108
109 @pytest.mark.parametrize(
109 @pytest.mark.parametrize(
110 "obj,expected_output",
110 "obj,expected_output",
111 zip(
111 zip(
112 [
112 [
113 set(),
113 set(),
114 frozenset(),
114 frozenset(),
115 set([1]),
115 set([1]),
116 frozenset([1]),
116 frozenset([1]),
117 set([1, 2]),
117 set([1, 2]),
118 frozenset([1, 2]),
118 frozenset([1, 2]),
119 set([-1, -2, -3]),
119 set([-1, -2, -3]),
120 ],
120 ],
121 [
121 [
122 "set()",
122 "set()",
123 "frozenset()",
123 "frozenset()",
124 "{1}",
124 "{1}",
125 "frozenset({1})",
125 "frozenset({1})",
126 "{1, 2}",
126 "{1, 2}",
127 "frozenset({1, 2})",
127 "frozenset({1, 2})",
128 "{-3, -2, -1}",
128 "{-3, -2, -1}",
129 ],
129 ],
130 ),
130 ),
131 )
131 )
132 @skip_iptest_but_not_pytest
132 @skip_iptest_but_not_pytest
133 def test_sets(obj, expected_output):
133 def test_sets(obj, expected_output):
134 """
134 """
135 Test that set and frozenset use Python 3 formatting.
135 Test that set and frozenset use Python 3 formatting.
136 """
136 """
137 got_output = pretty.pretty(obj)
137 got_output = pretty.pretty(obj)
138 nt.assert_equal(got_output, expected_output)
138 assert got_output == expected_output
139
139
140
140
141 @skip_without('xxlimited')
141 @skip_without('xxlimited')
142 def test_pprint_heap_allocated_type():
142 def test_pprint_heap_allocated_type():
143 """
143 """
144 Test that pprint works for heap allocated types.
144 Test that pprint works for heap allocated types.
145 """
145 """
146 import xxlimited
146 import xxlimited
147 output = pretty.pretty(xxlimited.Null)
147 output = pretty.pretty(xxlimited.Null)
148 nt.assert_equal(output, 'xxlimited.Null')
148 assert output == "xxlimited.Null"
149
149
150
150 def test_pprint_nomod():
151 def test_pprint_nomod():
151 """
152 """
152 Test that pprint works for classes with no __module__.
153 Test that pprint works for classes with no __module__.
153 """
154 """
154 output = pretty.pretty(NoModule)
155 output = pretty.pretty(NoModule)
155 nt.assert_equal(output, 'NoModule')
156 assert output == "NoModule"
156
157
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 nt.assert_equal(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 nt.assert_equal(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 nt.assert_equal(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 nt.assert_raises(ZeroDivisionError):
181 with nt.assert_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 nt.assert_raises(BadException):
198 with nt.assert_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 nt.assert_equal(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 nt.assert_equal(p, u)
276 assert p == u
275 p = pretty.pretty([c])
277 p = pretty.pretty([c])
276 nt.assert_equal(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 nt.assert_equal(output, '%s.MyObj' % __name__)
295 assert output == "%s.MyObj" % __name__
294 nt.assert_true(type_pprint_wrapper.called)
296 nt.assert_true(type_pprint_wrapper.called)
295
297
296
298
299 # TODO : pytest.mark.parametrise once nose is gone.
297 def test_collections_defaultdict():
300 def test_collections_defaultdict():
298 # Create defaultdicts with cycles
301 # Create defaultdicts with cycles
299 a = defaultdict()
302 a = defaultdict()
300 a.default_factory = a
303 a.default_factory = a
301 b = defaultdict(list)
304 b = defaultdict(list)
302 b['key'] = b
305 b['key'] = b
303
306
304 # Dictionary order cannot be relied on, test against single keys.
307 # Dictionary order cannot be relied on, test against single keys.
305 cases = [
308 cases = [
306 (defaultdict(list), 'defaultdict(list, {})'),
309 (defaultdict(list), 'defaultdict(list, {})'),
307 (defaultdict(list, {'key': '-' * 50}),
310 (defaultdict(list, {'key': '-' * 50}),
308 "defaultdict(list,\n"
311 "defaultdict(list,\n"
309 " {'key': '--------------------------------------------------'})"),
312 " {'key': '--------------------------------------------------'})"),
310 (a, 'defaultdict(defaultdict(...), {})'),
313 (a, 'defaultdict(defaultdict(...), {})'),
311 (b, "defaultdict(list, {'key': defaultdict(...)})"),
314 (b, "defaultdict(list, {'key': defaultdict(...)})"),
312 ]
315 ]
313 for obj, expected in cases:
316 for obj, expected in cases:
314 nt.assert_equal(pretty.pretty(obj), expected)
317 assert pretty.pretty(obj) == expected
315
318
316
319
320 # TODO : pytest.mark.parametrise once nose is gone.
317 def test_collections_ordereddict():
321 def test_collections_ordereddict():
318 # Create OrderedDict with cycle
322 # Create OrderedDict with cycle
319 a = OrderedDict()
323 a = OrderedDict()
320 a['key'] = a
324 a['key'] = a
321
325
322 cases = [
326 cases = [
323 (OrderedDict(), 'OrderedDict()'),
327 (OrderedDict(), 'OrderedDict()'),
324 (OrderedDict((i, i) for i in range(1000, 1010)),
328 (OrderedDict((i, i) for i in range(1000, 1010)),
325 'OrderedDict([(1000, 1000),\n'
329 'OrderedDict([(1000, 1000),\n'
326 ' (1001, 1001),\n'
330 ' (1001, 1001),\n'
327 ' (1002, 1002),\n'
331 ' (1002, 1002),\n'
328 ' (1003, 1003),\n'
332 ' (1003, 1003),\n'
329 ' (1004, 1004),\n'
333 ' (1004, 1004),\n'
330 ' (1005, 1005),\n'
334 ' (1005, 1005),\n'
331 ' (1006, 1006),\n'
335 ' (1006, 1006),\n'
332 ' (1007, 1007),\n'
336 ' (1007, 1007),\n'
333 ' (1008, 1008),\n'
337 ' (1008, 1008),\n'
334 ' (1009, 1009)])'),
338 ' (1009, 1009)])'),
335 (a, "OrderedDict([('key', OrderedDict(...))])"),
339 (a, "OrderedDict([('key', OrderedDict(...))])"),
336 ]
340 ]
337 for obj, expected in cases:
341 for obj, expected in cases:
338 nt.assert_equal(pretty.pretty(obj), expected)
342 assert pretty.pretty(obj) == expected
339
343
340
344
345 # TODO : pytest.mark.parametrise once nose is gone.
341 def test_collections_deque():
346 def test_collections_deque():
342 # Create deque with cycle
347 # Create deque with cycle
343 a = deque()
348 a = deque()
344 a.append(a)
349 a.append(a)
345
350
346 cases = [
351 cases = [
347 (deque(), 'deque([])'),
352 (deque(), 'deque([])'),
348 (deque(i for i in range(1000, 1020)),
353 (deque(i for i in range(1000, 1020)),
349 'deque([1000,\n'
354 'deque([1000,\n'
350 ' 1001,\n'
355 ' 1001,\n'
351 ' 1002,\n'
356 ' 1002,\n'
352 ' 1003,\n'
357 ' 1003,\n'
353 ' 1004,\n'
358 ' 1004,\n'
354 ' 1005,\n'
359 ' 1005,\n'
355 ' 1006,\n'
360 ' 1006,\n'
356 ' 1007,\n'
361 ' 1007,\n'
357 ' 1008,\n'
362 ' 1008,\n'
358 ' 1009,\n'
363 ' 1009,\n'
359 ' 1010,\n'
364 ' 1010,\n'
360 ' 1011,\n'
365 ' 1011,\n'
361 ' 1012,\n'
366 ' 1012,\n'
362 ' 1013,\n'
367 ' 1013,\n'
363 ' 1014,\n'
368 ' 1014,\n'
364 ' 1015,\n'
369 ' 1015,\n'
365 ' 1016,\n'
370 ' 1016,\n'
366 ' 1017,\n'
371 ' 1017,\n'
367 ' 1018,\n'
372 ' 1018,\n'
368 ' 1019])'),
373 ' 1019])'),
369 (a, 'deque([deque(...)])'),
374 (a, 'deque([deque(...)])'),
370 ]
375 ]
371 for obj, expected in cases:
376 for obj, expected in cases:
372 nt.assert_equal(pretty.pretty(obj), expected)
377 assert pretty.pretty(obj) == expected
373
378
379
380 # TODO : pytest.mark.parametrise once nose is gone.
374 def test_collections_counter():
381 def test_collections_counter():
375 class MyCounter(Counter):
382 class MyCounter(Counter):
376 pass
383 pass
377 cases = [
384 cases = [
378 (Counter(), 'Counter()'),
385 (Counter(), 'Counter()'),
379 (Counter(a=1), "Counter({'a': 1})"),
386 (Counter(a=1), "Counter({'a': 1})"),
380 (MyCounter(a=1), "MyCounter({'a': 1})"),
387 (MyCounter(a=1), "MyCounter({'a': 1})"),
381 ]
388 ]
382 for obj, expected in cases:
389 for obj, expected in cases:
383 nt.assert_equal(pretty.pretty(obj), expected)
390 assert pretty.pretty(obj) == expected
384
391
392 # TODO : pytest.mark.parametrise once nose is gone.
385 def test_mappingproxy():
393 def test_mappingproxy():
386 MP = types.MappingProxyType
394 MP = types.MappingProxyType
387 underlying_dict = {}
395 underlying_dict = {}
388 mp_recursive = MP(underlying_dict)
396 mp_recursive = MP(underlying_dict)
389 underlying_dict[2] = mp_recursive
397 underlying_dict[2] = mp_recursive
390 underlying_dict[3] = underlying_dict
398 underlying_dict[3] = underlying_dict
391
399
392 cases = [
400 cases = [
393 (MP({}), "mappingproxy({})"),
401 (MP({}), "mappingproxy({})"),
394 (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
402 (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
395 (MP({k: k.upper() for k in string.ascii_lowercase}),
403 (MP({k: k.upper() for k in string.ascii_lowercase}),
396 "mappingproxy({'a': 'A',\n"
404 "mappingproxy({'a': 'A',\n"
397 " 'b': 'B',\n"
405 " 'b': 'B',\n"
398 " 'c': 'C',\n"
406 " 'c': 'C',\n"
399 " 'd': 'D',\n"
407 " 'd': 'D',\n"
400 " 'e': 'E',\n"
408 " 'e': 'E',\n"
401 " 'f': 'F',\n"
409 " 'f': 'F',\n"
402 " 'g': 'G',\n"
410 " 'g': 'G',\n"
403 " 'h': 'H',\n"
411 " 'h': 'H',\n"
404 " 'i': 'I',\n"
412 " 'i': 'I',\n"
405 " 'j': 'J',\n"
413 " 'j': 'J',\n"
406 " 'k': 'K',\n"
414 " 'k': 'K',\n"
407 " 'l': 'L',\n"
415 " 'l': 'L',\n"
408 " 'm': 'M',\n"
416 " 'm': 'M',\n"
409 " 'n': 'N',\n"
417 " 'n': 'N',\n"
410 " 'o': 'O',\n"
418 " 'o': 'O',\n"
411 " 'p': 'P',\n"
419 " 'p': 'P',\n"
412 " 'q': 'Q',\n"
420 " 'q': 'Q',\n"
413 " 'r': 'R',\n"
421 " 'r': 'R',\n"
414 " 's': 'S',\n"
422 " 's': 'S',\n"
415 " 't': 'T',\n"
423 " 't': 'T',\n"
416 " 'u': 'U',\n"
424 " 'u': 'U',\n"
417 " 'v': 'V',\n"
425 " 'v': 'V',\n"
418 " 'w': 'W',\n"
426 " 'w': 'W',\n"
419 " 'x': 'X',\n"
427 " 'x': 'X',\n"
420 " 'y': 'Y',\n"
428 " 'y': 'Y',\n"
421 " 'z': 'Z'})"),
429 " 'z': 'Z'})"),
422 (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
430 (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
423 (underlying_dict,
431 (underlying_dict,
424 "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
432 "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
425 ]
433 ]
426 for obj, expected in cases:
434 for obj, expected in cases:
427 nt.assert_equal(pretty.pretty(obj), expected)
435 assert pretty.pretty(obj) == expected
428
436
429
437
438 # TODO : pytest.mark.parametrise once nose is gone.
430 def test_simplenamespace():
439 def test_simplenamespace():
431 SN = types.SimpleNamespace
440 SN = types.SimpleNamespace
432
441
433 sn_recursive = SN()
442 sn_recursive = SN()
434 sn_recursive.first = sn_recursive
443 sn_recursive.first = sn_recursive
435 sn_recursive.second = sn_recursive
444 sn_recursive.second = sn_recursive
436 cases = [
445 cases = [
437 (SN(), "namespace()"),
446 (SN(), "namespace()"),
438 (SN(x=SN()), "namespace(x=namespace())"),
447 (SN(x=SN()), "namespace(x=namespace())"),
439 (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),
440 "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
449 "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
441 " namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
450 " namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
442 " namespace(s='abcdefghijklmnopqrstuvwxyz')],\n"
451 " namespace(s='abcdefghijklmnopqrstuvwxyz')],\n"
443 " a_short_name=None)"),
452 " a_short_name=None)"),
444 (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
453 (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
445 ]
454 ]
446 for obj, expected in cases:
455 for obj, expected in cases:
447 nt.assert_equal(pretty.pretty(obj), expected)
456 assert pretty.pretty(obj) == expected
448
457
449
458
450 def test_pretty_environ():
459 def test_pretty_environ():
451 dict_repr = pretty.pretty(dict(os.environ))
460 dict_repr = pretty.pretty(dict(os.environ))
452 # reindent to align with 'environ' prefix
461 # reindent to align with 'environ' prefix
453 dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ')))
462 dict_indented = dict_repr.replace('\n', '\n' + (' ' * len('environ')))
454 env_repr = pretty.pretty(os.environ)
463 env_repr = pretty.pretty(os.environ)
455 nt.assert_equal(env_repr, 'environ' + dict_indented)
464 assert env_repr == "environ" + dict_indented
456
465
457
466
458 def test_function_pretty():
467 def test_function_pretty():
459 "Test pretty print of function"
468 "Test pretty print of function"
460 # posixpath is a pure python module, its interface is consistent
469 # posixpath is a pure python module, its interface is consistent
461 # across Python distributions
470 # across Python distributions
462 import posixpath
471 import posixpath
463 nt.assert_equal(pretty.pretty(posixpath.join), '<function posixpath.join(a, *p)>')
472
464
473 assert pretty.pretty(posixpath.join) == "<function posixpath.join(a, *p)>"
474
465 # custom function
475 # custom function
466 def meaning_of_life(question=None):
476 def meaning_of_life(question=None):
467 if question:
477 if question:
468 return 42
478 return 42
469 return "Don't panic"
479 return "Don't panic"
470
480
471 nt.assert_in('meaning_of_life(question=None)', pretty.pretty(meaning_of_life))
481 nt.assert_in('meaning_of_life(question=None)', pretty.pretty(meaning_of_life))
472
482
473
483
474 class OrderedCounter(Counter, OrderedDict):
484 class OrderedCounter(Counter, OrderedDict):
475 'Counter that remembers the order elements are first encountered'
485 'Counter that remembers the order elements are first encountered'
476
486
477 def __repr__(self):
487 def __repr__(self):
478 return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
488 return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
479
489
480 def __reduce__(self):
490 def __reduce__(self):
481 return self.__class__, (OrderedDict(self),)
491 return self.__class__, (OrderedDict(self),)
482
492
483 class MySet(set): # Override repr of a basic type
493 class MySet(set): # Override repr of a basic type
484 def __repr__(self):
494 def __repr__(self):
485 return 'mine'
495 return 'mine'
486
496
487 def test_custom_repr():
497 def test_custom_repr():
488 """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"""
489 oc = OrderedCounter("abracadabra")
499 oc = OrderedCounter("abracadabra")
490 nt.assert_in("OrderedCounter(OrderedDict", pretty.pretty(oc))
500 nt.assert_in("OrderedCounter(OrderedDict", pretty.pretty(oc))
491
501
492 nt.assert_equal(pretty.pretty(MySet()), 'mine')
502 assert pretty.pretty(MySet()) == "mine"
General Comments 0
You need to be logged in to leave comments. Login now