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