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