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