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