##// END OF EJS Templates
Adds test for pprinting type with meta __repr__...
Remi Rampin -
Show More
@@ -1,216 +1,232 b''
1 """Tests for IPython.lib.pretty."""
1 """Tests for IPython.lib.pretty."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 # Third-party imports
8 # Third-party imports
9 import nose.tools as nt
9 import nose.tools as nt
10
10
11 # Our own imports
11 # Our own imports
12 from IPython.lib import pretty
12 from IPython.lib import pretty
13 from IPython.testing.decorators import skip_without
13 from IPython.testing.decorators import skip_without
14
14
15
15
16 class MyList(object):
16 class MyList(object):
17 def __init__(self, content):
17 def __init__(self, content):
18 self.content = content
18 self.content = content
19 def _repr_pretty_(self, p, cycle):
19 def _repr_pretty_(self, p, cycle):
20 if cycle:
20 if cycle:
21 p.text("MyList(...)")
21 p.text("MyList(...)")
22 else:
22 else:
23 with p.group(3, "MyList(", ")"):
23 with p.group(3, "MyList(", ")"):
24 for (i, child) in enumerate(self.content):
24 for (i, child) in enumerate(self.content):
25 if i:
25 if i:
26 p.text(",")
26 p.text(",")
27 p.breakable()
27 p.breakable()
28 else:
28 else:
29 p.breakable("")
29 p.breakable("")
30 p.pretty(child)
30 p.pretty(child)
31
31
32
32
33 class MyDict(dict):
33 class MyDict(dict):
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 p.text("MyDict(...)")
35 p.text("MyDict(...)")
36
36
37 class MyObj(object):
37 class MyObj(object):
38 def somemethod(self):
38 def somemethod(self):
39 pass
39 pass
40
40
41
41
42 class Dummy1(object):
42 class Dummy1(object):
43 def _repr_pretty_(self, p, cycle):
43 def _repr_pretty_(self, p, cycle):
44 p.text("Dummy1(...)")
44 p.text("Dummy1(...)")
45
45
46 class Dummy2(Dummy1):
46 class Dummy2(Dummy1):
47 _repr_pretty_ = None
47 _repr_pretty_ = None
48
48
49 class NoModule(object):
49 class NoModule(object):
50 pass
50 pass
51
51
52 NoModule.__module__ = None
52 NoModule.__module__ = None
53
53
54 class Breaking(object):
54 class Breaking(object):
55 def _repr_pretty_(self, p, cycle):
55 def _repr_pretty_(self, p, cycle):
56 with p.group(4,"TG: ",":"):
56 with p.group(4,"TG: ",":"):
57 p.text("Breaking(")
57 p.text("Breaking(")
58 p.break_()
58 p.break_()
59 p.text(")")
59 p.text(")")
60
60
61 class BreakingRepr(object):
61 class BreakingRepr(object):
62 def __repr__(self):
62 def __repr__(self):
63 return "Breaking(\n)"
63 return "Breaking(\n)"
64
64
65 class BreakingReprParent(object):
65 class BreakingReprParent(object):
66 def _repr_pretty_(self, p, cycle):
66 def _repr_pretty_(self, p, cycle):
67 with p.group(4,"TG: ",":"):
67 with p.group(4,"TG: ",":"):
68 p.pretty(BreakingRepr())
68 p.pretty(BreakingRepr())
69
69
70 class BadRepr(object):
70 class BadRepr(object):
71
71
72 def __repr__(self):
72 def __repr__(self):
73 return 1/0
73 return 1/0
74
74
75
75
76 def test_indentation():
76 def test_indentation():
77 """Test correct indentation in groups"""
77 """Test correct indentation in groups"""
78 count = 40
78 count = 40
79 gotoutput = pretty.pretty(MyList(range(count)))
79 gotoutput = pretty.pretty(MyList(range(count)))
80 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
80 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
81
81
82 nt.assert_equal(gotoutput, expectedoutput)
82 nt.assert_equal(gotoutput, expectedoutput)
83
83
84
84
85 def test_dispatch():
85 def test_dispatch():
86 """
86 """
87 Test correct dispatching: The _repr_pretty_ method for MyDict
87 Test correct dispatching: The _repr_pretty_ method for MyDict
88 must be found before the registered printer for dict.
88 must be found before the registered printer for dict.
89 """
89 """
90 gotoutput = pretty.pretty(MyDict())
90 gotoutput = pretty.pretty(MyDict())
91 expectedoutput = "MyDict(...)"
91 expectedoutput = "MyDict(...)"
92
92
93 nt.assert_equal(gotoutput, expectedoutput)
93 nt.assert_equal(gotoutput, expectedoutput)
94
94
95
95
96 def test_callability_checking():
96 def test_callability_checking():
97 """
97 """
98 Test that the _repr_pretty_ method is tested for callability and skipped if
98 Test that the _repr_pretty_ method is tested for callability and skipped if
99 not.
99 not.
100 """
100 """
101 gotoutput = pretty.pretty(Dummy2())
101 gotoutput = pretty.pretty(Dummy2())
102 expectedoutput = "Dummy1(...)"
102 expectedoutput = "Dummy1(...)"
103
103
104 nt.assert_equal(gotoutput, expectedoutput)
104 nt.assert_equal(gotoutput, expectedoutput)
105
105
106
106
107 def test_sets():
107 def test_sets():
108 """
108 """
109 Test that set and frozenset use Python 3 formatting.
109 Test that set and frozenset use Python 3 formatting.
110 """
110 """
111 objects = [set(), frozenset(), set([1]), frozenset([1]), set([1, 2]),
111 objects = [set(), frozenset(), set([1]), frozenset([1]), set([1, 2]),
112 frozenset([1, 2]), set([-1, -2, -3])]
112 frozenset([1, 2]), set([-1, -2, -3])]
113 expected = ['set()', 'frozenset()', '{1}', 'frozenset({1})', '{1, 2}',
113 expected = ['set()', 'frozenset()', '{1}', 'frozenset({1})', '{1, 2}',
114 'frozenset({1, 2})', '{-3, -2, -1}']
114 'frozenset({1, 2})', '{-3, -2, -1}']
115 for obj, expected_output in zip(objects, expected):
115 for obj, expected_output in zip(objects, expected):
116 got_output = pretty.pretty(obj)
116 got_output = pretty.pretty(obj)
117 yield nt.assert_equal, got_output, expected_output
117 yield nt.assert_equal, got_output, expected_output
118
118
119
119
120 @skip_without('xxlimited')
120 @skip_without('xxlimited')
121 def test_pprint_heap_allocated_type():
121 def test_pprint_heap_allocated_type():
122 """
122 """
123 Test that pprint works for heap allocated types.
123 Test that pprint works for heap allocated types.
124 """
124 """
125 import xxlimited
125 import xxlimited
126 output = pretty.pretty(xxlimited.Null)
126 output = pretty.pretty(xxlimited.Null)
127 nt.assert_equal(output, 'xxlimited.Null')
127 nt.assert_equal(output, 'xxlimited.Null')
128
128
129 def test_pprint_nomod():
129 def test_pprint_nomod():
130 """
130 """
131 Test that pprint works for classes with no __module__.
131 Test that pprint works for classes with no __module__.
132 """
132 """
133 output = pretty.pretty(NoModule)
133 output = pretty.pretty(NoModule)
134 nt.assert_equal(output, 'NoModule')
134 nt.assert_equal(output, 'NoModule')
135
135
136 def test_pprint_break():
136 def test_pprint_break():
137 """
137 """
138 Test that p.break_ produces expected output
138 Test that p.break_ produces expected output
139 """
139 """
140 output = pretty.pretty(Breaking())
140 output = pretty.pretty(Breaking())
141 expected = "TG: Breaking(\n ):"
141 expected = "TG: Breaking(\n ):"
142 nt.assert_equal(output, expected)
142 nt.assert_equal(output, expected)
143
143
144 def test_pprint_break_repr():
144 def test_pprint_break_repr():
145 """
145 """
146 Test that p.break_ is used in repr
146 Test that p.break_ is used in repr
147 """
147 """
148 output = pretty.pretty(BreakingReprParent())
148 output = pretty.pretty(BreakingReprParent())
149 expected = "TG: Breaking(\n ):"
149 expected = "TG: Breaking(\n ):"
150 nt.assert_equal(output, expected)
150 nt.assert_equal(output, expected)
151
151
152 def test_bad_repr():
152 def test_bad_repr():
153 """Don't catch bad repr errors"""
153 """Don't catch bad repr errors"""
154 with nt.assert_raises(ZeroDivisionError):
154 with nt.assert_raises(ZeroDivisionError):
155 output = pretty.pretty(BadRepr())
155 output = pretty.pretty(BadRepr())
156
156
157 class BadException(Exception):
157 class BadException(Exception):
158 def __str__(self):
158 def __str__(self):
159 return -1
159 return -1
160
160
161 class ReallyBadRepr(object):
161 class ReallyBadRepr(object):
162 __module__ = 1
162 __module__ = 1
163 @property
163 @property
164 def __class__(self):
164 def __class__(self):
165 raise ValueError("I am horrible")
165 raise ValueError("I am horrible")
166
166
167 def __repr__(self):
167 def __repr__(self):
168 raise BadException()
168 raise BadException()
169
169
170 def test_really_bad_repr():
170 def test_really_bad_repr():
171 with nt.assert_raises(BadException):
171 with nt.assert_raises(BadException):
172 output = pretty.pretty(ReallyBadRepr())
172 output = pretty.pretty(ReallyBadRepr())
173
173
174
174
175 class SA(object):
175 class SA(object):
176 pass
176 pass
177
177
178 class SB(SA):
178 class SB(SA):
179 pass
179 pass
180
180
181 def test_super_repr():
181 def test_super_repr():
182 output = pretty.pretty(super(SA))
182 output = pretty.pretty(super(SA))
183 nt.assert_in("SA", output)
183 nt.assert_in("SA", output)
184
184
185 sb = SB()
185 sb = SB()
186 output = pretty.pretty(super(SA, sb))
186 output = pretty.pretty(super(SA, sb))
187 nt.assert_in("SA", output)
187 nt.assert_in("SA", output)
188
188
189
189
190 def test_long_list():
190 def test_long_list():
191 lis = list(range(10000))
191 lis = list(range(10000))
192 p = pretty.pretty(lis)
192 p = pretty.pretty(lis)
193 last2 = p.rsplit('\n', 2)[-2:]
193 last2 = p.rsplit('\n', 2)[-2:]
194 nt.assert_equal(last2, [' 999,', ' ...]'])
194 nt.assert_equal(last2, [' 999,', ' ...]'])
195
195
196 def test_long_set():
196 def test_long_set():
197 s = set(range(10000))
197 s = set(range(10000))
198 p = pretty.pretty(s)
198 p = pretty.pretty(s)
199 last2 = p.rsplit('\n', 2)[-2:]
199 last2 = p.rsplit('\n', 2)[-2:]
200 nt.assert_equal(last2, [' 999,', ' ...}'])
200 nt.assert_equal(last2, [' 999,', ' ...}'])
201
201
202 def test_long_tuple():
202 def test_long_tuple():
203 tup = tuple(range(10000))
203 tup = tuple(range(10000))
204 p = pretty.pretty(tup)
204 p = pretty.pretty(tup)
205 last2 = p.rsplit('\n', 2)[-2:]
205 last2 = p.rsplit('\n', 2)[-2:]
206 nt.assert_equal(last2, [' 999,', ' ...)'])
206 nt.assert_equal(last2, [' 999,', ' ...)'])
207
207
208 def test_long_dict():
208 def test_long_dict():
209 d = { n:n for n in range(10000) }
209 d = { n:n for n in range(10000) }
210 p = pretty.pretty(d)
210 p = pretty.pretty(d)
211 last2 = p.rsplit('\n', 2)[-2:]
211 last2 = p.rsplit('\n', 2)[-2:]
212 nt.assert_equal(last2, [' 999: 999,', ' ...}'])
212 nt.assert_equal(last2, [' 999: 999,', ' ...}'])
213
213
214 def test_unbound_method():
214 def test_unbound_method():
215 output = pretty.pretty(MyObj.somemethod)
215 output = pretty.pretty(MyObj.somemethod)
216 nt.assert_in('MyObj.somemethod', output)
216 nt.assert_in('MyObj.somemethod', output)
217
218
219 class MetaClass(type):
220 def __new__(cls, name):
221 return type.__new__(cls, name, (object,), {'name': name})
222
223 def __repr__(self):
224 return "[CUSTOM REPR FOR CLASS %s]" % self.name
225
226
227 ClassWithMeta = MetaClass('ClassWithMeta')
228
229
230 def test_metaclass_repr():
231 output = pretty.pretty(ClassWithMeta)
232 nt.assert_equal(output, "[CUSTOM REPR FOR CLASS ClassWithMeta]")
General Comments 0
You need to be logged in to leave comments. Login now