##// END OF EJS Templates
Remove some nose
Matthias Bussonnier -
Show More
@@ -1,533 +1,542 b''
1 """Tests for the Formatters."""
1 """Tests for the Formatters."""
2
2
3 import warnings
3 import warnings
4 from math import pi
4 from math import pi
5
5
6 try:
6 try:
7 import numpy
7 import numpy
8 except:
8 except:
9 numpy = None
9 numpy = None
10 import nose.tools as nt
10 import nose.tools as nt
11
11
12 from IPython import get_ipython
12 from IPython import get_ipython
13 from traitlets.config import Config
13 from traitlets.config import Config
14 from IPython.core.formatters import (
14 from IPython.core.formatters import (
15 PlainTextFormatter, HTMLFormatter, PDFFormatter, _mod_name_key,
15 PlainTextFormatter, HTMLFormatter, PDFFormatter, _mod_name_key,
16 DisplayFormatter, JSONFormatter,
16 DisplayFormatter, JSONFormatter,
17 )
17 )
18 from IPython.utils.io import capture_output
18 from IPython.utils.io import capture_output
19
19
20 class A(object):
20 class A(object):
21 def __repr__(self):
21 def __repr__(self):
22 return 'A()'
22 return 'A()'
23
23
24 class B(A):
24 class B(A):
25 def __repr__(self):
25 def __repr__(self):
26 return 'B()'
26 return 'B()'
27
27
28 class C:
28 class C:
29 pass
29 pass
30
30
31 class BadRepr(object):
31 class BadRepr(object):
32 def __repr__(self):
32 def __repr__(self):
33 raise ValueError("bad repr")
33 raise ValueError("bad repr")
34
34
35 class BadPretty(object):
35 class BadPretty(object):
36 _repr_pretty_ = None
36 _repr_pretty_ = None
37
37
38 class GoodPretty(object):
38 class GoodPretty(object):
39 def _repr_pretty_(self, pp, cycle):
39 def _repr_pretty_(self, pp, cycle):
40 pp.text('foo')
40 pp.text('foo')
41
41
42 def __repr__(self):
42 def __repr__(self):
43 return 'GoodPretty()'
43 return 'GoodPretty()'
44
44
45 def foo_printer(obj, pp, cycle):
45 def foo_printer(obj, pp, cycle):
46 pp.text('foo')
46 pp.text('foo')
47
47
48 def test_pretty():
48 def test_pretty():
49 f = PlainTextFormatter()
49 f = PlainTextFormatter()
50 f.for_type(A, foo_printer)
50 f.for_type(A, foo_printer)
51 nt.assert_equal(f(A()), 'foo')
51 assert f(A()) == "foo"
52 nt.assert_equal(f(B()), 'B()')
52 assert f(B()) == "B()"
53 nt.assert_equal(f(GoodPretty()), 'foo')
53 assert f(GoodPretty()) == "foo"
54 # Just don't raise an exception for the following:
54 # Just don't raise an exception for the following:
55 f(BadPretty())
55 f(BadPretty())
56
56
57 f.pprint = False
57 f.pprint = False
58 nt.assert_equal(f(A()), 'A()')
58 assert f(A()) == "A()"
59 nt.assert_equal(f(B()), 'B()')
59 assert f(B()) == "B()"
60 nt.assert_equal(f(GoodPretty()), 'GoodPretty()')
60 assert f(GoodPretty()) == "GoodPretty()"
61
61
62
62
63 def test_deferred():
63 def test_deferred():
64 f = PlainTextFormatter()
64 f = PlainTextFormatter()
65
65
66 def test_precision():
66 def test_precision():
67 """test various values for float_precision."""
67 """test various values for float_precision."""
68 f = PlainTextFormatter()
68 f = PlainTextFormatter()
69 nt.assert_equal(f(pi), repr(pi))
69 assert f(pi) == repr(pi)
70 f.float_precision = 0
70 f.float_precision = 0
71 if numpy:
71 if numpy:
72 po = numpy.get_printoptions()
72 po = numpy.get_printoptions()
73 nt.assert_equal(po['precision'], 0)
73 assert po["precision"] == 0
74 nt.assert_equal(f(pi), '3')
74 assert f(pi) == "3"
75 f.float_precision = 2
75 f.float_precision = 2
76 if numpy:
76 if numpy:
77 po = numpy.get_printoptions()
77 po = numpy.get_printoptions()
78 nt.assert_equal(po['precision'], 2)
78 assert po["precision"] == 2
79 nt.assert_equal(f(pi), '3.14')
79 assert f(pi) == "3.14"
80 f.float_precision = '%g'
80 f.float_precision = "%g"
81 if numpy:
81 if numpy:
82 po = numpy.get_printoptions()
82 po = numpy.get_printoptions()
83 nt.assert_equal(po['precision'], 2)
83 assert po["precision"] == 2
84 nt.assert_equal(f(pi), '3.14159')
84 assert f(pi) == "3.14159"
85 f.float_precision = '%e'
85 f.float_precision = "%e"
86 nt.assert_equal(f(pi), '3.141593e+00')
86 assert f(pi) == "3.141593e+00"
87 f.float_precision = ''
87 f.float_precision = ""
88 if numpy:
88 if numpy:
89 po = numpy.get_printoptions()
89 po = numpy.get_printoptions()
90 nt.assert_equal(po['precision'], 8)
90 assert po["precision"] == 8
91 nt.assert_equal(f(pi), repr(pi))
91 assert f(pi) == repr(pi)
92
92
93
93 def test_bad_precision():
94 def test_bad_precision():
94 """test various invalid values for float_precision."""
95 """test various invalid values for float_precision."""
95 f = PlainTextFormatter()
96 f = PlainTextFormatter()
96 def set_fp(p):
97 def set_fp(p):
97 f.float_precision=p
98 f.float_precision=p
98 nt.assert_raises(ValueError, set_fp, '%')
99 nt.assert_raises(ValueError, set_fp, '%')
99 nt.assert_raises(ValueError, set_fp, '%.3f%i')
100 nt.assert_raises(ValueError, set_fp, '%.3f%i')
100 nt.assert_raises(ValueError, set_fp, 'foo')
101 nt.assert_raises(ValueError, set_fp, 'foo')
101 nt.assert_raises(ValueError, set_fp, -1)
102 nt.assert_raises(ValueError, set_fp, -1)
102
103
103 def test_for_type():
104 def test_for_type():
104 f = PlainTextFormatter()
105 f = PlainTextFormatter()
105
106
106 # initial return, None
107 # initial return, None
107 nt.assert_is(f.for_type(C, foo_printer), None)
108 nt.assert_is(f.for_type(C, foo_printer), None)
108 # no func queries
109 # no func queries
109 nt.assert_is(f.for_type(C), foo_printer)
110 nt.assert_is(f.for_type(C), foo_printer)
110 # shouldn't change anything
111 # shouldn't change anything
111 nt.assert_is(f.for_type(C), foo_printer)
112 nt.assert_is(f.for_type(C), foo_printer)
112 # None should do the same
113 # None should do the same
113 nt.assert_is(f.for_type(C, None), foo_printer)
114 nt.assert_is(f.for_type(C, None), foo_printer)
114 nt.assert_is(f.for_type(C, None), foo_printer)
115 nt.assert_is(f.for_type(C, None), foo_printer)
115
116
116 def test_for_type_string():
117 def test_for_type_string():
117 f = PlainTextFormatter()
118 f = PlainTextFormatter()
118
119
119 type_str = '%s.%s' % (C.__module__, 'C')
120 type_str = '%s.%s' % (C.__module__, 'C')
120
121
121 # initial return, None
122 # initial return, None
122 nt.assert_is(f.for_type(type_str, foo_printer), None)
123 nt.assert_is(f.for_type(type_str, foo_printer), None)
123 # no func queries
124 # no func queries
124 nt.assert_is(f.for_type(type_str), foo_printer)
125 nt.assert_is(f.for_type(type_str), foo_printer)
125 nt.assert_in(_mod_name_key(C), f.deferred_printers)
126 nt.assert_in(_mod_name_key(C), f.deferred_printers)
126 nt.assert_is(f.for_type(C), foo_printer)
127 nt.assert_is(f.for_type(C), foo_printer)
127 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
128 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
128 nt.assert_in(C, f.type_printers)
129 nt.assert_in(C, f.type_printers)
129
130
130 def test_for_type_by_name():
131 def test_for_type_by_name():
131 f = PlainTextFormatter()
132 f = PlainTextFormatter()
132
133
133 mod = C.__module__
134 mod = C.__module__
134
135
135 # initial return, None
136 # initial return, None
136 nt.assert_is(f.for_type_by_name(mod, 'C', foo_printer), None)
137 nt.assert_is(f.for_type_by_name(mod, 'C', foo_printer), None)
137 # no func queries
138 # no func queries
138 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
139 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
139 # shouldn't change anything
140 # shouldn't change anything
140 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
141 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
141 # None should do the same
142 # None should do the same
142 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
143 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
143 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
144 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
144
145
145 def test_lookup():
146 def test_lookup():
146 f = PlainTextFormatter()
147 f = PlainTextFormatter()
147
148
148 f.for_type(C, foo_printer)
149 f.for_type(C, foo_printer)
149 nt.assert_is(f.lookup(C()), foo_printer)
150 nt.assert_is(f.lookup(C()), foo_printer)
150 with nt.assert_raises(KeyError):
151 with nt.assert_raises(KeyError):
151 f.lookup(A())
152 f.lookup(A())
152
153
153 def test_lookup_string():
154 def test_lookup_string():
154 f = PlainTextFormatter()
155 f = PlainTextFormatter()
155 type_str = '%s.%s' % (C.__module__, 'C')
156 type_str = '%s.%s' % (C.__module__, 'C')
156
157
157 f.for_type(type_str, foo_printer)
158 f.for_type(type_str, foo_printer)
158 nt.assert_is(f.lookup(C()), foo_printer)
159 nt.assert_is(f.lookup(C()), foo_printer)
159 # should move from deferred to imported dict
160 # should move from deferred to imported dict
160 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
161 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
161 nt.assert_in(C, f.type_printers)
162 nt.assert_in(C, f.type_printers)
162
163
163 def test_lookup_by_type():
164 def test_lookup_by_type():
164 f = PlainTextFormatter()
165 f = PlainTextFormatter()
165 f.for_type(C, foo_printer)
166 f.for_type(C, foo_printer)
166 nt.assert_is(f.lookup_by_type(C), foo_printer)
167 nt.assert_is(f.lookup_by_type(C), foo_printer)
167 with nt.assert_raises(KeyError):
168 with nt.assert_raises(KeyError):
168 f.lookup_by_type(A)
169 f.lookup_by_type(A)
169
170
170 def test_lookup_by_type_string():
171 def test_lookup_by_type_string():
171 f = PlainTextFormatter()
172 f = PlainTextFormatter()
172 type_str = '%s.%s' % (C.__module__, 'C')
173 type_str = '%s.%s' % (C.__module__, 'C')
173 f.for_type(type_str, foo_printer)
174 f.for_type(type_str, foo_printer)
174
175
175 # verify insertion
176 # verify insertion
176 nt.assert_in(_mod_name_key(C), f.deferred_printers)
177 nt.assert_in(_mod_name_key(C), f.deferred_printers)
177 nt.assert_not_in(C, f.type_printers)
178 nt.assert_not_in(C, f.type_printers)
178
179
179 nt.assert_is(f.lookup_by_type(type_str), foo_printer)
180 nt.assert_is(f.lookup_by_type(type_str), foo_printer)
180 # lookup by string doesn't cause import
181 # lookup by string doesn't cause import
181 nt.assert_in(_mod_name_key(C), f.deferred_printers)
182 nt.assert_in(_mod_name_key(C), f.deferred_printers)
182 nt.assert_not_in(C, f.type_printers)
183 nt.assert_not_in(C, f.type_printers)
183
184
184 nt.assert_is(f.lookup_by_type(C), foo_printer)
185 nt.assert_is(f.lookup_by_type(C), foo_printer)
185 # should move from deferred to imported dict
186 # should move from deferred to imported dict
186 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
187 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
187 nt.assert_in(C, f.type_printers)
188 nt.assert_in(C, f.type_printers)
188
189
189 def test_in_formatter():
190 def test_in_formatter():
190 f = PlainTextFormatter()
191 f = PlainTextFormatter()
191 f.for_type(C, foo_printer)
192 f.for_type(C, foo_printer)
192 type_str = '%s.%s' % (C.__module__, 'C')
193 type_str = '%s.%s' % (C.__module__, 'C')
193 nt.assert_in(C, f)
194 nt.assert_in(C, f)
194 nt.assert_in(type_str, f)
195 nt.assert_in(type_str, f)
195
196
196 def test_string_in_formatter():
197 def test_string_in_formatter():
197 f = PlainTextFormatter()
198 f = PlainTextFormatter()
198 type_str = '%s.%s' % (C.__module__, 'C')
199 type_str = '%s.%s' % (C.__module__, 'C')
199 f.for_type(type_str, foo_printer)
200 f.for_type(type_str, foo_printer)
200 nt.assert_in(type_str, f)
201 nt.assert_in(type_str, f)
201 nt.assert_in(C, f)
202 nt.assert_in(C, f)
202
203
203 def test_pop():
204 def test_pop():
204 f = PlainTextFormatter()
205 f = PlainTextFormatter()
205 f.for_type(C, foo_printer)
206 f.for_type(C, foo_printer)
206 nt.assert_is(f.lookup_by_type(C), foo_printer)
207 nt.assert_is(f.lookup_by_type(C), foo_printer)
207 nt.assert_is(f.pop(C, None), foo_printer)
208 nt.assert_is(f.pop(C, None), foo_printer)
208 f.for_type(C, foo_printer)
209 f.for_type(C, foo_printer)
209 nt.assert_is(f.pop(C), foo_printer)
210 nt.assert_is(f.pop(C), foo_printer)
210 with nt.assert_raises(KeyError):
211 with nt.assert_raises(KeyError):
211 f.lookup_by_type(C)
212 f.lookup_by_type(C)
212 with nt.assert_raises(KeyError):
213 with nt.assert_raises(KeyError):
213 f.pop(C)
214 f.pop(C)
214 with nt.assert_raises(KeyError):
215 with nt.assert_raises(KeyError):
215 f.pop(A)
216 f.pop(A)
216 nt.assert_is(f.pop(A, None), None)
217 nt.assert_is(f.pop(A, None), None)
217
218
218 def test_pop_string():
219 def test_pop_string():
219 f = PlainTextFormatter()
220 f = PlainTextFormatter()
220 type_str = '%s.%s' % (C.__module__, 'C')
221 type_str = '%s.%s' % (C.__module__, 'C')
221
222
222 with nt.assert_raises(KeyError):
223 with nt.assert_raises(KeyError):
223 f.pop(type_str)
224 f.pop(type_str)
224
225
225 f.for_type(type_str, foo_printer)
226 f.for_type(type_str, foo_printer)
226 f.pop(type_str)
227 f.pop(type_str)
227 with nt.assert_raises(KeyError):
228 with nt.assert_raises(KeyError):
228 f.lookup_by_type(C)
229 f.lookup_by_type(C)
229 with nt.assert_raises(KeyError):
230 with nt.assert_raises(KeyError):
230 f.pop(type_str)
231 f.pop(type_str)
231
232
232 f.for_type(C, foo_printer)
233 f.for_type(C, foo_printer)
233 nt.assert_is(f.pop(type_str, None), foo_printer)
234 nt.assert_is(f.pop(type_str, None), foo_printer)
234 with nt.assert_raises(KeyError):
235 with nt.assert_raises(KeyError):
235 f.lookup_by_type(C)
236 f.lookup_by_type(C)
236 with nt.assert_raises(KeyError):
237 with nt.assert_raises(KeyError):
237 f.pop(type_str)
238 f.pop(type_str)
238 nt.assert_is(f.pop(type_str, None), None)
239 nt.assert_is(f.pop(type_str, None), None)
239
240
240
241
241 def test_error_method():
242 def test_error_method():
242 f = HTMLFormatter()
243 f = HTMLFormatter()
243 class BadHTML(object):
244 class BadHTML(object):
244 def _repr_html_(self):
245 def _repr_html_(self):
245 raise ValueError("Bad HTML")
246 raise ValueError("Bad HTML")
246 bad = BadHTML()
247 bad = BadHTML()
247 with capture_output() as captured:
248 with capture_output() as captured:
248 result = f(bad)
249 result = f(bad)
249 nt.assert_is(result, None)
250 nt.assert_is(result, None)
250 nt.assert_in("Traceback", captured.stdout)
251 nt.assert_in("Traceback", captured.stdout)
251 nt.assert_in("Bad HTML", captured.stdout)
252 nt.assert_in("Bad HTML", captured.stdout)
252 nt.assert_in("_repr_html_", captured.stdout)
253 nt.assert_in("_repr_html_", captured.stdout)
253
254
254 def test_nowarn_notimplemented():
255 def test_nowarn_notimplemented():
255 f = HTMLFormatter()
256 f = HTMLFormatter()
256 class HTMLNotImplemented(object):
257 class HTMLNotImplemented(object):
257 def _repr_html_(self):
258 def _repr_html_(self):
258 raise NotImplementedError
259 raise NotImplementedError
259 h = HTMLNotImplemented()
260 h = HTMLNotImplemented()
260 with capture_output() as captured:
261 with capture_output() as captured:
261 result = f(h)
262 result = f(h)
262 nt.assert_is(result, None)
263 nt.assert_is(result, None)
263 nt.assert_equal("", captured.stderr)
264 assert "" == captured.stderr
264 nt.assert_equal("", captured.stdout)
265 assert "" == captured.stdout
266
265
267
266 def test_warn_error_for_type():
268 def test_warn_error_for_type():
267 f = HTMLFormatter()
269 f = HTMLFormatter()
268 f.for_type(int, lambda i: name_error)
270 f.for_type(int, lambda i: name_error)
269 with capture_output() as captured:
271 with capture_output() as captured:
270 result = f(5)
272 result = f(5)
271 nt.assert_is(result, None)
273 nt.assert_is(result, None)
272 nt.assert_in("Traceback", captured.stdout)
274 nt.assert_in("Traceback", captured.stdout)
273 nt.assert_in("NameError", captured.stdout)
275 nt.assert_in("NameError", captured.stdout)
274 nt.assert_in("name_error", captured.stdout)
276 nt.assert_in("name_error", captured.stdout)
275
277
276 def test_error_pretty_method():
278 def test_error_pretty_method():
277 f = PlainTextFormatter()
279 f = PlainTextFormatter()
278 class BadPretty(object):
280 class BadPretty(object):
279 def _repr_pretty_(self):
281 def _repr_pretty_(self):
280 return "hello"
282 return "hello"
281 bad = BadPretty()
283 bad = BadPretty()
282 with capture_output() as captured:
284 with capture_output() as captured:
283 result = f(bad)
285 result = f(bad)
284 nt.assert_is(result, None)
286 nt.assert_is(result, None)
285 nt.assert_in("Traceback", captured.stdout)
287 nt.assert_in("Traceback", captured.stdout)
286 nt.assert_in("_repr_pretty_", captured.stdout)
288 nt.assert_in("_repr_pretty_", captured.stdout)
287 nt.assert_in("given", captured.stdout)
289 nt.assert_in("given", captured.stdout)
288 nt.assert_in("argument", captured.stdout)
290 nt.assert_in("argument", captured.stdout)
289
291
290
292
291 def test_bad_repr_traceback():
293 def test_bad_repr_traceback():
292 f = PlainTextFormatter()
294 f = PlainTextFormatter()
293 bad = BadRepr()
295 bad = BadRepr()
294 with capture_output() as captured:
296 with capture_output() as captured:
295 result = f(bad)
297 result = f(bad)
296 # catches error, returns None
298 # catches error, returns None
297 nt.assert_is(result, None)
299 nt.assert_is(result, None)
298 nt.assert_in("Traceback", captured.stdout)
300 nt.assert_in("Traceback", captured.stdout)
299 nt.assert_in("__repr__", captured.stdout)
301 nt.assert_in("__repr__", captured.stdout)
300 nt.assert_in("ValueError", captured.stdout)
302 nt.assert_in("ValueError", captured.stdout)
301
303
302
304
303 class MakePDF(object):
305 class MakePDF(object):
304 def _repr_pdf_(self):
306 def _repr_pdf_(self):
305 return 'PDF'
307 return 'PDF'
306
308
307 def test_pdf_formatter():
309 def test_pdf_formatter():
308 pdf = MakePDF()
310 pdf = MakePDF()
309 f = PDFFormatter()
311 f = PDFFormatter()
310 nt.assert_equal(f(pdf), 'PDF')
312 assert f(pdf) == "PDF"
313
311
314
312 def test_print_method_bound():
315 def test_print_method_bound():
313 f = HTMLFormatter()
316 f = HTMLFormatter()
314 class MyHTML(object):
317 class MyHTML(object):
315 def _repr_html_(self):
318 def _repr_html_(self):
316 return "hello"
319 return "hello"
317 with capture_output() as captured:
320 with capture_output() as captured:
318 result = f(MyHTML)
321 result = f(MyHTML)
319 nt.assert_is(result, None)
322 nt.assert_is(result, None)
320 nt.assert_not_in("FormatterWarning", captured.stderr)
323 nt.assert_not_in("FormatterWarning", captured.stderr)
321
324
322 with capture_output() as captured:
325 with capture_output() as captured:
323 result = f(MyHTML())
326 result = f(MyHTML())
324 nt.assert_equal(result, "hello")
327 assert result == "hello"
325 nt.assert_equal(captured.stderr, "")
328 assert captured.stderr == ""
329
326
330
327 def test_print_method_weird():
331 def test_print_method_weird():
328
332
329 class TextMagicHat(object):
333 class TextMagicHat(object):
330 def __getattr__(self, key):
334 def __getattr__(self, key):
331 return key
335 return key
332
336
333 f = HTMLFormatter()
337 f = HTMLFormatter()
334
338
335 text_hat = TextMagicHat()
339 text_hat = TextMagicHat()
336 nt.assert_equal(text_hat._repr_html_, '_repr_html_')
340 assert text_hat._repr_html_ == "_repr_html_"
337 with capture_output() as captured:
341 with capture_output() as captured:
338 result = f(text_hat)
342 result = f(text_hat)
339
343
340 nt.assert_is(result, None)
344 nt.assert_is(result, None)
341 nt.assert_not_in("FormatterWarning", captured.stderr)
345 nt.assert_not_in("FormatterWarning", captured.stderr)
342
346
343 class CallableMagicHat(object):
347 class CallableMagicHat(object):
344 def __getattr__(self, key):
348 def __getattr__(self, key):
345 return lambda : key
349 return lambda : key
346
350
347 call_hat = CallableMagicHat()
351 call_hat = CallableMagicHat()
348 with capture_output() as captured:
352 with capture_output() as captured:
349 result = f(call_hat)
353 result = f(call_hat)
350
354
351 nt.assert_equal(result, None)
355 assert result == None
352
356
353 class BadReprArgs(object):
357 class BadReprArgs(object):
354 def _repr_html_(self, extra, args):
358 def _repr_html_(self, extra, args):
355 return "html"
359 return "html"
356
360
357 bad = BadReprArgs()
361 bad = BadReprArgs()
358 with capture_output() as captured:
362 with capture_output() as captured:
359 result = f(bad)
363 result = f(bad)
360
364
361 nt.assert_is(result, None)
365 nt.assert_is(result, None)
362 nt.assert_not_in("FormatterWarning", captured.stderr)
366 nt.assert_not_in("FormatterWarning", captured.stderr)
363
367
364
368
365 def test_format_config():
369 def test_format_config():
366 """config objects don't pretend to support fancy reprs with lazy attrs"""
370 """config objects don't pretend to support fancy reprs with lazy attrs"""
367 f = HTMLFormatter()
371 f = HTMLFormatter()
368 cfg = Config()
372 cfg = Config()
369 with capture_output() as captured:
373 with capture_output() as captured:
370 result = f(cfg)
374 result = f(cfg)
371 nt.assert_is(result, None)
375 nt.assert_is(result, None)
372 nt.assert_equal(captured.stderr, "")
376 assert captured.stderr == ""
373
377
374 with capture_output() as captured:
378 with capture_output() as captured:
375 result = f(Config)
379 result = f(Config)
376 nt.assert_is(result, None)
380 nt.assert_is(result, None)
377 nt.assert_equal(captured.stderr, "")
381 assert captured.stderr == ""
382
378
383
379 def test_pretty_max_seq_length():
384 def test_pretty_max_seq_length():
380 f = PlainTextFormatter(max_seq_length=1)
385 f = PlainTextFormatter(max_seq_length=1)
381 lis = list(range(3))
386 lis = list(range(3))
382 text = f(lis)
387 text = f(lis)
383 nt.assert_equal(text, '[0, ...]')
388 assert text == "[0, ...]"
384 f.max_seq_length = 0
389 f.max_seq_length = 0
385 text = f(lis)
390 text = f(lis)
386 nt.assert_equal(text, '[0, 1, 2]')
391 assert text == "[0, 1, 2]"
387 text = f(list(range(1024)))
392 text = f(list(range(1024)))
388 lines = text.splitlines()
393 lines = text.splitlines()
389 nt.assert_equal(len(lines), 1024)
394 assert len(lines) == 1024
390
395
391
396
392 def test_ipython_display_formatter():
397 def test_ipython_display_formatter():
393 """Objects with _ipython_display_ defined bypass other formatters"""
398 """Objects with _ipython_display_ defined bypass other formatters"""
394 f = get_ipython().display_formatter
399 f = get_ipython().display_formatter
395 catcher = []
400 catcher = []
396 class SelfDisplaying(object):
401 class SelfDisplaying(object):
397 def _ipython_display_(self):
402 def _ipython_display_(self):
398 catcher.append(self)
403 catcher.append(self)
399
404
400 class NotSelfDisplaying(object):
405 class NotSelfDisplaying(object):
401 def __repr__(self):
406 def __repr__(self):
402 return "NotSelfDisplaying"
407 return "NotSelfDisplaying"
403
408
404 def _ipython_display_(self):
409 def _ipython_display_(self):
405 raise NotImplementedError
410 raise NotImplementedError
406
411
407 save_enabled = f.ipython_display_formatter.enabled
412 save_enabled = f.ipython_display_formatter.enabled
408 f.ipython_display_formatter.enabled = True
413 f.ipython_display_formatter.enabled = True
409
414
410 yes = SelfDisplaying()
415 yes = SelfDisplaying()
411 no = NotSelfDisplaying()
416 no = NotSelfDisplaying()
412
417
413 d, md = f.format(no)
418 d, md = f.format(no)
414 nt.assert_equal(d, {'text/plain': repr(no)})
419 assert d == {"text/plain": repr(no)}
415 nt.assert_equal(md, {})
420 assert md == {}
416 nt.assert_equal(catcher, [])
421 assert catcher == []
417
422
418 d, md = f.format(yes)
423 d, md = f.format(yes)
419 nt.assert_equal(d, {})
424 assert d == {}
420 nt.assert_equal(md, {})
425 assert md == {}
421 nt.assert_equal(catcher, [yes])
426 assert catcher == [yes]
422
427
423 f.ipython_display_formatter.enabled = save_enabled
428 f.ipython_display_formatter.enabled = save_enabled
424
429
425
430
426 def test_json_as_string_deprecated():
431 def test_json_as_string_deprecated():
427 class JSONString(object):
432 class JSONString(object):
428 def _repr_json_(self):
433 def _repr_json_(self):
429 return '{}'
434 return '{}'
430
435
431 f = JSONFormatter()
436 f = JSONFormatter()
432 with warnings.catch_warnings(record=True) as w:
437 with warnings.catch_warnings(record=True) as w:
433 d = f(JSONString())
438 d = f(JSONString())
434 nt.assert_equal(d, {})
439 assert d == {}
435 nt.assert_equal(len(w), 1)
440 assert len(w) == 1
436
441
437
442
438 def test_repr_mime():
443 def test_repr_mime():
439 class HasReprMime(object):
444 class HasReprMime(object):
440 def _repr_mimebundle_(self, include=None, exclude=None):
445 def _repr_mimebundle_(self, include=None, exclude=None):
441 return {
446 return {
442 'application/json+test.v2': {
447 'application/json+test.v2': {
443 'x': 'y'
448 'x': 'y'
444 },
449 },
445 'plain/text' : '<HasReprMime>',
450 'plain/text' : '<HasReprMime>',
446 'image/png' : 'i-overwrite'
451 'image/png' : 'i-overwrite'
447 }
452 }
448
453
449 def _repr_png_(self):
454 def _repr_png_(self):
450 return 'should-be-overwritten'
455 return 'should-be-overwritten'
451 def _repr_html_(self):
456 def _repr_html_(self):
452 return '<b>hi!</b>'
457 return '<b>hi!</b>'
453
458
454 f = get_ipython().display_formatter
459 f = get_ipython().display_formatter
455 html_f = f.formatters['text/html']
460 html_f = f.formatters['text/html']
456 save_enabled = html_f.enabled
461 save_enabled = html_f.enabled
457 html_f.enabled = True
462 html_f.enabled = True
458 obj = HasReprMime()
463 obj = HasReprMime()
459 d, md = f.format(obj)
464 d, md = f.format(obj)
460 html_f.enabled = save_enabled
465 html_f.enabled = save_enabled
461
466
462 nt.assert_equal(sorted(d), ['application/json+test.v2',
467 assert sorted(d) == [
463 'image/png',
468 "application/json+test.v2",
464 'plain/text',
469 "image/png",
465 'text/html',
470 "plain/text",
466 'text/plain'])
471 "text/html",
467 nt.assert_equal(md, {})
472 "text/plain",
473 ]
474 assert md == {}
468
475
469 d, md = f.format(obj, include={'image/png'})
476 d, md = f.format(obj, include={"image/png"})
470 nt.assert_equal(list(d.keys()), ['image/png'],
477 assert list(d.keys()) == [
471 'Include should filter out even things from repr_mimebundle')
478 "image/png"
472 nt.assert_equal(d['image/png'], 'i-overwrite', '_repr_mimebundle_ take precedence')
479 ], "Include should filter out even things from repr_mimebundle"
473
480
481 assert d["image/png"] == "i-overwrite", "_repr_mimebundle_ take precedence"
474
482
475
483
476 def test_pass_correct_include_exclude():
484 def test_pass_correct_include_exclude():
477 class Tester(object):
485 class Tester(object):
478
486
479 def __init__(self, include=None, exclude=None):
487 def __init__(self, include=None, exclude=None):
480 self.include = include
488 self.include = include
481 self.exclude = exclude
489 self.exclude = exclude
482
490
483 def _repr_mimebundle_(self, include, exclude, **kwargs):
491 def _repr_mimebundle_(self, include, exclude, **kwargs):
484 if include and (include != self.include):
492 if include and (include != self.include):
485 raise ValueError('include got modified: display() may be broken.')
493 raise ValueError('include got modified: display() may be broken.')
486 if exclude and (exclude != self.exclude):
494 if exclude and (exclude != self.exclude):
487 raise ValueError('exclude got modified: display() may be broken.')
495 raise ValueError('exclude got modified: display() may be broken.')
488
496
489 return None
497 return None
490
498
491 include = {'a', 'b', 'c'}
499 include = {'a', 'b', 'c'}
492 exclude = {'c', 'e' , 'f'}
500 exclude = {'c', 'e' , 'f'}
493
501
494 f = get_ipython().display_formatter
502 f = get_ipython().display_formatter
495 f.format(Tester(include=include, exclude=exclude), include=include, exclude=exclude)
503 f.format(Tester(include=include, exclude=exclude), include=include, exclude=exclude)
496 f.format(Tester(exclude=exclude), exclude=exclude)
504 f.format(Tester(exclude=exclude), exclude=exclude)
497 f.format(Tester(include=include), include=include)
505 f.format(Tester(include=include), include=include)
498
506
499
507
500 def test_repr_mime_meta():
508 def test_repr_mime_meta():
501 class HasReprMimeMeta(object):
509 class HasReprMimeMeta(object):
502 def _repr_mimebundle_(self, include=None, exclude=None):
510 def _repr_mimebundle_(self, include=None, exclude=None):
503 data = {
511 data = {
504 'image/png': 'base64-image-data',
512 'image/png': 'base64-image-data',
505 }
513 }
506 metadata = {
514 metadata = {
507 'image/png': {
515 'image/png': {
508 'width': 5,
516 'width': 5,
509 'height': 10,
517 'height': 10,
510 }
518 }
511 }
519 }
512 return (data, metadata)
520 return (data, metadata)
513
521
514 f = get_ipython().display_formatter
522 f = get_ipython().display_formatter
515 obj = HasReprMimeMeta()
523 obj = HasReprMimeMeta()
516 d, md = f.format(obj)
524 d, md = f.format(obj)
517 nt.assert_equal(sorted(d), ['image/png', 'text/plain'])
525 assert sorted(d) == ["image/png", "text/plain"]
518 nt.assert_equal(md, {
526 assert md == {
519 'image/png': {
527 "image/png": {
520 'width': 5,
528 "width": 5,
521 'height': 10,
529 "height": 10,
522 }
530 }
523 })
531 }
532
524
533
525 def test_repr_mime_failure():
534 def test_repr_mime_failure():
526 class BadReprMime(object):
535 class BadReprMime(object):
527 def _repr_mimebundle_(self, include=None, exclude=None):
536 def _repr_mimebundle_(self, include=None, exclude=None):
528 raise RuntimeError
537 raise RuntimeError
529
538
530 f = get_ipython().display_formatter
539 f = get_ipython().display_formatter
531 obj = BadReprMime()
540 obj = BadReprMime()
532 d, md = f.format(obj)
541 d, md = f.format(obj)
533 nt.assert_in('text/plain', d)
542 assert "text/plain" in d
General Comments 0
You need to be logged in to leave comments. Login now