##// END OF EJS Templates
Merge pull request #9827 from danilobellini/pypy...
Min RK -
r22757:99d29c2d merge
parent child Browse files
Show More
@@ -1,26 +1,44 b''
1 # http://travis-ci.org/#!/ipython/ipython
1 # http://travis-ci.org/#!/ipython/ipython
2 language: python
2 language: python
3 python:
3 python:
4 - "nightly"
4 - "nightly"
5 - 3.5
5 - 3.5
6 - 3.4
6 - 3.4
7 - 3.3
7 - 3.3
8 - 2.7
8 - 2.7
9 - pypy
9 sudo: false
10 sudo: false
10 before_install:
11 before_install:
11 - git clone --quiet --depth 1 https://github.com/minrk/travis-wheels travis-wheels
12 - git clone --quiet --depth 1 https://github.com/minrk/travis-wheels travis-wheels
12 - 'if [[ $GROUP != js* ]]; then COVERAGE=""; fi'
13 - 'if [[ $GROUP != js* ]]; then COVERAGE=""; fi'
13 install:
14 install:
14 - pip install "setuptools>=18.5"
15 - pip install "setuptools>=18.5"
16 # Installs PyPy (+ its Numpy). Based on @frol comment at:
17 # https://github.com/travis-ci/travis-ci/issues/5027
18 - |
19 if [ "$TRAVIS_PYTHON_VERSION" = "pypy" ]; then
20 export PYENV_ROOT="$HOME/.pyenv"
21 if [ -f "$PYENV_ROOT/bin/pyenv" ]; then
22 cd "$PYENV_ROOT" && git pull
23 else
24 rm -rf "$PYENV_ROOT" && git clone --depth 1 https://github.com/yyuu/pyenv.git "$PYENV_ROOT"
25 fi
26 export PYPY_VERSION="5.3.1"
27 "$PYENV_ROOT/bin/pyenv" install "pypy-$PYPY_VERSION"
28 virtualenv --python="$PYENV_ROOT/versions/pypy-$PYPY_VERSION/bin/python" "$HOME/virtualenvs/pypy-$PYPY_VERSION"
29 source "$HOME/virtualenvs/pypy-$PYPY_VERSION/bin/activate"
30 pip install https://bitbucket.org/pypy/numpy/get/master.zip
31 fi
15 - pip install -f travis-wheels/wheelhouse -e file://$PWD#egg=ipython[test]
32 - pip install -f travis-wheels/wheelhouse -e file://$PWD#egg=ipython[test]
16 - pip install codecov
33 - pip install codecov
17 script:
34 script:
18 - cd /tmp && iptest --coverage xml && cd -
35 - cd /tmp && iptest --coverage xml && cd -
19 after_success:
36 after_success:
20 - cp /tmp/ipy_coverage.xml ./
37 - cp /tmp/ipy_coverage.xml ./
21 - cp /tmp/.coverage ./
38 - cp /tmp/.coverage ./
22 - codecov
39 - codecov
23
40
24 matrix:
41 matrix:
25 allow_failures:
42 allow_failures:
26 python: nightly
43 - python: nightly
44 - python: pypy
@@ -1,856 +1,868 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Python advanced pretty printer. This pretty printer is intended to
3 Python advanced pretty printer. This pretty printer is intended to
4 replace the old `pprint` python module which does not allow developers
4 replace the old `pprint` python module which does not allow developers
5 to provide their own pretty print callbacks.
5 to provide their own pretty print callbacks.
6
6
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8
8
9
9
10 Example Usage
10 Example Usage
11 -------------
11 -------------
12
12
13 To directly print the representation of an object use `pprint`::
13 To directly print the representation of an object use `pprint`::
14
14
15 from pretty import pprint
15 from pretty import pprint
16 pprint(complex_object)
16 pprint(complex_object)
17
17
18 To get a string of the output use `pretty`::
18 To get a string of the output use `pretty`::
19
19
20 from pretty import pretty
20 from pretty import pretty
21 string = pretty(complex_object)
21 string = pretty(complex_object)
22
22
23
23
24 Extending
24 Extending
25 ---------
25 ---------
26
26
27 The pretty library allows developers to add pretty printing rules for their
27 The pretty library allows developers to add pretty printing rules for their
28 own objects. This process is straightforward. All you have to do is to
28 own objects. This process is straightforward. All you have to do is to
29 add a `_repr_pretty_` method to your object and call the methods on the
29 add a `_repr_pretty_` method to your object and call the methods on the
30 pretty printer passed::
30 pretty printer passed::
31
31
32 class MyObject(object):
32 class MyObject(object):
33
33
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 ...
35 ...
36
36
37 Here is an example implementation of a `_repr_pretty_` method for a list
37 Here is an example implementation of a `_repr_pretty_` method for a list
38 subclass::
38 subclass::
39
39
40 class MyList(list):
40 class MyList(list):
41
41
42 def _repr_pretty_(self, p, cycle):
42 def _repr_pretty_(self, p, cycle):
43 if cycle:
43 if cycle:
44 p.text('MyList(...)')
44 p.text('MyList(...)')
45 else:
45 else:
46 with p.group(8, 'MyList([', '])'):
46 with p.group(8, 'MyList([', '])'):
47 for idx, item in enumerate(self):
47 for idx, item in enumerate(self):
48 if idx:
48 if idx:
49 p.text(',')
49 p.text(',')
50 p.breakable()
50 p.breakable()
51 p.pretty(item)
51 p.pretty(item)
52
52
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
54 react to that or the result is an infinite loop. `p.text()` just adds
54 react to that or the result is an infinite loop. `p.text()` just adds
55 non breaking text to the output, `p.breakable()` either adds a whitespace
55 non breaking text to the output, `p.breakable()` either adds a whitespace
56 or breaks here. If you pass it an argument it's used instead of the
56 or breaks here. If you pass it an argument it's used instead of the
57 default space. `p.pretty` prettyprints another object using the pretty print
57 default space. `p.pretty` prettyprints another object using the pretty print
58 method.
58 method.
59
59
60 The first parameter to the `group` function specifies the extra indentation
60 The first parameter to the `group` function specifies the extra indentation
61 of the next line. In this example the next item will either be on the same
61 of the next line. In this example the next item will either be on the same
62 line (if the items are short enough) or aligned with the right edge of the
62 line (if the items are short enough) or aligned with the right edge of the
63 opening bracket of `MyList`.
63 opening bracket of `MyList`.
64
64
65 If you just want to indent something you can use the group function
65 If you just want to indent something you can use the group function
66 without open / close parameters. You can also use this code::
66 without open / close parameters. You can also use this code::
67
67
68 with p.indent(2):
68 with p.indent(2):
69 ...
69 ...
70
70
71 Inheritance diagram:
71 Inheritance diagram:
72
72
73 .. inheritance-diagram:: IPython.lib.pretty
73 .. inheritance-diagram:: IPython.lib.pretty
74 :parts: 3
74 :parts: 3
75
75
76 :copyright: 2007 by Armin Ronacher.
76 :copyright: 2007 by Armin Ronacher.
77 Portions (c) 2009 by Robert Kern.
77 Portions (c) 2009 by Robert Kern.
78 :license: BSD License.
78 :license: BSD License.
79 """
79 """
80 from __future__ import print_function
80 from __future__ import print_function
81 from contextlib import contextmanager
81 from contextlib import contextmanager
82 import sys
82 import sys
83 import types
83 import types
84 import re
84 import re
85 import datetime
85 import datetime
86 from collections import deque
86 from collections import deque
87
87
88 from IPython.utils.py3compat import PY3, cast_unicode, string_types
88 from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
89 from IPython.utils.encoding import get_stream_enc
89 from IPython.utils.encoding import get_stream_enc
90
90
91 from io import StringIO
91 from io import StringIO
92
92
93
93
94 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
94 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
95 'for_type', 'for_type_by_name']
95 'for_type', 'for_type_by_name']
96
96
97
97
98 MAX_SEQ_LENGTH = 1000
98 MAX_SEQ_LENGTH = 1000
99 _re_pattern_type = type(re.compile(''))
99 _re_pattern_type = type(re.compile(''))
100
100
101 def _safe_getattr(obj, attr, default=None):
101 def _safe_getattr(obj, attr, default=None):
102 """Safe version of getattr.
102 """Safe version of getattr.
103
103
104 Same as getattr, but will return ``default`` on any Exception,
104 Same as getattr, but will return ``default`` on any Exception,
105 rather than raising.
105 rather than raising.
106 """
106 """
107 try:
107 try:
108 return getattr(obj, attr, default)
108 return getattr(obj, attr, default)
109 except Exception:
109 except Exception:
110 return default
110 return default
111
111
112 if PY3:
112 if PY3:
113 CUnicodeIO = StringIO
113 CUnicodeIO = StringIO
114 else:
114 else:
115 class CUnicodeIO(StringIO):
115 class CUnicodeIO(StringIO):
116 """StringIO that casts str to unicode on Python 2"""
116 """StringIO that casts str to unicode on Python 2"""
117 def write(self, text):
117 def write(self, text):
118 return super(CUnicodeIO, self).write(
118 return super(CUnicodeIO, self).write(
119 cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
119 cast_unicode(text, encoding=get_stream_enc(sys.stdout)))
120
120
121
121
122 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
122 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
123 """
123 """
124 Pretty print the object's representation.
124 Pretty print the object's representation.
125 """
125 """
126 stream = CUnicodeIO()
126 stream = CUnicodeIO()
127 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
127 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
128 printer.pretty(obj)
128 printer.pretty(obj)
129 printer.flush()
129 printer.flush()
130 return stream.getvalue()
130 return stream.getvalue()
131
131
132
132
133 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
133 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
134 """
134 """
135 Like `pretty` but print to stdout.
135 Like `pretty` but print to stdout.
136 """
136 """
137 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
137 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
138 printer.pretty(obj)
138 printer.pretty(obj)
139 printer.flush()
139 printer.flush()
140 sys.stdout.write(newline)
140 sys.stdout.write(newline)
141 sys.stdout.flush()
141 sys.stdout.flush()
142
142
143 class _PrettyPrinterBase(object):
143 class _PrettyPrinterBase(object):
144
144
145 @contextmanager
145 @contextmanager
146 def indent(self, indent):
146 def indent(self, indent):
147 """with statement support for indenting/dedenting."""
147 """with statement support for indenting/dedenting."""
148 self.indentation += indent
148 self.indentation += indent
149 try:
149 try:
150 yield
150 yield
151 finally:
151 finally:
152 self.indentation -= indent
152 self.indentation -= indent
153
153
154 @contextmanager
154 @contextmanager
155 def group(self, indent=0, open='', close=''):
155 def group(self, indent=0, open='', close=''):
156 """like begin_group / end_group but for the with statement."""
156 """like begin_group / end_group but for the with statement."""
157 self.begin_group(indent, open)
157 self.begin_group(indent, open)
158 try:
158 try:
159 yield
159 yield
160 finally:
160 finally:
161 self.end_group(indent, close)
161 self.end_group(indent, close)
162
162
163 class PrettyPrinter(_PrettyPrinterBase):
163 class PrettyPrinter(_PrettyPrinterBase):
164 """
164 """
165 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
165 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
166 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
166 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
167 this printer knows nothing about the default pprinters or the `_repr_pretty_`
167 this printer knows nothing about the default pprinters or the `_repr_pretty_`
168 callback method.
168 callback method.
169 """
169 """
170
170
171 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
171 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
172 self.output = output
172 self.output = output
173 self.max_width = max_width
173 self.max_width = max_width
174 self.newline = newline
174 self.newline = newline
175 self.max_seq_length = max_seq_length
175 self.max_seq_length = max_seq_length
176 self.output_width = 0
176 self.output_width = 0
177 self.buffer_width = 0
177 self.buffer_width = 0
178 self.buffer = deque()
178 self.buffer = deque()
179
179
180 root_group = Group(0)
180 root_group = Group(0)
181 self.group_stack = [root_group]
181 self.group_stack = [root_group]
182 self.group_queue = GroupQueue(root_group)
182 self.group_queue = GroupQueue(root_group)
183 self.indentation = 0
183 self.indentation = 0
184
184
185 def _break_outer_groups(self):
185 def _break_outer_groups(self):
186 while self.max_width < self.output_width + self.buffer_width:
186 while self.max_width < self.output_width + self.buffer_width:
187 group = self.group_queue.deq()
187 group = self.group_queue.deq()
188 if not group:
188 if not group:
189 return
189 return
190 while group.breakables:
190 while group.breakables:
191 x = self.buffer.popleft()
191 x = self.buffer.popleft()
192 self.output_width = x.output(self.output, self.output_width)
192 self.output_width = x.output(self.output, self.output_width)
193 self.buffer_width -= x.width
193 self.buffer_width -= x.width
194 while self.buffer and isinstance(self.buffer[0], Text):
194 while self.buffer and isinstance(self.buffer[0], Text):
195 x = self.buffer.popleft()
195 x = self.buffer.popleft()
196 self.output_width = x.output(self.output, self.output_width)
196 self.output_width = x.output(self.output, self.output_width)
197 self.buffer_width -= x.width
197 self.buffer_width -= x.width
198
198
199 def text(self, obj):
199 def text(self, obj):
200 """Add literal text to the output."""
200 """Add literal text to the output."""
201 width = len(obj)
201 width = len(obj)
202 if self.buffer:
202 if self.buffer:
203 text = self.buffer[-1]
203 text = self.buffer[-1]
204 if not isinstance(text, Text):
204 if not isinstance(text, Text):
205 text = Text()
205 text = Text()
206 self.buffer.append(text)
206 self.buffer.append(text)
207 text.add(obj, width)
207 text.add(obj, width)
208 self.buffer_width += width
208 self.buffer_width += width
209 self._break_outer_groups()
209 self._break_outer_groups()
210 else:
210 else:
211 self.output.write(obj)
211 self.output.write(obj)
212 self.output_width += width
212 self.output_width += width
213
213
214 def breakable(self, sep=' '):
214 def breakable(self, sep=' '):
215 """
215 """
216 Add a breakable separator to the output. This does not mean that it
216 Add a breakable separator to the output. This does not mean that it
217 will automatically break here. If no breaking on this position takes
217 will automatically break here. If no breaking on this position takes
218 place the `sep` is inserted which default to one space.
218 place the `sep` is inserted which default to one space.
219 """
219 """
220 width = len(sep)
220 width = len(sep)
221 group = self.group_stack[-1]
221 group = self.group_stack[-1]
222 if group.want_break:
222 if group.want_break:
223 self.flush()
223 self.flush()
224 self.output.write(self.newline)
224 self.output.write(self.newline)
225 self.output.write(' ' * self.indentation)
225 self.output.write(' ' * self.indentation)
226 self.output_width = self.indentation
226 self.output_width = self.indentation
227 self.buffer_width = 0
227 self.buffer_width = 0
228 else:
228 else:
229 self.buffer.append(Breakable(sep, width, self))
229 self.buffer.append(Breakable(sep, width, self))
230 self.buffer_width += width
230 self.buffer_width += width
231 self._break_outer_groups()
231 self._break_outer_groups()
232
232
233 def break_(self):
233 def break_(self):
234 """
234 """
235 Explicitly insert a newline into the output, maintaining correct indentation.
235 Explicitly insert a newline into the output, maintaining correct indentation.
236 """
236 """
237 self.flush()
237 self.flush()
238 self.output.write(self.newline)
238 self.output.write(self.newline)
239 self.output.write(' ' * self.indentation)
239 self.output.write(' ' * self.indentation)
240 self.output_width = self.indentation
240 self.output_width = self.indentation
241 self.buffer_width = 0
241 self.buffer_width = 0
242
242
243
243
244 def begin_group(self, indent=0, open=''):
244 def begin_group(self, indent=0, open=''):
245 """
245 """
246 Begin a group. If you want support for python < 2.5 which doesn't has
246 Begin a group. If you want support for python < 2.5 which doesn't has
247 the with statement this is the preferred way:
247 the with statement this is the preferred way:
248
248
249 p.begin_group(1, '{')
249 p.begin_group(1, '{')
250 ...
250 ...
251 p.end_group(1, '}')
251 p.end_group(1, '}')
252
252
253 The python 2.5 expression would be this:
253 The python 2.5 expression would be this:
254
254
255 with p.group(1, '{', '}'):
255 with p.group(1, '{', '}'):
256 ...
256 ...
257
257
258 The first parameter specifies the indentation for the next line (usually
258 The first parameter specifies the indentation for the next line (usually
259 the width of the opening text), the second the opening text. All
259 the width of the opening text), the second the opening text. All
260 parameters are optional.
260 parameters are optional.
261 """
261 """
262 if open:
262 if open:
263 self.text(open)
263 self.text(open)
264 group = Group(self.group_stack[-1].depth + 1)
264 group = Group(self.group_stack[-1].depth + 1)
265 self.group_stack.append(group)
265 self.group_stack.append(group)
266 self.group_queue.enq(group)
266 self.group_queue.enq(group)
267 self.indentation += indent
267 self.indentation += indent
268
268
269 def _enumerate(self, seq):
269 def _enumerate(self, seq):
270 """like enumerate, but with an upper limit on the number of items"""
270 """like enumerate, but with an upper limit on the number of items"""
271 for idx, x in enumerate(seq):
271 for idx, x in enumerate(seq):
272 if self.max_seq_length and idx >= self.max_seq_length:
272 if self.max_seq_length and idx >= self.max_seq_length:
273 self.text(',')
273 self.text(',')
274 self.breakable()
274 self.breakable()
275 self.text('...')
275 self.text('...')
276 return
276 return
277 yield idx, x
277 yield idx, x
278
278
279 def end_group(self, dedent=0, close=''):
279 def end_group(self, dedent=0, close=''):
280 """End a group. See `begin_group` for more details."""
280 """End a group. See `begin_group` for more details."""
281 self.indentation -= dedent
281 self.indentation -= dedent
282 group = self.group_stack.pop()
282 group = self.group_stack.pop()
283 if not group.breakables:
283 if not group.breakables:
284 self.group_queue.remove(group)
284 self.group_queue.remove(group)
285 if close:
285 if close:
286 self.text(close)
286 self.text(close)
287
287
288 def flush(self):
288 def flush(self):
289 """Flush data that is left in the buffer."""
289 """Flush data that is left in the buffer."""
290 for data in self.buffer:
290 for data in self.buffer:
291 self.output_width += data.output(self.output, self.output_width)
291 self.output_width += data.output(self.output, self.output_width)
292 self.buffer.clear()
292 self.buffer.clear()
293 self.buffer_width = 0
293 self.buffer_width = 0
294
294
295
295
296 def _get_mro(obj_class):
296 def _get_mro(obj_class):
297 """ Get a reasonable method resolution order of a class and its superclasses
297 """ Get a reasonable method resolution order of a class and its superclasses
298 for both old-style and new-style classes.
298 for both old-style and new-style classes.
299 """
299 """
300 if not hasattr(obj_class, '__mro__'):
300 if not hasattr(obj_class, '__mro__'):
301 # Old-style class. Mix in object to make a fake new-style class.
301 # Old-style class. Mix in object to make a fake new-style class.
302 try:
302 try:
303 obj_class = type(obj_class.__name__, (obj_class, object), {})
303 obj_class = type(obj_class.__name__, (obj_class, object), {})
304 except TypeError:
304 except TypeError:
305 # Old-style extension type that does not descend from object.
305 # Old-style extension type that does not descend from object.
306 # FIXME: try to construct a more thorough MRO.
306 # FIXME: try to construct a more thorough MRO.
307 mro = [obj_class]
307 mro = [obj_class]
308 else:
308 else:
309 mro = obj_class.__mro__[1:-1]
309 mro = obj_class.__mro__[1:-1]
310 else:
310 else:
311 mro = obj_class.__mro__
311 mro = obj_class.__mro__
312 return mro
312 return mro
313
313
314
314
315 class RepresentationPrinter(PrettyPrinter):
315 class RepresentationPrinter(PrettyPrinter):
316 """
316 """
317 Special pretty printer that has a `pretty` method that calls the pretty
317 Special pretty printer that has a `pretty` method that calls the pretty
318 printer for a python object.
318 printer for a python object.
319
319
320 This class stores processing data on `self` so you must *never* use
320 This class stores processing data on `self` so you must *never* use
321 this class in a threaded environment. Always lock it or reinstanciate
321 this class in a threaded environment. Always lock it or reinstanciate
322 it.
322 it.
323
323
324 Instances also have a verbose flag callbacks can access to control their
324 Instances also have a verbose flag callbacks can access to control their
325 output. For example the default instance repr prints all attributes and
325 output. For example the default instance repr prints all attributes and
326 methods that are not prefixed by an underscore if the printer is in
326 methods that are not prefixed by an underscore if the printer is in
327 verbose mode.
327 verbose mode.
328 """
328 """
329
329
330 def __init__(self, output, verbose=False, max_width=79, newline='\n',
330 def __init__(self, output, verbose=False, max_width=79, newline='\n',
331 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
331 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
332 max_seq_length=MAX_SEQ_LENGTH):
332 max_seq_length=MAX_SEQ_LENGTH):
333
333
334 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
334 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
335 self.verbose = verbose
335 self.verbose = verbose
336 self.stack = []
336 self.stack = []
337 if singleton_pprinters is None:
337 if singleton_pprinters is None:
338 singleton_pprinters = _singleton_pprinters.copy()
338 singleton_pprinters = _singleton_pprinters.copy()
339 self.singleton_pprinters = singleton_pprinters
339 self.singleton_pprinters = singleton_pprinters
340 if type_pprinters is None:
340 if type_pprinters is None:
341 type_pprinters = _type_pprinters.copy()
341 type_pprinters = _type_pprinters.copy()
342 self.type_pprinters = type_pprinters
342 self.type_pprinters = type_pprinters
343 if deferred_pprinters is None:
343 if deferred_pprinters is None:
344 deferred_pprinters = _deferred_type_pprinters.copy()
344 deferred_pprinters = _deferred_type_pprinters.copy()
345 self.deferred_pprinters = deferred_pprinters
345 self.deferred_pprinters = deferred_pprinters
346
346
347 def pretty(self, obj):
347 def pretty(self, obj):
348 """Pretty print the given object."""
348 """Pretty print the given object."""
349 obj_id = id(obj)
349 obj_id = id(obj)
350 cycle = obj_id in self.stack
350 cycle = obj_id in self.stack
351 self.stack.append(obj_id)
351 self.stack.append(obj_id)
352 self.begin_group()
352 self.begin_group()
353 try:
353 try:
354 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
354 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
355 # First try to find registered singleton printers for the type.
355 # First try to find registered singleton printers for the type.
356 try:
356 try:
357 printer = self.singleton_pprinters[obj_id]
357 printer = self.singleton_pprinters[obj_id]
358 except (TypeError, KeyError):
358 except (TypeError, KeyError):
359 pass
359 pass
360 else:
360 else:
361 return printer(obj, self, cycle)
361 return printer(obj, self, cycle)
362 # Next walk the mro and check for either:
362 # Next walk the mro and check for either:
363 # 1) a registered printer
363 # 1) a registered printer
364 # 2) a _repr_pretty_ method
364 # 2) a _repr_pretty_ method
365 for cls in _get_mro(obj_class):
365 for cls in _get_mro(obj_class):
366 if cls in self.type_pprinters:
366 if cls in self.type_pprinters:
367 # printer registered in self.type_pprinters
367 # printer registered in self.type_pprinters
368 return self.type_pprinters[cls](obj, self, cycle)
368 return self.type_pprinters[cls](obj, self, cycle)
369 else:
369 else:
370 # deferred printer
370 # deferred printer
371 printer = self._in_deferred_types(cls)
371 printer = self._in_deferred_types(cls)
372 if printer is not None:
372 if printer is not None:
373 return printer(obj, self, cycle)
373 return printer(obj, self, cycle)
374 else:
374 else:
375 # Finally look for special method names.
375 # Finally look for special method names.
376 # Some objects automatically create any requested
376 # Some objects automatically create any requested
377 # attribute. Try to ignore most of them by checking for
377 # attribute. Try to ignore most of them by checking for
378 # callability.
378 # callability.
379 if '_repr_pretty_' in cls.__dict__:
379 if '_repr_pretty_' in cls.__dict__:
380 meth = cls._repr_pretty_
380 meth = cls._repr_pretty_
381 if callable(meth):
381 if callable(meth):
382 return meth(obj, self, cycle)
382 return meth(obj, self, cycle)
383 return _default_pprint(obj, self, cycle)
383 return _default_pprint(obj, self, cycle)
384 finally:
384 finally:
385 self.end_group()
385 self.end_group()
386 self.stack.pop()
386 self.stack.pop()
387
387
388 def _in_deferred_types(self, cls):
388 def _in_deferred_types(self, cls):
389 """
389 """
390 Check if the given class is specified in the deferred type registry.
390 Check if the given class is specified in the deferred type registry.
391
391
392 Returns the printer from the registry if it exists, and None if the
392 Returns the printer from the registry if it exists, and None if the
393 class is not in the registry. Successful matches will be moved to the
393 class is not in the registry. Successful matches will be moved to the
394 regular type registry for future use.
394 regular type registry for future use.
395 """
395 """
396 mod = _safe_getattr(cls, '__module__', None)
396 mod = _safe_getattr(cls, '__module__', None)
397 name = _safe_getattr(cls, '__name__', None)
397 name = _safe_getattr(cls, '__name__', None)
398 key = (mod, name)
398 key = (mod, name)
399 printer = None
399 printer = None
400 if key in self.deferred_pprinters:
400 if key in self.deferred_pprinters:
401 # Move the printer over to the regular registry.
401 # Move the printer over to the regular registry.
402 printer = self.deferred_pprinters.pop(key)
402 printer = self.deferred_pprinters.pop(key)
403 self.type_pprinters[cls] = printer
403 self.type_pprinters[cls] = printer
404 return printer
404 return printer
405
405
406
406
407 class Printable(object):
407 class Printable(object):
408
408
409 def output(self, stream, output_width):
409 def output(self, stream, output_width):
410 return output_width
410 return output_width
411
411
412
412
413 class Text(Printable):
413 class Text(Printable):
414
414
415 def __init__(self):
415 def __init__(self):
416 self.objs = []
416 self.objs = []
417 self.width = 0
417 self.width = 0
418
418
419 def output(self, stream, output_width):
419 def output(self, stream, output_width):
420 for obj in self.objs:
420 for obj in self.objs:
421 stream.write(obj)
421 stream.write(obj)
422 return output_width + self.width
422 return output_width + self.width
423
423
424 def add(self, obj, width):
424 def add(self, obj, width):
425 self.objs.append(obj)
425 self.objs.append(obj)
426 self.width += width
426 self.width += width
427
427
428
428
429 class Breakable(Printable):
429 class Breakable(Printable):
430
430
431 def __init__(self, seq, width, pretty):
431 def __init__(self, seq, width, pretty):
432 self.obj = seq
432 self.obj = seq
433 self.width = width
433 self.width = width
434 self.pretty = pretty
434 self.pretty = pretty
435 self.indentation = pretty.indentation
435 self.indentation = pretty.indentation
436 self.group = pretty.group_stack[-1]
436 self.group = pretty.group_stack[-1]
437 self.group.breakables.append(self)
437 self.group.breakables.append(self)
438
438
439 def output(self, stream, output_width):
439 def output(self, stream, output_width):
440 self.group.breakables.popleft()
440 self.group.breakables.popleft()
441 if self.group.want_break:
441 if self.group.want_break:
442 stream.write(self.pretty.newline)
442 stream.write(self.pretty.newline)
443 stream.write(' ' * self.indentation)
443 stream.write(' ' * self.indentation)
444 return self.indentation
444 return self.indentation
445 if not self.group.breakables:
445 if not self.group.breakables:
446 self.pretty.group_queue.remove(self.group)
446 self.pretty.group_queue.remove(self.group)
447 stream.write(self.obj)
447 stream.write(self.obj)
448 return output_width + self.width
448 return output_width + self.width
449
449
450
450
451 class Group(Printable):
451 class Group(Printable):
452
452
453 def __init__(self, depth):
453 def __init__(self, depth):
454 self.depth = depth
454 self.depth = depth
455 self.breakables = deque()
455 self.breakables = deque()
456 self.want_break = False
456 self.want_break = False
457
457
458
458
459 class GroupQueue(object):
459 class GroupQueue(object):
460
460
461 def __init__(self, *groups):
461 def __init__(self, *groups):
462 self.queue = []
462 self.queue = []
463 for group in groups:
463 for group in groups:
464 self.enq(group)
464 self.enq(group)
465
465
466 def enq(self, group):
466 def enq(self, group):
467 depth = group.depth
467 depth = group.depth
468 while depth > len(self.queue) - 1:
468 while depth > len(self.queue) - 1:
469 self.queue.append([])
469 self.queue.append([])
470 self.queue[depth].append(group)
470 self.queue[depth].append(group)
471
471
472 def deq(self):
472 def deq(self):
473 for stack in self.queue:
473 for stack in self.queue:
474 for idx, group in enumerate(reversed(stack)):
474 for idx, group in enumerate(reversed(stack)):
475 if group.breakables:
475 if group.breakables:
476 del stack[idx]
476 del stack[idx]
477 group.want_break = True
477 group.want_break = True
478 return group
478 return group
479 for group in stack:
479 for group in stack:
480 group.want_break = True
480 group.want_break = True
481 del stack[:]
481 del stack[:]
482
482
483 def remove(self, group):
483 def remove(self, group):
484 try:
484 try:
485 self.queue[group.depth].remove(group)
485 self.queue[group.depth].remove(group)
486 except ValueError:
486 except ValueError:
487 pass
487 pass
488
488
489 try:
489 try:
490 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
490 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
491 except AttributeError: # Python 3
491 except AttributeError: # Python 3
492 _baseclass_reprs = (object.__repr__,)
492 _baseclass_reprs = (object.__repr__,)
493
493
494
494
495 def _default_pprint(obj, p, cycle):
495 def _default_pprint(obj, p, cycle):
496 """
496 """
497 The default print function. Used if an object does not provide one and
497 The default print function. Used if an object does not provide one and
498 it's none of the builtin objects.
498 it's none of the builtin objects.
499 """
499 """
500 klass = _safe_getattr(obj, '__class__', None) or type(obj)
500 klass = _safe_getattr(obj, '__class__', None) or type(obj)
501 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
501 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
502 # A user-provided repr. Find newlines and replace them with p.break_()
502 # A user-provided repr. Find newlines and replace them with p.break_()
503 _repr_pprint(obj, p, cycle)
503 _repr_pprint(obj, p, cycle)
504 return
504 return
505 p.begin_group(1, '<')
505 p.begin_group(1, '<')
506 p.pretty(klass)
506 p.pretty(klass)
507 p.text(' at 0x%x' % id(obj))
507 p.text(' at 0x%x' % id(obj))
508 if cycle:
508 if cycle:
509 p.text(' ...')
509 p.text(' ...')
510 elif p.verbose:
510 elif p.verbose:
511 first = True
511 first = True
512 for key in dir(obj):
512 for key in dir(obj):
513 if not key.startswith('_'):
513 if not key.startswith('_'):
514 try:
514 try:
515 value = getattr(obj, key)
515 value = getattr(obj, key)
516 except AttributeError:
516 except AttributeError:
517 continue
517 continue
518 if isinstance(value, types.MethodType):
518 if isinstance(value, types.MethodType):
519 continue
519 continue
520 if not first:
520 if not first:
521 p.text(',')
521 p.text(',')
522 p.breakable()
522 p.breakable()
523 p.text(key)
523 p.text(key)
524 p.text('=')
524 p.text('=')
525 step = len(key) + 1
525 step = len(key) + 1
526 p.indentation += step
526 p.indentation += step
527 p.pretty(value)
527 p.pretty(value)
528 p.indentation -= step
528 p.indentation -= step
529 first = False
529 first = False
530 p.end_group(1, '>')
530 p.end_group(1, '>')
531
531
532
532
533 def _seq_pprinter_factory(start, end, basetype):
533 def _seq_pprinter_factory(start, end, basetype):
534 """
534 """
535 Factory that returns a pprint function useful for sequences. Used by
535 Factory that returns a pprint function useful for sequences. Used by
536 the default pprint for tuples, dicts, and lists.
536 the default pprint for tuples, dicts, and lists.
537 """
537 """
538 def inner(obj, p, cycle):
538 def inner(obj, p, cycle):
539 typ = type(obj)
539 typ = type(obj)
540 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
540 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
541 # If the subclass provides its own repr, use it instead.
541 # If the subclass provides its own repr, use it instead.
542 return p.text(typ.__repr__(obj))
542 return p.text(typ.__repr__(obj))
543
543
544 if cycle:
544 if cycle:
545 return p.text(start + '...' + end)
545 return p.text(start + '...' + end)
546 step = len(start)
546 step = len(start)
547 p.begin_group(step, start)
547 p.begin_group(step, start)
548 for idx, x in p._enumerate(obj):
548 for idx, x in p._enumerate(obj):
549 if idx:
549 if idx:
550 p.text(',')
550 p.text(',')
551 p.breakable()
551 p.breakable()
552 p.pretty(x)
552 p.pretty(x)
553 if len(obj) == 1 and type(obj) is tuple:
553 if len(obj) == 1 and type(obj) is tuple:
554 # Special case for 1-item tuples.
554 # Special case for 1-item tuples.
555 p.text(',')
555 p.text(',')
556 p.end_group(step, end)
556 p.end_group(step, end)
557 return inner
557 return inner
558
558
559
559
560 def _set_pprinter_factory(start, end, basetype):
560 def _set_pprinter_factory(start, end, basetype):
561 """
561 """
562 Factory that returns a pprint function useful for sets and frozensets.
562 Factory that returns a pprint function useful for sets and frozensets.
563 """
563 """
564 def inner(obj, p, cycle):
564 def inner(obj, p, cycle):
565 typ = type(obj)
565 typ = type(obj)
566 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
566 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
567 # If the subclass provides its own repr, use it instead.
567 # If the subclass provides its own repr, use it instead.
568 return p.text(typ.__repr__(obj))
568 return p.text(typ.__repr__(obj))
569
569
570 if cycle:
570 if cycle:
571 return p.text(start + '...' + end)
571 return p.text(start + '...' + end)
572 if len(obj) == 0:
572 if len(obj) == 0:
573 # Special case.
573 # Special case.
574 p.text(basetype.__name__ + '()')
574 p.text(basetype.__name__ + '()')
575 else:
575 else:
576 step = len(start)
576 step = len(start)
577 p.begin_group(step, start)
577 p.begin_group(step, start)
578 # Like dictionary keys, we will try to sort the items if there aren't too many
578 # Like dictionary keys, we will try to sort the items if there aren't too many
579 items = obj
579 items = obj
580 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
580 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
581 try:
581 try:
582 items = sorted(obj)
582 items = sorted(obj)
583 except Exception:
583 except Exception:
584 # Sometimes the items don't sort.
584 # Sometimes the items don't sort.
585 pass
585 pass
586 for idx, x in p._enumerate(items):
586 for idx, x in p._enumerate(items):
587 if idx:
587 if idx:
588 p.text(',')
588 p.text(',')
589 p.breakable()
589 p.breakable()
590 p.pretty(x)
590 p.pretty(x)
591 p.end_group(step, end)
591 p.end_group(step, end)
592 return inner
592 return inner
593
593
594
594
595 def _dict_pprinter_factory(start, end, basetype=None):
595 def _dict_pprinter_factory(start, end, basetype=None):
596 """
596 """
597 Factory that returns a pprint function used by the default pprint of
597 Factory that returns a pprint function used by the default pprint of
598 dicts and dict proxies.
598 dicts and dict proxies.
599 """
599 """
600 def inner(obj, p, cycle):
600 def inner(obj, p, cycle):
601 typ = type(obj)
601 typ = type(obj)
602 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
602 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
603 # If the subclass provides its own repr, use it instead.
603 # If the subclass provides its own repr, use it instead.
604 return p.text(typ.__repr__(obj))
604 return p.text(typ.__repr__(obj))
605
605
606 if cycle:
606 if cycle:
607 return p.text('{...}')
607 return p.text('{...}')
608 p.begin_group(1, start)
608 step = len(start)
609 p.begin_group(step, start)
609 keys = obj.keys()
610 keys = obj.keys()
610 # if dict isn't large enough to be truncated, sort keys before displaying
611 # if dict isn't large enough to be truncated, sort keys before displaying
611 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
612 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
612 try:
613 try:
613 keys = sorted(keys)
614 keys = sorted(keys)
614 except Exception:
615 except Exception:
615 # Sometimes the keys don't sort.
616 # Sometimes the keys don't sort.
616 pass
617 pass
617 for idx, key in p._enumerate(keys):
618 for idx, key in p._enumerate(keys):
618 if idx:
619 if idx:
619 p.text(',')
620 p.text(',')
620 p.breakable()
621 p.breakable()
621 p.pretty(key)
622 p.pretty(key)
622 p.text(': ')
623 p.text(': ')
623 p.pretty(obj[key])
624 p.pretty(obj[key])
624 p.end_group(1, end)
625 p.end_group(step, end)
625 return inner
626 return inner
626
627
627
628
628 def _super_pprint(obj, p, cycle):
629 def _super_pprint(obj, p, cycle):
629 """The pprint for the super type."""
630 """The pprint for the super type."""
630 p.begin_group(8, '<super: ')
631 p.begin_group(8, '<super: ')
631 p.pretty(obj.__thisclass__)
632 p.pretty(obj.__thisclass__)
632 p.text(',')
633 p.text(',')
633 p.breakable()
634 p.breakable()
634 p.pretty(obj.__self__)
635 if PYPY: # In PyPy, super() objects don't have __self__ attributes
636 dself = obj.__repr__.__self__
637 p.pretty(None if dself is obj else dself)
638 else:
639 p.pretty(obj.__self__)
635 p.end_group(8, '>')
640 p.end_group(8, '>')
636
641
637
642
638 def _re_pattern_pprint(obj, p, cycle):
643 def _re_pattern_pprint(obj, p, cycle):
639 """The pprint function for regular expression patterns."""
644 """The pprint function for regular expression patterns."""
640 p.text('re.compile(')
645 p.text('re.compile(')
641 pattern = repr(obj.pattern)
646 pattern = repr(obj.pattern)
642 if pattern[:1] in 'uU':
647 if pattern[:1] in 'uU':
643 pattern = pattern[1:]
648 pattern = pattern[1:]
644 prefix = 'ur'
649 prefix = 'ur'
645 else:
650 else:
646 prefix = 'r'
651 prefix = 'r'
647 pattern = prefix + pattern.replace('\\\\', '\\')
652 pattern = prefix + pattern.replace('\\\\', '\\')
648 p.text(pattern)
653 p.text(pattern)
649 if obj.flags:
654 if obj.flags:
650 p.text(',')
655 p.text(',')
651 p.breakable()
656 p.breakable()
652 done_one = False
657 done_one = False
653 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
658 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
654 'UNICODE', 'VERBOSE', 'DEBUG'):
659 'UNICODE', 'VERBOSE', 'DEBUG'):
655 if obj.flags & getattr(re, flag):
660 if obj.flags & getattr(re, flag):
656 if done_one:
661 if done_one:
657 p.text('|')
662 p.text('|')
658 p.text('re.' + flag)
663 p.text('re.' + flag)
659 done_one = True
664 done_one = True
660 p.text(')')
665 p.text(')')
661
666
662
667
663 def _type_pprint(obj, p, cycle):
668 def _type_pprint(obj, p, cycle):
664 """The pprint for classes and types."""
669 """The pprint for classes and types."""
665 # Heap allocated types might not have the module attribute,
670 # Heap allocated types might not have the module attribute,
666 # and others may set it to None.
671 # and others may set it to None.
667
672
668 # Checks for a __repr__ override in the metaclass
673 # Checks for a __repr__ override in the metaclass. Can't compare the
669 if type(obj).__repr__ is not type.__repr__:
674 # type(obj).__repr__ directly because in PyPy the representation function
675 # inherited from type isn't the same type.__repr__
676 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
670 _repr_pprint(obj, p, cycle)
677 _repr_pprint(obj, p, cycle)
671 return
678 return
672
679
673 mod = _safe_getattr(obj, '__module__', None)
680 mod = _safe_getattr(obj, '__module__', None)
674 try:
681 try:
675 name = obj.__qualname__
682 name = obj.__qualname__
676 if not isinstance(name, string_types):
683 if not isinstance(name, string_types):
677 # This can happen if the type implements __qualname__ as a property
684 # This can happen if the type implements __qualname__ as a property
678 # or other descriptor in Python 2.
685 # or other descriptor in Python 2.
679 raise Exception("Try __name__")
686 raise Exception("Try __name__")
680 except Exception:
687 except Exception:
681 name = obj.__name__
688 name = obj.__name__
682 if not isinstance(name, string_types):
689 if not isinstance(name, string_types):
683 name = '<unknown type>'
690 name = '<unknown type>'
684
691
685 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
692 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
686 p.text(name)
693 p.text(name)
687 else:
694 else:
688 p.text(mod + '.' + name)
695 p.text(mod + '.' + name)
689
696
690
697
691 def _repr_pprint(obj, p, cycle):
698 def _repr_pprint(obj, p, cycle):
692 """A pprint that just redirects to the normal repr function."""
699 """A pprint that just redirects to the normal repr function."""
693 # Find newlines and replace them with p.break_()
700 # Find newlines and replace them with p.break_()
694 output = repr(obj)
701 output = repr(obj)
695 for idx,output_line in enumerate(output.splitlines()):
702 for idx,output_line in enumerate(output.splitlines()):
696 if idx:
703 if idx:
697 p.break_()
704 p.break_()
698 p.text(output_line)
705 p.text(output_line)
699
706
700
707
701 def _function_pprint(obj, p, cycle):
708 def _function_pprint(obj, p, cycle):
702 """Base pprint for all functions and builtin functions."""
709 """Base pprint for all functions and builtin functions."""
703 name = _safe_getattr(obj, '__qualname__', obj.__name__)
710 name = _safe_getattr(obj, '__qualname__', obj.__name__)
704 mod = obj.__module__
711 mod = obj.__module__
705 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
712 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
706 name = mod + '.' + name
713 name = mod + '.' + name
707 p.text('<function %s>' % name)
714 p.text('<function %s>' % name)
708
715
709
716
710 def _exception_pprint(obj, p, cycle):
717 def _exception_pprint(obj, p, cycle):
711 """Base pprint for all exceptions."""
718 """Base pprint for all exceptions."""
712 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
719 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
713 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
720 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
714 name = '%s.%s' % (obj.__class__.__module__, name)
721 name = '%s.%s' % (obj.__class__.__module__, name)
715 step = len(name) + 1
722 step = len(name) + 1
716 p.begin_group(step, name + '(')
723 p.begin_group(step, name + '(')
717 for idx, arg in enumerate(getattr(obj, 'args', ())):
724 for idx, arg in enumerate(getattr(obj, 'args', ())):
718 if idx:
725 if idx:
719 p.text(',')
726 p.text(',')
720 p.breakable()
727 p.breakable()
721 p.pretty(arg)
728 p.pretty(arg)
722 p.end_group(step, ')')
729 p.end_group(step, ')')
723
730
724
731
725 #: the exception base
732 #: the exception base
726 try:
733 try:
727 _exception_base = BaseException
734 _exception_base = BaseException
728 except NameError:
735 except NameError:
729 _exception_base = Exception
736 _exception_base = Exception
730
737
731
738
732 #: printers for builtin types
739 #: printers for builtin types
733 _type_pprinters = {
740 _type_pprinters = {
734 int: _repr_pprint,
741 int: _repr_pprint,
735 float: _repr_pprint,
742 float: _repr_pprint,
736 str: _repr_pprint,
743 str: _repr_pprint,
737 tuple: _seq_pprinter_factory('(', ')', tuple),
744 tuple: _seq_pprinter_factory('(', ')', tuple),
738 list: _seq_pprinter_factory('[', ']', list),
745 list: _seq_pprinter_factory('[', ']', list),
739 dict: _dict_pprinter_factory('{', '}', dict),
746 dict: _dict_pprinter_factory('{', '}', dict),
740
747
741 set: _set_pprinter_factory('{', '}', set),
748 set: _set_pprinter_factory('{', '}', set),
742 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
749 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
743 super: _super_pprint,
750 super: _super_pprint,
744 _re_pattern_type: _re_pattern_pprint,
751 _re_pattern_type: _re_pattern_pprint,
745 type: _type_pprint,
752 type: _type_pprint,
746 types.FunctionType: _function_pprint,
753 types.FunctionType: _function_pprint,
747 types.BuiltinFunctionType: _function_pprint,
754 types.BuiltinFunctionType: _function_pprint,
748 types.MethodType: _repr_pprint,
755 types.MethodType: _repr_pprint,
749
756
750 datetime.datetime: _repr_pprint,
757 datetime.datetime: _repr_pprint,
751 datetime.timedelta: _repr_pprint,
758 datetime.timedelta: _repr_pprint,
752 _exception_base: _exception_pprint
759 _exception_base: _exception_pprint
753 }
760 }
754
761
755 try:
762 try:
756 _type_pprinters[types.DictProxyType] = _dict_pprinter_factory('<dictproxy {', '}>')
763 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
764 # using dict.setdefault avoids overwritting the dict printer
765 _type_pprinters.setdefault(types.DictProxyType,
766 _dict_pprinter_factory('dict_proxy({', '})'))
757 _type_pprinters[types.ClassType] = _type_pprint
767 _type_pprinters[types.ClassType] = _type_pprint
758 _type_pprinters[types.SliceType] = _repr_pprint
768 _type_pprinters[types.SliceType] = _repr_pprint
759 except AttributeError: # Python 3
769 except AttributeError: # Python 3
770 _type_pprinters[types.MappingProxyType] = \
771 _dict_pprinter_factory('mappingproxy({', '})')
760 _type_pprinters[slice] = _repr_pprint
772 _type_pprinters[slice] = _repr_pprint
761
773
762 try:
774 try:
763 _type_pprinters[xrange] = _repr_pprint
775 _type_pprinters[xrange] = _repr_pprint
764 _type_pprinters[long] = _repr_pprint
776 _type_pprinters[long] = _repr_pprint
765 _type_pprinters[unicode] = _repr_pprint
777 _type_pprinters[unicode] = _repr_pprint
766 except NameError:
778 except NameError:
767 _type_pprinters[range] = _repr_pprint
779 _type_pprinters[range] = _repr_pprint
768 _type_pprinters[bytes] = _repr_pprint
780 _type_pprinters[bytes] = _repr_pprint
769
781
770 #: printers for types specified by name
782 #: printers for types specified by name
771 _deferred_type_pprinters = {
783 _deferred_type_pprinters = {
772 }
784 }
773
785
774 def for_type(typ, func):
786 def for_type(typ, func):
775 """
787 """
776 Add a pretty printer for a given type.
788 Add a pretty printer for a given type.
777 """
789 """
778 oldfunc = _type_pprinters.get(typ, None)
790 oldfunc = _type_pprinters.get(typ, None)
779 if func is not None:
791 if func is not None:
780 # To support easy restoration of old pprinters, we need to ignore Nones.
792 # To support easy restoration of old pprinters, we need to ignore Nones.
781 _type_pprinters[typ] = func
793 _type_pprinters[typ] = func
782 return oldfunc
794 return oldfunc
783
795
784 def for_type_by_name(type_module, type_name, func):
796 def for_type_by_name(type_module, type_name, func):
785 """
797 """
786 Add a pretty printer for a type specified by the module and name of a type
798 Add a pretty printer for a type specified by the module and name of a type
787 rather than the type object itself.
799 rather than the type object itself.
788 """
800 """
789 key = (type_module, type_name)
801 key = (type_module, type_name)
790 oldfunc = _deferred_type_pprinters.get(key, None)
802 oldfunc = _deferred_type_pprinters.get(key, None)
791 if func is not None:
803 if func is not None:
792 # To support easy restoration of old pprinters, we need to ignore Nones.
804 # To support easy restoration of old pprinters, we need to ignore Nones.
793 _deferred_type_pprinters[key] = func
805 _deferred_type_pprinters[key] = func
794 return oldfunc
806 return oldfunc
795
807
796
808
797 #: printers for the default singletons
809 #: printers for the default singletons
798 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
810 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
799 NotImplemented]), _repr_pprint)
811 NotImplemented]), _repr_pprint)
800
812
801
813
802 def _defaultdict_pprint(obj, p, cycle):
814 def _defaultdict_pprint(obj, p, cycle):
803 name = obj.__class__.__name__
815 name = obj.__class__.__name__
804 with p.group(len(name) + 1, name + '(', ')'):
816 with p.group(len(name) + 1, name + '(', ')'):
805 if cycle:
817 if cycle:
806 p.text('...')
818 p.text('...')
807 else:
819 else:
808 p.pretty(obj.default_factory)
820 p.pretty(obj.default_factory)
809 p.text(',')
821 p.text(',')
810 p.breakable()
822 p.breakable()
811 p.pretty(dict(obj))
823 p.pretty(dict(obj))
812
824
813 def _ordereddict_pprint(obj, p, cycle):
825 def _ordereddict_pprint(obj, p, cycle):
814 name = obj.__class__.__name__
826 name = obj.__class__.__name__
815 with p.group(len(name) + 1, name + '(', ')'):
827 with p.group(len(name) + 1, name + '(', ')'):
816 if cycle:
828 if cycle:
817 p.text('...')
829 p.text('...')
818 elif len(obj):
830 elif len(obj):
819 p.pretty(list(obj.items()))
831 p.pretty(list(obj.items()))
820
832
821 def _deque_pprint(obj, p, cycle):
833 def _deque_pprint(obj, p, cycle):
822 name = obj.__class__.__name__
834 name = obj.__class__.__name__
823 with p.group(len(name) + 1, name + '(', ')'):
835 with p.group(len(name) + 1, name + '(', ')'):
824 if cycle:
836 if cycle:
825 p.text('...')
837 p.text('...')
826 else:
838 else:
827 p.pretty(list(obj))
839 p.pretty(list(obj))
828
840
829
841
830 def _counter_pprint(obj, p, cycle):
842 def _counter_pprint(obj, p, cycle):
831 name = obj.__class__.__name__
843 name = obj.__class__.__name__
832 with p.group(len(name) + 1, name + '(', ')'):
844 with p.group(len(name) + 1, name + '(', ')'):
833 if cycle:
845 if cycle:
834 p.text('...')
846 p.text('...')
835 elif len(obj):
847 elif len(obj):
836 p.pretty(dict(obj))
848 p.pretty(dict(obj))
837
849
838 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
850 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
839 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
851 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
840 for_type_by_name('collections', 'deque', _deque_pprint)
852 for_type_by_name('collections', 'deque', _deque_pprint)
841 for_type_by_name('collections', 'Counter', _counter_pprint)
853 for_type_by_name('collections', 'Counter', _counter_pprint)
842
854
843 if __name__ == '__main__':
855 if __name__ == '__main__':
844 from random import randrange
856 from random import randrange
845 class Foo(object):
857 class Foo(object):
846 def __init__(self):
858 def __init__(self):
847 self.foo = 1
859 self.foo = 1
848 self.bar = re.compile(r'\s+')
860 self.bar = re.compile(r'\s+')
849 self.blub = dict.fromkeys(range(30), randrange(1, 40))
861 self.blub = dict.fromkeys(range(30), randrange(1, 40))
850 self.hehe = 23424.234234
862 self.hehe = 23424.234234
851 self.list = ["blub", "blah", self]
863 self.list = ["blub", "blah", self]
852
864
853 def get_foo(self):
865 def get_foo(self):
854 print("foo")
866 print("foo")
855
867
856 pprint(Foo(), verbose=True)
868 pprint(Foo(), verbose=True)
@@ -1,438 +1,536 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 from collections import Counter, defaultdict, deque, OrderedDict
9 from collections import Counter, defaultdict, deque, OrderedDict
10 import types, string, ctypes
10
11
11 import nose.tools as nt
12 import nose.tools as nt
12
13
13 from IPython.lib import pretty
14 from IPython.lib import pretty
14 from IPython.testing.decorators import skip_without, py2_only
15 from IPython.testing.decorators import (skip_without, py2_only, py3_only,
16 cpython2_only)
15 from IPython.utils.py3compat import PY3, unicode_to_str
17 from IPython.utils.py3compat import PY3, unicode_to_str
16
18
17 if PY3:
19 if PY3:
18 from io import StringIO
20 from io import StringIO
19 else:
21 else:
20 from StringIO import StringIO
22 from StringIO import StringIO
21
23
22
24
23 class MyList(object):
25 class MyList(object):
24 def __init__(self, content):
26 def __init__(self, content):
25 self.content = content
27 self.content = content
26 def _repr_pretty_(self, p, cycle):
28 def _repr_pretty_(self, p, cycle):
27 if cycle:
29 if cycle:
28 p.text("MyList(...)")
30 p.text("MyList(...)")
29 else:
31 else:
30 with p.group(3, "MyList(", ")"):
32 with p.group(3, "MyList(", ")"):
31 for (i, child) in enumerate(self.content):
33 for (i, child) in enumerate(self.content):
32 if i:
34 if i:
33 p.text(",")
35 p.text(",")
34 p.breakable()
36 p.breakable()
35 else:
37 else:
36 p.breakable("")
38 p.breakable("")
37 p.pretty(child)
39 p.pretty(child)
38
40
39
41
40 class MyDict(dict):
42 class MyDict(dict):
41 def _repr_pretty_(self, p, cycle):
43 def _repr_pretty_(self, p, cycle):
42 p.text("MyDict(...)")
44 p.text("MyDict(...)")
43
45
44 class MyObj(object):
46 class MyObj(object):
45 def somemethod(self):
47 def somemethod(self):
46 pass
48 pass
47
49
48
50
49 class Dummy1(object):
51 class Dummy1(object):
50 def _repr_pretty_(self, p, cycle):
52 def _repr_pretty_(self, p, cycle):
51 p.text("Dummy1(...)")
53 p.text("Dummy1(...)")
52
54
53 class Dummy2(Dummy1):
55 class Dummy2(Dummy1):
54 _repr_pretty_ = None
56 _repr_pretty_ = None
55
57
56 class NoModule(object):
58 class NoModule(object):
57 pass
59 pass
58
60
59 NoModule.__module__ = None
61 NoModule.__module__ = None
60
62
61 class Breaking(object):
63 class Breaking(object):
62 def _repr_pretty_(self, p, cycle):
64 def _repr_pretty_(self, p, cycle):
63 with p.group(4,"TG: ",":"):
65 with p.group(4,"TG: ",":"):
64 p.text("Breaking(")
66 p.text("Breaking(")
65 p.break_()
67 p.break_()
66 p.text(")")
68 p.text(")")
67
69
68 class BreakingRepr(object):
70 class BreakingRepr(object):
69 def __repr__(self):
71 def __repr__(self):
70 return "Breaking(\n)"
72 return "Breaking(\n)"
71
73
72 class BreakingReprParent(object):
74 class BreakingReprParent(object):
73 def _repr_pretty_(self, p, cycle):
75 def _repr_pretty_(self, p, cycle):
74 with p.group(4,"TG: ",":"):
76 with p.group(4,"TG: ",":"):
75 p.pretty(BreakingRepr())
77 p.pretty(BreakingRepr())
76
78
77 class BadRepr(object):
79 class BadRepr(object):
78
80
79 def __repr__(self):
81 def __repr__(self):
80 return 1/0
82 return 1/0
81
83
82
84
83 def test_indentation():
85 def test_indentation():
84 """Test correct indentation in groups"""
86 """Test correct indentation in groups"""
85 count = 40
87 count = 40
86 gotoutput = pretty.pretty(MyList(range(count)))
88 gotoutput = pretty.pretty(MyList(range(count)))
87 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
89 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
88
90
89 nt.assert_equal(gotoutput, expectedoutput)
91 nt.assert_equal(gotoutput, expectedoutput)
90
92
91
93
92 def test_dispatch():
94 def test_dispatch():
93 """
95 """
94 Test correct dispatching: The _repr_pretty_ method for MyDict
96 Test correct dispatching: The _repr_pretty_ method for MyDict
95 must be found before the registered printer for dict.
97 must be found before the registered printer for dict.
96 """
98 """
97 gotoutput = pretty.pretty(MyDict())
99 gotoutput = pretty.pretty(MyDict())
98 expectedoutput = "MyDict(...)"
100 expectedoutput = "MyDict(...)"
99
101
100 nt.assert_equal(gotoutput, expectedoutput)
102 nt.assert_equal(gotoutput, expectedoutput)
101
103
102
104
103 def test_callability_checking():
105 def test_callability_checking():
104 """
106 """
105 Test that the _repr_pretty_ method is tested for callability and skipped if
107 Test that the _repr_pretty_ method is tested for callability and skipped if
106 not.
108 not.
107 """
109 """
108 gotoutput = pretty.pretty(Dummy2())
110 gotoutput = pretty.pretty(Dummy2())
109 expectedoutput = "Dummy1(...)"
111 expectedoutput = "Dummy1(...)"
110
112
111 nt.assert_equal(gotoutput, expectedoutput)
113 nt.assert_equal(gotoutput, expectedoutput)
112
114
113
115
114 def test_sets():
116 def test_sets():
115 """
117 """
116 Test that set and frozenset use Python 3 formatting.
118 Test that set and frozenset use Python 3 formatting.
117 """
119 """
118 objects = [set(), frozenset(), set([1]), frozenset([1]), set([1, 2]),
120 objects = [set(), frozenset(), set([1]), frozenset([1]), set([1, 2]),
119 frozenset([1, 2]), set([-1, -2, -3])]
121 frozenset([1, 2]), set([-1, -2, -3])]
120 expected = ['set()', 'frozenset()', '{1}', 'frozenset({1})', '{1, 2}',
122 expected = ['set()', 'frozenset()', '{1}', 'frozenset({1})', '{1, 2}',
121 'frozenset({1, 2})', '{-3, -2, -1}']
123 'frozenset({1, 2})', '{-3, -2, -1}']
122 for obj, expected_output in zip(objects, expected):
124 for obj, expected_output in zip(objects, expected):
123 got_output = pretty.pretty(obj)
125 got_output = pretty.pretty(obj)
124 yield nt.assert_equal, got_output, expected_output
126 yield nt.assert_equal, got_output, expected_output
125
127
126
128
127 @skip_without('xxlimited')
129 @skip_without('xxlimited')
128 def test_pprint_heap_allocated_type():
130 def test_pprint_heap_allocated_type():
129 """
131 """
130 Test that pprint works for heap allocated types.
132 Test that pprint works for heap allocated types.
131 """
133 """
132 import xxlimited
134 import xxlimited
133 output = pretty.pretty(xxlimited.Null)
135 output = pretty.pretty(xxlimited.Null)
134 nt.assert_equal(output, 'xxlimited.Null')
136 nt.assert_equal(output, 'xxlimited.Null')
135
137
136 def test_pprint_nomod():
138 def test_pprint_nomod():
137 """
139 """
138 Test that pprint works for classes with no __module__.
140 Test that pprint works for classes with no __module__.
139 """
141 """
140 output = pretty.pretty(NoModule)
142 output = pretty.pretty(NoModule)
141 nt.assert_equal(output, 'NoModule')
143 nt.assert_equal(output, 'NoModule')
142
144
143 def test_pprint_break():
145 def test_pprint_break():
144 """
146 """
145 Test that p.break_ produces expected output
147 Test that p.break_ produces expected output
146 """
148 """
147 output = pretty.pretty(Breaking())
149 output = pretty.pretty(Breaking())
148 expected = "TG: Breaking(\n ):"
150 expected = "TG: Breaking(\n ):"
149 nt.assert_equal(output, expected)
151 nt.assert_equal(output, expected)
150
152
151 def test_pprint_break_repr():
153 def test_pprint_break_repr():
152 """
154 """
153 Test that p.break_ is used in repr
155 Test that p.break_ is used in repr
154 """
156 """
155 output = pretty.pretty(BreakingReprParent())
157 output = pretty.pretty(BreakingReprParent())
156 expected = "TG: Breaking(\n ):"
158 expected = "TG: Breaking(\n ):"
157 nt.assert_equal(output, expected)
159 nt.assert_equal(output, expected)
158
160
159 def test_bad_repr():
161 def test_bad_repr():
160 """Don't catch bad repr errors"""
162 """Don't catch bad repr errors"""
161 with nt.assert_raises(ZeroDivisionError):
163 with nt.assert_raises(ZeroDivisionError):
162 output = pretty.pretty(BadRepr())
164 output = pretty.pretty(BadRepr())
163
165
164 class BadException(Exception):
166 class BadException(Exception):
165 def __str__(self):
167 def __str__(self):
166 return -1
168 return -1
167
169
168 class ReallyBadRepr(object):
170 class ReallyBadRepr(object):
169 __module__ = 1
171 __module__ = 1
170 @property
172 @property
171 def __class__(self):
173 def __class__(self):
172 raise ValueError("I am horrible")
174 raise ValueError("I am horrible")
173
175
174 def __repr__(self):
176 def __repr__(self):
175 raise BadException()
177 raise BadException()
176
178
177 def test_really_bad_repr():
179 def test_really_bad_repr():
178 with nt.assert_raises(BadException):
180 with nt.assert_raises(BadException):
179 output = pretty.pretty(ReallyBadRepr())
181 output = pretty.pretty(ReallyBadRepr())
180
182
181
183
182 class SA(object):
184 class SA(object):
183 pass
185 pass
184
186
185 class SB(SA):
187 class SB(SA):
186 pass
188 pass
187
189
188 def test_super_repr():
190 def test_super_repr():
191 # "<super: module_name.SA, None>"
189 output = pretty.pretty(super(SA))
192 output = pretty.pretty(super(SA))
190 nt.assert_in("SA", output)
193 nt.assert_regexp_matches(output, r"<super: \S+.SA, None>")
191
194
195 # "<super: module_name.SA, <module_name.SB at 0x...>>"
192 sb = SB()
196 sb = SB()
193 output = pretty.pretty(super(SA, sb))
197 output = pretty.pretty(super(SA, sb))
194 nt.assert_in("SA", output)
198 nt.assert_regexp_matches(output, r"<super: \S+.SA,\s+<\S+.SB at 0x\S+>>")
195
199
196
200
197 def test_long_list():
201 def test_long_list():
198 lis = list(range(10000))
202 lis = list(range(10000))
199 p = pretty.pretty(lis)
203 p = pretty.pretty(lis)
200 last2 = p.rsplit('\n', 2)[-2:]
204 last2 = p.rsplit('\n', 2)[-2:]
201 nt.assert_equal(last2, [' 999,', ' ...]'])
205 nt.assert_equal(last2, [' 999,', ' ...]'])
202
206
203 def test_long_set():
207 def test_long_set():
204 s = set(range(10000))
208 s = set(range(10000))
205 p = pretty.pretty(s)
209 p = pretty.pretty(s)
206 last2 = p.rsplit('\n', 2)[-2:]
210 last2 = p.rsplit('\n', 2)[-2:]
207 nt.assert_equal(last2, [' 999,', ' ...}'])
211 nt.assert_equal(last2, [' 999,', ' ...}'])
208
212
209 def test_long_tuple():
213 def test_long_tuple():
210 tup = tuple(range(10000))
214 tup = tuple(range(10000))
211 p = pretty.pretty(tup)
215 p = pretty.pretty(tup)
212 last2 = p.rsplit('\n', 2)[-2:]
216 last2 = p.rsplit('\n', 2)[-2:]
213 nt.assert_equal(last2, [' 999,', ' ...)'])
217 nt.assert_equal(last2, [' 999,', ' ...)'])
214
218
215 def test_long_dict():
219 def test_long_dict():
216 d = { n:n for n in range(10000) }
220 d = { n:n for n in range(10000) }
217 p = pretty.pretty(d)
221 p = pretty.pretty(d)
218 last2 = p.rsplit('\n', 2)[-2:]
222 last2 = p.rsplit('\n', 2)[-2:]
219 nt.assert_equal(last2, [' 999: 999,', ' ...}'])
223 nt.assert_equal(last2, [' 999: 999,', ' ...}'])
220
224
221 def test_unbound_method():
225 def test_unbound_method():
222 output = pretty.pretty(MyObj.somemethod)
226 output = pretty.pretty(MyObj.somemethod)
223 nt.assert_in('MyObj.somemethod', output)
227 nt.assert_in('MyObj.somemethod', output)
224
228
225
229
226 class MetaClass(type):
230 class MetaClass(type):
227 def __new__(cls, name):
231 def __new__(cls, name):
228 return type.__new__(cls, name, (object,), {'name': name})
232 return type.__new__(cls, name, (object,), {'name': name})
229
233
230 def __repr__(self):
234 def __repr__(self):
231 return "[CUSTOM REPR FOR CLASS %s]" % self.name
235 return "[CUSTOM REPR FOR CLASS %s]" % self.name
232
236
233
237
234 ClassWithMeta = MetaClass('ClassWithMeta')
238 ClassWithMeta = MetaClass('ClassWithMeta')
235
239
236
240
237 def test_metaclass_repr():
241 def test_metaclass_repr():
238 output = pretty.pretty(ClassWithMeta)
242 output = pretty.pretty(ClassWithMeta)
239 nt.assert_equal(output, "[CUSTOM REPR FOR CLASS ClassWithMeta]")
243 nt.assert_equal(output, "[CUSTOM REPR FOR CLASS ClassWithMeta]")
240
244
241
245
242 def test_unicode_repr():
246 def test_unicode_repr():
243 u = u"üniçodé"
247 u = u"üniçodé"
244 ustr = unicode_to_str(u)
248 ustr = unicode_to_str(u)
245
249
246 class C(object):
250 class C(object):
247 def __repr__(self):
251 def __repr__(self):
248 return ustr
252 return ustr
249
253
250 c = C()
254 c = C()
251 p = pretty.pretty(c)
255 p = pretty.pretty(c)
252 nt.assert_equal(p, u)
256 nt.assert_equal(p, u)
253 p = pretty.pretty([c])
257 p = pretty.pretty([c])
254 nt.assert_equal(p, u'[%s]' % u)
258 nt.assert_equal(p, u'[%s]' % u)
255
259
256
260
257 def test_basic_class():
261 def test_basic_class():
258 def type_pprint_wrapper(obj, p, cycle):
262 def type_pprint_wrapper(obj, p, cycle):
259 if obj is MyObj:
263 if obj is MyObj:
260 type_pprint_wrapper.called = True
264 type_pprint_wrapper.called = True
261 return pretty._type_pprint(obj, p, cycle)
265 return pretty._type_pprint(obj, p, cycle)
262 type_pprint_wrapper.called = False
266 type_pprint_wrapper.called = False
263
267
264 stream = StringIO()
268 stream = StringIO()
265 printer = pretty.RepresentationPrinter(stream)
269 printer = pretty.RepresentationPrinter(stream)
266 printer.type_pprinters[type] = type_pprint_wrapper
270 printer.type_pprinters[type] = type_pprint_wrapper
267 printer.pretty(MyObj)
271 printer.pretty(MyObj)
268 printer.flush()
272 printer.flush()
269 output = stream.getvalue()
273 output = stream.getvalue()
270
274
271 nt.assert_equal(output, '%s.MyObj' % __name__)
275 nt.assert_equal(output, '%s.MyObj' % __name__)
272 nt.assert_true(type_pprint_wrapper.called)
276 nt.assert_true(type_pprint_wrapper.called)
273
277
274
278
275 # This is only run on Python 2 because in Python 3 the language prevents you
279 # This is only run on Python 2 because in Python 3 the language prevents you
276 # from setting a non-unicode value for __qualname__ on a metaclass, and it
280 # from setting a non-unicode value for __qualname__ on a metaclass, and it
277 # doesn't respect the descriptor protocol if you subclass unicode and implement
281 # doesn't respect the descriptor protocol if you subclass unicode and implement
278 # __get__.
282 # __get__.
279 @py2_only
283 @py2_only
280 def test_fallback_to__name__on_type():
284 def test_fallback_to__name__on_type():
281 # Test that we correctly repr types that have non-string values for
285 # Test that we correctly repr types that have non-string values for
282 # __qualname__ by falling back to __name__
286 # __qualname__ by falling back to __name__
283
287
284 class Type(object):
288 class Type(object):
285 __qualname__ = 5
289 __qualname__ = 5
286
290
287 # Test repring of the type.
291 # Test repring of the type.
288 stream = StringIO()
292 stream = StringIO()
289 printer = pretty.RepresentationPrinter(stream)
293 printer = pretty.RepresentationPrinter(stream)
290
294
291 printer.pretty(Type)
295 printer.pretty(Type)
292 printer.flush()
296 printer.flush()
293 output = stream.getvalue()
297 output = stream.getvalue()
294
298
295 # If __qualname__ is malformed, we should fall back to __name__.
299 # If __qualname__ is malformed, we should fall back to __name__.
296 expected = '.'.join([__name__, Type.__name__])
300 expected = '.'.join([__name__, Type.__name__])
297 nt.assert_equal(output, expected)
301 nt.assert_equal(output, expected)
298
302
299 # Clear stream buffer.
303 # Clear stream buffer.
300 stream.buf = ''
304 stream.buf = ''
301
305
302 # Test repring of an instance of the type.
306 # Test repring of an instance of the type.
303 instance = Type()
307 instance = Type()
304 printer.pretty(instance)
308 printer.pretty(instance)
305 printer.flush()
309 printer.flush()
306 output = stream.getvalue()
310 output = stream.getvalue()
307
311
308 # Should look like:
312 # Should look like:
309 # <IPython.lib.tests.test_pretty.Type at 0x7f7658ae07d0>
313 # <IPython.lib.tests.test_pretty.Type at 0x7f7658ae07d0>
310 prefix = '<' + '.'.join([__name__, Type.__name__]) + ' at 0x'
314 prefix = '<' + '.'.join([__name__, Type.__name__]) + ' at 0x'
311 nt.assert_true(output.startswith(prefix))
315 nt.assert_true(output.startswith(prefix))
312
316
313
317
314 @py2_only
318 @py2_only
315 def test_fail_gracefully_on_bogus__qualname__and__name__():
319 def test_fail_gracefully_on_bogus__qualname__and__name__():
316 # Test that we correctly repr types that have non-string values for both
320 # Test that we correctly repr types that have non-string values for both
317 # __qualname__ and __name__
321 # __qualname__ and __name__
318
322
319 class Meta(type):
323 class Meta(type):
320 __name__ = 5
324 __name__ = 5
321
325
322 class Type(object):
326 class Type(object):
323 __metaclass__ = Meta
327 __metaclass__ = Meta
324 __qualname__ = 5
328 __qualname__ = 5
325
329
326 stream = StringIO()
330 stream = StringIO()
327 printer = pretty.RepresentationPrinter(stream)
331 printer = pretty.RepresentationPrinter(stream)
328
332
329 printer.pretty(Type)
333 printer.pretty(Type)
330 printer.flush()
334 printer.flush()
331 output = stream.getvalue()
335 output = stream.getvalue()
332
336
333 # If we can't find __name__ or __qualname__ just use a sentinel string.
337 # If we can't find __name__ or __qualname__ just use a sentinel string.
334 expected = '.'.join([__name__, '<unknown type>'])
338 expected = '.'.join([__name__, '<unknown type>'])
335 nt.assert_equal(output, expected)
339 nt.assert_equal(output, expected)
336
340
337 # Clear stream buffer.
341 # Clear stream buffer.
338 stream.buf = ''
342 stream.buf = ''
339
343
340 # Test repring of an instance of the type.
344 # Test repring of an instance of the type.
341 instance = Type()
345 instance = Type()
342 printer.pretty(instance)
346 printer.pretty(instance)
343 printer.flush()
347 printer.flush()
344 output = stream.getvalue()
348 output = stream.getvalue()
345
349
346 # Should look like:
350 # Should look like:
347 # <IPython.lib.tests.test_pretty.<unknown type> at 0x7f7658ae07d0>
351 # <IPython.lib.tests.test_pretty.<unknown type> at 0x7f7658ae07d0>
348 prefix = '<' + '.'.join([__name__, '<unknown type>']) + ' at 0x'
352 prefix = '<' + '.'.join([__name__, '<unknown type>']) + ' at 0x'
349 nt.assert_true(output.startswith(prefix))
353 nt.assert_true(output.startswith(prefix))
350
354
351
355
352 def test_collections_defaultdict():
356 def test_collections_defaultdict():
353 # Create defaultdicts with cycles
357 # Create defaultdicts with cycles
354 a = defaultdict()
358 a = defaultdict()
355 a.default_factory = a
359 a.default_factory = a
356 b = defaultdict(list)
360 b = defaultdict(list)
357 b['key'] = b
361 b['key'] = b
358
362
359 # Dictionary order cannot be relied on, test against single keys.
363 # Dictionary order cannot be relied on, test against single keys.
360 cases = [
364 cases = [
361 (defaultdict(list), 'defaultdict(list, {})'),
365 (defaultdict(list), 'defaultdict(list, {})'),
362 (defaultdict(list, {'key': '-' * 50}),
366 (defaultdict(list, {'key': '-' * 50}),
363 "defaultdict(list,\n"
367 "defaultdict(list,\n"
364 " {'key': '--------------------------------------------------'})"),
368 " {'key': '--------------------------------------------------'})"),
365 (a, 'defaultdict(defaultdict(...), {})'),
369 (a, 'defaultdict(defaultdict(...), {})'),
366 (b, "defaultdict(list, {'key': defaultdict(...)})"),
370 (b, "defaultdict(list, {'key': defaultdict(...)})"),
367 ]
371 ]
368 for obj, expected in cases:
372 for obj, expected in cases:
369 nt.assert_equal(pretty.pretty(obj), expected)
373 nt.assert_equal(pretty.pretty(obj), expected)
370
374
371
375
372 def test_collections_ordereddict():
376 def test_collections_ordereddict():
373 # Create OrderedDict with cycle
377 # Create OrderedDict with cycle
374 a = OrderedDict()
378 a = OrderedDict()
375 a['key'] = a
379 a['key'] = a
376
380
377 cases = [
381 cases = [
378 (OrderedDict(), 'OrderedDict()'),
382 (OrderedDict(), 'OrderedDict()'),
379 (OrderedDict((i, i) for i in range(1000, 1010)),
383 (OrderedDict((i, i) for i in range(1000, 1010)),
380 'OrderedDict([(1000, 1000),\n'
384 'OrderedDict([(1000, 1000),\n'
381 ' (1001, 1001),\n'
385 ' (1001, 1001),\n'
382 ' (1002, 1002),\n'
386 ' (1002, 1002),\n'
383 ' (1003, 1003),\n'
387 ' (1003, 1003),\n'
384 ' (1004, 1004),\n'
388 ' (1004, 1004),\n'
385 ' (1005, 1005),\n'
389 ' (1005, 1005),\n'
386 ' (1006, 1006),\n'
390 ' (1006, 1006),\n'
387 ' (1007, 1007),\n'
391 ' (1007, 1007),\n'
388 ' (1008, 1008),\n'
392 ' (1008, 1008),\n'
389 ' (1009, 1009)])'),
393 ' (1009, 1009)])'),
390 (a, "OrderedDict([('key', OrderedDict(...))])"),
394 (a, "OrderedDict([('key', OrderedDict(...))])"),
391 ]
395 ]
392 for obj, expected in cases:
396 for obj, expected in cases:
393 nt.assert_equal(pretty.pretty(obj), expected)
397 nt.assert_equal(pretty.pretty(obj), expected)
394
398
395
399
396 def test_collections_deque():
400 def test_collections_deque():
397 # Create deque with cycle
401 # Create deque with cycle
398 a = deque()
402 a = deque()
399 a.append(a)
403 a.append(a)
400
404
401 cases = [
405 cases = [
402 (deque(), 'deque([])'),
406 (deque(), 'deque([])'),
403 (deque(i for i in range(1000, 1020)),
407 (deque(i for i in range(1000, 1020)),
404 'deque([1000,\n'
408 'deque([1000,\n'
405 ' 1001,\n'
409 ' 1001,\n'
406 ' 1002,\n'
410 ' 1002,\n'
407 ' 1003,\n'
411 ' 1003,\n'
408 ' 1004,\n'
412 ' 1004,\n'
409 ' 1005,\n'
413 ' 1005,\n'
410 ' 1006,\n'
414 ' 1006,\n'
411 ' 1007,\n'
415 ' 1007,\n'
412 ' 1008,\n'
416 ' 1008,\n'
413 ' 1009,\n'
417 ' 1009,\n'
414 ' 1010,\n'
418 ' 1010,\n'
415 ' 1011,\n'
419 ' 1011,\n'
416 ' 1012,\n'
420 ' 1012,\n'
417 ' 1013,\n'
421 ' 1013,\n'
418 ' 1014,\n'
422 ' 1014,\n'
419 ' 1015,\n'
423 ' 1015,\n'
420 ' 1016,\n'
424 ' 1016,\n'
421 ' 1017,\n'
425 ' 1017,\n'
422 ' 1018,\n'
426 ' 1018,\n'
423 ' 1019])'),
427 ' 1019])'),
424 (a, 'deque([deque(...)])'),
428 (a, 'deque([deque(...)])'),
425 ]
429 ]
426 for obj, expected in cases:
430 for obj, expected in cases:
427 nt.assert_equal(pretty.pretty(obj), expected)
431 nt.assert_equal(pretty.pretty(obj), expected)
428
432
429 def test_collections_counter():
433 def test_collections_counter():
430 class MyCounter(Counter):
434 class MyCounter(Counter):
431 pass
435 pass
432 cases = [
436 cases = [
433 (Counter(), 'Counter()'),
437 (Counter(), 'Counter()'),
434 (Counter(a=1), "Counter({'a': 1})"),
438 (Counter(a=1), "Counter({'a': 1})"),
435 (MyCounter(a=1), "MyCounter({'a': 1})"),
439 (MyCounter(a=1), "MyCounter({'a': 1})"),
436 ]
440 ]
437 for obj, expected in cases:
441 for obj, expected in cases:
438 nt.assert_equal(pretty.pretty(obj), expected)
442 nt.assert_equal(pretty.pretty(obj), expected)
443
444 @py3_only
445 def test_mappingproxy():
446 MP = types.MappingProxyType
447 underlying_dict = {}
448 mp_recursive = MP(underlying_dict)
449 underlying_dict[2] = mp_recursive
450 underlying_dict[3] = underlying_dict
451
452 cases = [
453 (MP({}), "mappingproxy({})"),
454 (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
455 (MP({k: k.upper() for k in string.ascii_lowercase}),
456 "mappingproxy({'a': 'A',\n"
457 " 'b': 'B',\n"
458 " 'c': 'C',\n"
459 " 'd': 'D',\n"
460 " 'e': 'E',\n"
461 " 'f': 'F',\n"
462 " 'g': 'G',\n"
463 " 'h': 'H',\n"
464 " 'i': 'I',\n"
465 " 'j': 'J',\n"
466 " 'k': 'K',\n"
467 " 'l': 'L',\n"
468 " 'm': 'M',\n"
469 " 'n': 'N',\n"
470 " 'o': 'O',\n"
471 " 'p': 'P',\n"
472 " 'q': 'Q',\n"
473 " 'r': 'R',\n"
474 " 's': 'S',\n"
475 " 't': 'T',\n"
476 " 'u': 'U',\n"
477 " 'v': 'V',\n"
478 " 'w': 'W',\n"
479 " 'x': 'X',\n"
480 " 'y': 'Y',\n"
481 " 'z': 'Z'})"),
482 (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
483 (underlying_dict,
484 "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
485 ]
486 for obj, expected in cases:
487 nt.assert_equal(pretty.pretty(obj), expected)
488
489 @cpython2_only # In PyPy, types.DictProxyType is dict
490 def test_dictproxy():
491 # This is the dictproxy constructor itself from the Python API,
492 DP = ctypes.pythonapi.PyDictProxy_New
493 DP.argtypes, DP.restype = (ctypes.py_object,), ctypes.py_object
494
495 underlying_dict = {}
496 mp_recursive = DP(underlying_dict)
497 underlying_dict[0] = mp_recursive
498 underlying_dict[-3] = underlying_dict
499
500 cases = [
501 (DP({}), "dict_proxy({})"),
502 (DP({None: DP({})}), "dict_proxy({None: dict_proxy({})})"),
503 (DP({k: k.lower() for k in string.ascii_uppercase}),
504 "dict_proxy({'A': 'a',\n"
505 " 'B': 'b',\n"
506 " 'C': 'c',\n"
507 " 'D': 'd',\n"
508 " 'E': 'e',\n"
509 " 'F': 'f',\n"
510 " 'G': 'g',\n"
511 " 'H': 'h',\n"
512 " 'I': 'i',\n"
513 " 'J': 'j',\n"
514 " 'K': 'k',\n"
515 " 'L': 'l',\n"
516 " 'M': 'm',\n"
517 " 'N': 'n',\n"
518 " 'O': 'o',\n"
519 " 'P': 'p',\n"
520 " 'Q': 'q',\n"
521 " 'R': 'r',\n"
522 " 'S': 's',\n"
523 " 'T': 't',\n"
524 " 'U': 'u',\n"
525 " 'V': 'v',\n"
526 " 'W': 'w',\n"
527 " 'X': 'x',\n"
528 " 'Y': 'y',\n"
529 " 'Z': 'z'})"),
530 (mp_recursive, "dict_proxy({-3: {-3: {...}, 0: {...}}, 0: {...}})"),
531 ]
532 for obj, expected in cases:
533 nt.assert_is_instance(obj, types.DictProxyType) # Meta-test
534 nt.assert_equal(pretty.pretty(obj), expected)
535 nt.assert_equal(pretty.pretty(underlying_dict),
536 "{-3: {...}, 0: dict_proxy({-3: {...}, 0: {...}})}")
@@ -1,379 +1,380 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Decorators for labeling test objects.
2 """Decorators for labeling test objects.
3
3
4 Decorators that merely return a modified version of the original function
4 Decorators that merely return a modified version of the original function
5 object are straightforward. Decorators that return a new function object need
5 object are straightforward. Decorators that return a new function object need
6 to use nose.tools.make_decorator(original_function)(decorator) in returning the
6 to use nose.tools.make_decorator(original_function)(decorator) in returning the
7 decorator, in order to preserve metadata such as function name, setup and
7 decorator, in order to preserve metadata such as function name, setup and
8 teardown functions and so on - see nose.tools for more information.
8 teardown functions and so on - see nose.tools for more information.
9
9
10 This module provides a set of useful decorators meant to be ready to use in
10 This module provides a set of useful decorators meant to be ready to use in
11 your own tests. See the bottom of the file for the ready-made ones, and if you
11 your own tests. See the bottom of the file for the ready-made ones, and if you
12 find yourself writing a new one that may be of generic use, add it here.
12 find yourself writing a new one that may be of generic use, add it here.
13
13
14 Included decorators:
14 Included decorators:
15
15
16
16
17 Lightweight testing that remains unittest-compatible.
17 Lightweight testing that remains unittest-compatible.
18
18
19 - An @as_unittest decorator can be used to tag any normal parameter-less
19 - An @as_unittest decorator can be used to tag any normal parameter-less
20 function as a unittest TestCase. Then, both nose and normal unittest will
20 function as a unittest TestCase. Then, both nose and normal unittest will
21 recognize it as such. This will make it easier to migrate away from Nose if
21 recognize it as such. This will make it easier to migrate away from Nose if
22 we ever need/want to while maintaining very lightweight tests.
22 we ever need/want to while maintaining very lightweight tests.
23
23
24 NOTE: This file contains IPython-specific decorators. Using the machinery in
24 NOTE: This file contains IPython-specific decorators. Using the machinery in
25 IPython.external.decorators, we import either numpy.testing.decorators if numpy is
25 IPython.external.decorators, we import either numpy.testing.decorators if numpy is
26 available, OR use equivalent code in IPython.external._decorators, which
26 available, OR use equivalent code in IPython.external._decorators, which
27 we've copied verbatim from numpy.
27 we've copied verbatim from numpy.
28
28
29 """
29 """
30
30
31 # Copyright (c) IPython Development Team.
31 # Copyright (c) IPython Development Team.
32 # Distributed under the terms of the Modified BSD License.
32 # Distributed under the terms of the Modified BSD License.
33
33
34 import sys
34 import sys
35 import os
35 import os
36 import tempfile
36 import tempfile
37 import unittest
37 import unittest
38 import warnings
38 import warnings
39
39
40 from decorator import decorator
40 from decorator import decorator
41
41
42 # Expose the unittest-driven decorators
42 # Expose the unittest-driven decorators
43 from .ipunittest import ipdoctest, ipdocstring
43 from .ipunittest import ipdoctest, ipdocstring
44
44
45 # Grab the numpy-specific decorators which we keep in a file that we
45 # Grab the numpy-specific decorators which we keep in a file that we
46 # occasionally update from upstream: decorators.py is a copy of
46 # occasionally update from upstream: decorators.py is a copy of
47 # numpy.testing.decorators, we expose all of it here.
47 # numpy.testing.decorators, we expose all of it here.
48 from IPython.external.decorators import *
48 from IPython.external.decorators import *
49
49
50 # For onlyif_cmd_exists decorator
50 # For onlyif_cmd_exists decorator
51 from IPython.utils.py3compat import string_types, which, PY2, PY3
51 from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY
52
52
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54 # Classes and functions
54 # Classes and functions
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56
56
57 # Simple example of the basic idea
57 # Simple example of the basic idea
58 def as_unittest(func):
58 def as_unittest(func):
59 """Decorator to make a simple function into a normal test via unittest."""
59 """Decorator to make a simple function into a normal test via unittest."""
60 class Tester(unittest.TestCase):
60 class Tester(unittest.TestCase):
61 def test(self):
61 def test(self):
62 func()
62 func()
63
63
64 Tester.__name__ = func.__name__
64 Tester.__name__ = func.__name__
65
65
66 return Tester
66 return Tester
67
67
68 # Utility functions
68 # Utility functions
69
69
70 def apply_wrapper(wrapper,func):
70 def apply_wrapper(wrapper,func):
71 """Apply a wrapper to a function for decoration.
71 """Apply a wrapper to a function for decoration.
72
72
73 This mixes Michele Simionato's decorator tool with nose's make_decorator,
73 This mixes Michele Simionato's decorator tool with nose's make_decorator,
74 to apply a wrapper in a decorator so that all nose attributes, as well as
74 to apply a wrapper in a decorator so that all nose attributes, as well as
75 function signature and other properties, survive the decoration cleanly.
75 function signature and other properties, survive the decoration cleanly.
76 This will ensure that wrapped functions can still be well introspected via
76 This will ensure that wrapped functions can still be well introspected via
77 IPython, for example.
77 IPython, for example.
78 """
78 """
79 warnings.warn("The function `apply_wrapper` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
79 warnings.warn("The function `apply_wrapper` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
80
80
81 import nose.tools
81 import nose.tools
82
82
83 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
83 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
84
84
85
85
86 def make_label_dec(label,ds=None):
86 def make_label_dec(label,ds=None):
87 """Factory function to create a decorator that applies one or more labels.
87 """Factory function to create a decorator that applies one or more labels.
88
88
89 Parameters
89 Parameters
90 ----------
90 ----------
91 label : string or sequence
91 label : string or sequence
92 One or more labels that will be applied by the decorator to the functions
92 One or more labels that will be applied by the decorator to the functions
93 it decorates. Labels are attributes of the decorated function with their
93 it decorates. Labels are attributes of the decorated function with their
94 value set to True.
94 value set to True.
95
95
96 ds : string
96 ds : string
97 An optional docstring for the resulting decorator. If not given, a
97 An optional docstring for the resulting decorator. If not given, a
98 default docstring is auto-generated.
98 default docstring is auto-generated.
99
99
100 Returns
100 Returns
101 -------
101 -------
102 A decorator.
102 A decorator.
103
103
104 Examples
104 Examples
105 --------
105 --------
106
106
107 A simple labeling decorator:
107 A simple labeling decorator:
108
108
109 >>> slow = make_label_dec('slow')
109 >>> slow = make_label_dec('slow')
110 >>> slow.__doc__
110 >>> slow.__doc__
111 "Labels a test as 'slow'."
111 "Labels a test as 'slow'."
112
112
113 And one that uses multiple labels and a custom docstring:
113 And one that uses multiple labels and a custom docstring:
114
114
115 >>> rare = make_label_dec(['slow','hard'],
115 >>> rare = make_label_dec(['slow','hard'],
116 ... "Mix labels 'slow' and 'hard' for rare tests.")
116 ... "Mix labels 'slow' and 'hard' for rare tests.")
117 >>> rare.__doc__
117 >>> rare.__doc__
118 "Mix labels 'slow' and 'hard' for rare tests."
118 "Mix labels 'slow' and 'hard' for rare tests."
119
119
120 Now, let's test using this one:
120 Now, let's test using this one:
121 >>> @rare
121 >>> @rare
122 ... def f(): pass
122 ... def f(): pass
123 ...
123 ...
124 >>>
124 >>>
125 >>> f.slow
125 >>> f.slow
126 True
126 True
127 >>> f.hard
127 >>> f.hard
128 True
128 True
129 """
129 """
130
130
131 warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
131 warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
132 if isinstance(label, string_types):
132 if isinstance(label, string_types):
133 labels = [label]
133 labels = [label]
134 else:
134 else:
135 labels = label
135 labels = label
136
136
137 # Validate that the given label(s) are OK for use in setattr() by doing a
137 # Validate that the given label(s) are OK for use in setattr() by doing a
138 # dry run on a dummy function.
138 # dry run on a dummy function.
139 tmp = lambda : None
139 tmp = lambda : None
140 for label in labels:
140 for label in labels:
141 setattr(tmp,label,True)
141 setattr(tmp,label,True)
142
142
143 # This is the actual decorator we'll return
143 # This is the actual decorator we'll return
144 def decor(f):
144 def decor(f):
145 for label in labels:
145 for label in labels:
146 setattr(f,label,True)
146 setattr(f,label,True)
147 return f
147 return f
148
148
149 # Apply the user's docstring, or autogenerate a basic one
149 # Apply the user's docstring, or autogenerate a basic one
150 if ds is None:
150 if ds is None:
151 ds = "Labels a test as %r." % label
151 ds = "Labels a test as %r." % label
152 decor.__doc__ = ds
152 decor.__doc__ = ds
153
153
154 return decor
154 return decor
155
155
156
156
157 # Inspired by numpy's skipif, but uses the full apply_wrapper utility to
157 # Inspired by numpy's skipif, but uses the full apply_wrapper utility to
158 # preserve function metadata better and allows the skip condition to be a
158 # preserve function metadata better and allows the skip condition to be a
159 # callable.
159 # callable.
160 def skipif(skip_condition, msg=None):
160 def skipif(skip_condition, msg=None):
161 ''' Make function raise SkipTest exception if skip_condition is true
161 ''' Make function raise SkipTest exception if skip_condition is true
162
162
163 Parameters
163 Parameters
164 ----------
164 ----------
165
165
166 skip_condition : bool or callable
166 skip_condition : bool or callable
167 Flag to determine whether to skip test. If the condition is a
167 Flag to determine whether to skip test. If the condition is a
168 callable, it is used at runtime to dynamically make the decision. This
168 callable, it is used at runtime to dynamically make the decision. This
169 is useful for tests that may require costly imports, to delay the cost
169 is useful for tests that may require costly imports, to delay the cost
170 until the test suite is actually executed.
170 until the test suite is actually executed.
171 msg : string
171 msg : string
172 Message to give on raising a SkipTest exception.
172 Message to give on raising a SkipTest exception.
173
173
174 Returns
174 Returns
175 -------
175 -------
176 decorator : function
176 decorator : function
177 Decorator, which, when applied to a function, causes SkipTest
177 Decorator, which, when applied to a function, causes SkipTest
178 to be raised when the skip_condition was True, and the function
178 to be raised when the skip_condition was True, and the function
179 to be called normally otherwise.
179 to be called normally otherwise.
180
180
181 Notes
181 Notes
182 -----
182 -----
183 You will see from the code that we had to further decorate the
183 You will see from the code that we had to further decorate the
184 decorator with the nose.tools.make_decorator function in order to
184 decorator with the nose.tools.make_decorator function in order to
185 transmit function name, and various other metadata.
185 transmit function name, and various other metadata.
186 '''
186 '''
187
187
188 def skip_decorator(f):
188 def skip_decorator(f):
189 # Local import to avoid a hard nose dependency and only incur the
189 # Local import to avoid a hard nose dependency and only incur the
190 # import time overhead at actual test-time.
190 # import time overhead at actual test-time.
191 import nose
191 import nose
192
192
193 # Allow for both boolean or callable skip conditions.
193 # Allow for both boolean or callable skip conditions.
194 if callable(skip_condition):
194 if callable(skip_condition):
195 skip_val = skip_condition
195 skip_val = skip_condition
196 else:
196 else:
197 skip_val = lambda : skip_condition
197 skip_val = lambda : skip_condition
198
198
199 def get_msg(func,msg=None):
199 def get_msg(func,msg=None):
200 """Skip message with information about function being skipped."""
200 """Skip message with information about function being skipped."""
201 if msg is None: out = 'Test skipped due to test condition.'
201 if msg is None: out = 'Test skipped due to test condition.'
202 else: out = msg
202 else: out = msg
203 return "Skipping test: %s. %s" % (func.__name__,out)
203 return "Skipping test: %s. %s" % (func.__name__,out)
204
204
205 # We need to define *two* skippers because Python doesn't allow both
205 # We need to define *two* skippers because Python doesn't allow both
206 # return with value and yield inside the same function.
206 # return with value and yield inside the same function.
207 def skipper_func(*args, **kwargs):
207 def skipper_func(*args, **kwargs):
208 """Skipper for normal test functions."""
208 """Skipper for normal test functions."""
209 if skip_val():
209 if skip_val():
210 raise nose.SkipTest(get_msg(f,msg))
210 raise nose.SkipTest(get_msg(f,msg))
211 else:
211 else:
212 return f(*args, **kwargs)
212 return f(*args, **kwargs)
213
213
214 def skipper_gen(*args, **kwargs):
214 def skipper_gen(*args, **kwargs):
215 """Skipper for test generators."""
215 """Skipper for test generators."""
216 if skip_val():
216 if skip_val():
217 raise nose.SkipTest(get_msg(f,msg))
217 raise nose.SkipTest(get_msg(f,msg))
218 else:
218 else:
219 for x in f(*args, **kwargs):
219 for x in f(*args, **kwargs):
220 yield x
220 yield x
221
221
222 # Choose the right skipper to use when building the actual generator.
222 # Choose the right skipper to use when building the actual generator.
223 if nose.util.isgenerator(f):
223 if nose.util.isgenerator(f):
224 skipper = skipper_gen
224 skipper = skipper_gen
225 else:
225 else:
226 skipper = skipper_func
226 skipper = skipper_func
227
227
228 return nose.tools.make_decorator(f)(skipper)
228 return nose.tools.make_decorator(f)(skipper)
229
229
230 return skip_decorator
230 return skip_decorator
231
231
232 # A version with the condition set to true, common case just to attach a message
232 # A version with the condition set to true, common case just to attach a message
233 # to a skip decorator
233 # to a skip decorator
234 def skip(msg=None):
234 def skip(msg=None):
235 """Decorator factory - mark a test function for skipping from test suite.
235 """Decorator factory - mark a test function for skipping from test suite.
236
236
237 Parameters
237 Parameters
238 ----------
238 ----------
239 msg : string
239 msg : string
240 Optional message to be added.
240 Optional message to be added.
241
241
242 Returns
242 Returns
243 -------
243 -------
244 decorator : function
244 decorator : function
245 Decorator, which, when applied to a function, causes SkipTest
245 Decorator, which, when applied to a function, causes SkipTest
246 to be raised, with the optional message added.
246 to be raised, with the optional message added.
247 """
247 """
248
248
249 return skipif(True,msg)
249 return skipif(True,msg)
250
250
251
251
252 def onlyif(condition, msg):
252 def onlyif(condition, msg):
253 """The reverse from skipif, see skipif for details."""
253 """The reverse from skipif, see skipif for details."""
254
254
255 if callable(condition):
255 if callable(condition):
256 skip_condition = lambda : not condition()
256 skip_condition = lambda : not condition()
257 else:
257 else:
258 skip_condition = lambda : not condition
258 skip_condition = lambda : not condition
259
259
260 return skipif(skip_condition, msg)
260 return skipif(skip_condition, msg)
261
261
262 #-----------------------------------------------------------------------------
262 #-----------------------------------------------------------------------------
263 # Utility functions for decorators
263 # Utility functions for decorators
264 def module_not_available(module):
264 def module_not_available(module):
265 """Can module be imported? Returns true if module does NOT import.
265 """Can module be imported? Returns true if module does NOT import.
266
266
267 This is used to make a decorator to skip tests that require module to be
267 This is used to make a decorator to skip tests that require module to be
268 available, but delay the 'import numpy' to test execution time.
268 available, but delay the 'import numpy' to test execution time.
269 """
269 """
270 try:
270 try:
271 mod = __import__(module)
271 mod = __import__(module)
272 mod_not_avail = False
272 mod_not_avail = False
273 except ImportError:
273 except ImportError:
274 mod_not_avail = True
274 mod_not_avail = True
275
275
276 return mod_not_avail
276 return mod_not_avail
277
277
278
278
279 def decorated_dummy(dec, name):
279 def decorated_dummy(dec, name):
280 """Return a dummy function decorated with dec, with the given name.
280 """Return a dummy function decorated with dec, with the given name.
281
281
282 Examples
282 Examples
283 --------
283 --------
284 import IPython.testing.decorators as dec
284 import IPython.testing.decorators as dec
285 setup = dec.decorated_dummy(dec.skip_if_no_x11, __name__)
285 setup = dec.decorated_dummy(dec.skip_if_no_x11, __name__)
286 """
286 """
287 warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
287 warnings.warn("The function `make_label_dec` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
288 dummy = lambda: None
288 dummy = lambda: None
289 dummy.__name__ = name
289 dummy.__name__ = name
290 return dec(dummy)
290 return dec(dummy)
291
291
292 #-----------------------------------------------------------------------------
292 #-----------------------------------------------------------------------------
293 # Decorators for public use
293 # Decorators for public use
294
294
295 # Decorators to skip certain tests on specific platforms.
295 # Decorators to skip certain tests on specific platforms.
296 skip_win32 = skipif(sys.platform == 'win32',
296 skip_win32 = skipif(sys.platform == 'win32',
297 "This test does not run under Windows")
297 "This test does not run under Windows")
298 skip_linux = skipif(sys.platform.startswith('linux'),
298 skip_linux = skipif(sys.platform.startswith('linux'),
299 "This test does not run under Linux")
299 "This test does not run under Linux")
300 skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X")
300 skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X")
301
301
302
302
303 # Decorators to skip tests if not on specific platforms.
303 # Decorators to skip tests if not on specific platforms.
304 skip_if_not_win32 = skipif(sys.platform != 'win32',
304 skip_if_not_win32 = skipif(sys.platform != 'win32',
305 "This test only runs under Windows")
305 "This test only runs under Windows")
306 skip_if_not_linux = skipif(not sys.platform.startswith('linux'),
306 skip_if_not_linux = skipif(not sys.platform.startswith('linux'),
307 "This test only runs under Linux")
307 "This test only runs under Linux")
308 skip_if_not_osx = skipif(sys.platform != 'darwin',
308 skip_if_not_osx = skipif(sys.platform != 'darwin',
309 "This test only runs under OSX")
309 "This test only runs under OSX")
310
310
311
311
312 _x11_skip_cond = (sys.platform not in ('darwin', 'win32') and
312 _x11_skip_cond = (sys.platform not in ('darwin', 'win32') and
313 os.environ.get('DISPLAY', '') == '')
313 os.environ.get('DISPLAY', '') == '')
314 _x11_skip_msg = "Skipped under *nix when X11/XOrg not available"
314 _x11_skip_msg = "Skipped under *nix when X11/XOrg not available"
315
315
316 skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg)
316 skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg)
317
317
318 # not a decorator itself, returns a dummy function to be used as setup
318 # not a decorator itself, returns a dummy function to be used as setup
319 def skip_file_no_x11(name):
319 def skip_file_no_x11(name):
320 warnings.warn("The function `skip_file_no_x11` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
320 warnings.warn("The function `skip_file_no_x11` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
321 return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None
321 return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None
322
322
323 # Other skip decorators
323 # Other skip decorators
324
324
325 # generic skip without module
325 # generic skip without module
326 skip_without = lambda mod: skipif(module_not_available(mod), "This test requires %s" % mod)
326 skip_without = lambda mod: skipif(module_not_available(mod), "This test requires %s" % mod)
327
327
328 skipif_not_numpy = skip_without('numpy')
328 skipif_not_numpy = skip_without('numpy')
329
329
330 skipif_not_matplotlib = skip_without('matplotlib')
330 skipif_not_matplotlib = skip_without('matplotlib')
331
331
332 skipif_not_sympy = skip_without('sympy')
332 skipif_not_sympy = skip_without('sympy')
333
333
334 skip_known_failure = knownfailureif(True,'This test is known to fail')
334 skip_known_failure = knownfailureif(True,'This test is known to fail')
335
335
336 known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
336 known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
337 'This test is known to fail on Python 3.')
337 'This test is known to fail on Python 3.')
338
338
339 cpython2_only = skipif(PY3 or PYPY, "This test only runs on CPython 2.")
339 py2_only = skipif(PY3, "This test only runs on Python 2.")
340 py2_only = skipif(PY3, "This test only runs on Python 2.")
340 py3_only = skipif(PY2, "This test only runs on Python 3.")
341 py3_only = skipif(PY2, "This test only runs on Python 3.")
341
342
342 # A null 'decorator', useful to make more readable code that needs to pick
343 # A null 'decorator', useful to make more readable code that needs to pick
343 # between different decorators based on OS or other conditions
344 # between different decorators based on OS or other conditions
344 null_deco = lambda f: f
345 null_deco = lambda f: f
345
346
346 # Some tests only run where we can use unicode paths. Note that we can't just
347 # Some tests only run where we can use unicode paths. Note that we can't just
347 # check os.path.supports_unicode_filenames, which is always False on Linux.
348 # check os.path.supports_unicode_filenames, which is always False on Linux.
348 try:
349 try:
349 f = tempfile.NamedTemporaryFile(prefix=u"tmp€")
350 f = tempfile.NamedTemporaryFile(prefix=u"tmp€")
350 except UnicodeEncodeError:
351 except UnicodeEncodeError:
351 unicode_paths = False
352 unicode_paths = False
352 else:
353 else:
353 unicode_paths = True
354 unicode_paths = True
354 f.close()
355 f.close()
355
356
356 onlyif_unicode_paths = onlyif(unicode_paths, ("This test is only applicable "
357 onlyif_unicode_paths = onlyif(unicode_paths, ("This test is only applicable "
357 "where we can use unicode in filenames."))
358 "where we can use unicode in filenames."))
358
359
359
360
360 def onlyif_cmds_exist(*commands):
361 def onlyif_cmds_exist(*commands):
361 """
362 """
362 Decorator to skip test when at least one of `commands` is not found.
363 Decorator to skip test when at least one of `commands` is not found.
363 """
364 """
364 for cmd in commands:
365 for cmd in commands:
365 if not which(cmd):
366 if not which(cmd):
366 return skip("This test runs only if command '{0}' "
367 return skip("This test runs only if command '{0}' "
367 "is installed".format(cmd))
368 "is installed".format(cmd))
368 return null_deco
369 return null_deco
369
370
370 def onlyif_any_cmd_exists(*commands):
371 def onlyif_any_cmd_exists(*commands):
371 """
372 """
372 Decorator to skip test unless at least one of `commands` is found.
373 Decorator to skip test unless at least one of `commands` is found.
373 """
374 """
374 warnings.warn("The function `onlyif_any_cmd_exists` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
375 warnings.warn("The function `onlyif_any_cmd_exists` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
375 for cmd in commands:
376 for cmd in commands:
376 if which(cmd):
377 if which(cmd):
377 return null_deco
378 return null_deco
378 return skip("This test runs only if one of the commands {0} "
379 return skip("This test runs only if one of the commands {0} "
379 "is installed".format(commands))
380 "is installed".format(commands))
@@ -1,334 +1,336 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 import functools
3 import functools
4 import os
4 import os
5 import sys
5 import sys
6 import re
6 import re
7 import shutil
7 import shutil
8 import types
8 import types
9 import platform
9
10
10 from .encoding import DEFAULT_ENCODING
11 from .encoding import DEFAULT_ENCODING
11
12
12 def no_code(x, encoding=None):
13 def no_code(x, encoding=None):
13 return x
14 return x
14
15
15 def decode(s, encoding=None):
16 def decode(s, encoding=None):
16 encoding = encoding or DEFAULT_ENCODING
17 encoding = encoding or DEFAULT_ENCODING
17 return s.decode(encoding, "replace")
18 return s.decode(encoding, "replace")
18
19
19 def encode(u, encoding=None):
20 def encode(u, encoding=None):
20 encoding = encoding or DEFAULT_ENCODING
21 encoding = encoding or DEFAULT_ENCODING
21 return u.encode(encoding, "replace")
22 return u.encode(encoding, "replace")
22
23
23
24
24 def cast_unicode(s, encoding=None):
25 def cast_unicode(s, encoding=None):
25 if isinstance(s, bytes):
26 if isinstance(s, bytes):
26 return decode(s, encoding)
27 return decode(s, encoding)
27 return s
28 return s
28
29
29 def cast_bytes(s, encoding=None):
30 def cast_bytes(s, encoding=None):
30 if not isinstance(s, bytes):
31 if not isinstance(s, bytes):
31 return encode(s, encoding)
32 return encode(s, encoding)
32 return s
33 return s
33
34
34 def buffer_to_bytes(buf):
35 def buffer_to_bytes(buf):
35 """Cast a buffer object to bytes"""
36 """Cast a buffer object to bytes"""
36 if not isinstance(buf, bytes):
37 if not isinstance(buf, bytes):
37 buf = bytes(buf)
38 buf = bytes(buf)
38 return buf
39 return buf
39
40
40 def _modify_str_or_docstring(str_change_func):
41 def _modify_str_or_docstring(str_change_func):
41 @functools.wraps(str_change_func)
42 @functools.wraps(str_change_func)
42 def wrapper(func_or_str):
43 def wrapper(func_or_str):
43 if isinstance(func_or_str, string_types):
44 if isinstance(func_or_str, string_types):
44 func = None
45 func = None
45 doc = func_or_str
46 doc = func_or_str
46 else:
47 else:
47 func = func_or_str
48 func = func_or_str
48 doc = func.__doc__
49 doc = func.__doc__
49
50
50 # PYTHONOPTIMIZE=2 strips docstrings, so they can disappear unexpectedly
51 # PYTHONOPTIMIZE=2 strips docstrings, so they can disappear unexpectedly
51 if doc is not None:
52 if doc is not None:
52 doc = str_change_func(doc)
53 doc = str_change_func(doc)
53
54
54 if func:
55 if func:
55 func.__doc__ = doc
56 func.__doc__ = doc
56 return func
57 return func
57 return doc
58 return doc
58 return wrapper
59 return wrapper
59
60
60 def safe_unicode(e):
61 def safe_unicode(e):
61 """unicode(e) with various fallbacks. Used for exceptions, which may not be
62 """unicode(e) with various fallbacks. Used for exceptions, which may not be
62 safe to call unicode() on.
63 safe to call unicode() on.
63 """
64 """
64 try:
65 try:
65 return unicode_type(e)
66 return unicode_type(e)
66 except UnicodeError:
67 except UnicodeError:
67 pass
68 pass
68
69
69 try:
70 try:
70 return str_to_unicode(str(e))
71 return str_to_unicode(str(e))
71 except UnicodeError:
72 except UnicodeError:
72 pass
73 pass
73
74
74 try:
75 try:
75 return str_to_unicode(repr(e))
76 return str_to_unicode(repr(e))
76 except UnicodeError:
77 except UnicodeError:
77 pass
78 pass
78
79
79 return u'Unrecoverably corrupt evalue'
80 return u'Unrecoverably corrupt evalue'
80
81
81 # shutil.which from Python 3.4
82 # shutil.which from Python 3.4
82 def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
83 def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
83 """Given a command, mode, and a PATH string, return the path which
84 """Given a command, mode, and a PATH string, return the path which
84 conforms to the given mode on the PATH, or None if there is no such
85 conforms to the given mode on the PATH, or None if there is no such
85 file.
86 file.
86
87
87 `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
88 `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
88 of os.environ.get("PATH"), or can be overridden with a custom search
89 of os.environ.get("PATH"), or can be overridden with a custom search
89 path.
90 path.
90
91
91 This is a backport of shutil.which from Python 3.4
92 This is a backport of shutil.which from Python 3.4
92 """
93 """
93 # Check that a given file can be accessed with the correct mode.
94 # Check that a given file can be accessed with the correct mode.
94 # Additionally check that `file` is not a directory, as on Windows
95 # Additionally check that `file` is not a directory, as on Windows
95 # directories pass the os.access check.
96 # directories pass the os.access check.
96 def _access_check(fn, mode):
97 def _access_check(fn, mode):
97 return (os.path.exists(fn) and os.access(fn, mode)
98 return (os.path.exists(fn) and os.access(fn, mode)
98 and not os.path.isdir(fn))
99 and not os.path.isdir(fn))
99
100
100 # If we're given a path with a directory part, look it up directly rather
101 # If we're given a path with a directory part, look it up directly rather
101 # than referring to PATH directories. This includes checking relative to the
102 # than referring to PATH directories. This includes checking relative to the
102 # current directory, e.g. ./script
103 # current directory, e.g. ./script
103 if os.path.dirname(cmd):
104 if os.path.dirname(cmd):
104 if _access_check(cmd, mode):
105 if _access_check(cmd, mode):
105 return cmd
106 return cmd
106 return None
107 return None
107
108
108 if path is None:
109 if path is None:
109 path = os.environ.get("PATH", os.defpath)
110 path = os.environ.get("PATH", os.defpath)
110 if not path:
111 if not path:
111 return None
112 return None
112 path = path.split(os.pathsep)
113 path = path.split(os.pathsep)
113
114
114 if sys.platform == "win32":
115 if sys.platform == "win32":
115 # The current directory takes precedence on Windows.
116 # The current directory takes precedence on Windows.
116 if not os.curdir in path:
117 if not os.curdir in path:
117 path.insert(0, os.curdir)
118 path.insert(0, os.curdir)
118
119
119 # PATHEXT is necessary to check on Windows.
120 # PATHEXT is necessary to check on Windows.
120 pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
121 pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
121 # See if the given file matches any of the expected path extensions.
122 # See if the given file matches any of the expected path extensions.
122 # This will allow us to short circuit when given "python.exe".
123 # This will allow us to short circuit when given "python.exe".
123 # If it does match, only test that one, otherwise we have to try
124 # If it does match, only test that one, otherwise we have to try
124 # others.
125 # others.
125 if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
126 if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
126 files = [cmd]
127 files = [cmd]
127 else:
128 else:
128 files = [cmd + ext for ext in pathext]
129 files = [cmd + ext for ext in pathext]
129 else:
130 else:
130 # On other platforms you don't have things like PATHEXT to tell you
131 # On other platforms you don't have things like PATHEXT to tell you
131 # what file suffixes are executable, so just pass on cmd as-is.
132 # what file suffixes are executable, so just pass on cmd as-is.
132 files = [cmd]
133 files = [cmd]
133
134
134 seen = set()
135 seen = set()
135 for dir in path:
136 for dir in path:
136 normdir = os.path.normcase(dir)
137 normdir = os.path.normcase(dir)
137 if not normdir in seen:
138 if not normdir in seen:
138 seen.add(normdir)
139 seen.add(normdir)
139 for thefile in files:
140 for thefile in files:
140 name = os.path.join(dir, thefile)
141 name = os.path.join(dir, thefile)
141 if _access_check(name, mode):
142 if _access_check(name, mode):
142 return name
143 return name
143 return None
144 return None
144
145
145 if sys.version_info[0] >= 3:
146 if sys.version_info[0] >= 3:
146 PY3 = True
147 PY3 = True
147
148
148 # keep reference to builtin_mod because the kernel overrides that value
149 # keep reference to builtin_mod because the kernel overrides that value
149 # to forward requests to a frontend.
150 # to forward requests to a frontend.
150 def input(prompt=''):
151 def input(prompt=''):
151 return builtin_mod.input(prompt)
152 return builtin_mod.input(prompt)
152
153
153 builtin_mod_name = "builtins"
154 builtin_mod_name = "builtins"
154 import builtins as builtin_mod
155 import builtins as builtin_mod
155
156
156 str_to_unicode = no_code
157 str_to_unicode = no_code
157 unicode_to_str = no_code
158 unicode_to_str = no_code
158 str_to_bytes = encode
159 str_to_bytes = encode
159 bytes_to_str = decode
160 bytes_to_str = decode
160 cast_bytes_py2 = no_code
161 cast_bytes_py2 = no_code
161 cast_unicode_py2 = no_code
162 cast_unicode_py2 = no_code
162 buffer_to_bytes_py2 = no_code
163 buffer_to_bytes_py2 = no_code
163
164
164 string_types = (str,)
165 string_types = (str,)
165 unicode_type = str
166 unicode_type = str
166
167
167 which = shutil.which
168 which = shutil.which
168
169
169 def isidentifier(s, dotted=False):
170 def isidentifier(s, dotted=False):
170 if dotted:
171 if dotted:
171 return all(isidentifier(a) for a in s.split("."))
172 return all(isidentifier(a) for a in s.split("."))
172 return s.isidentifier()
173 return s.isidentifier()
173
174
174 xrange = range
175 xrange = range
175 def iteritems(d): return iter(d.items())
176 def iteritems(d): return iter(d.items())
176 def itervalues(d): return iter(d.values())
177 def itervalues(d): return iter(d.values())
177 getcwd = os.getcwd
178 getcwd = os.getcwd
178
179
179 MethodType = types.MethodType
180 MethodType = types.MethodType
180
181
181 def execfile(fname, glob, loc=None, compiler=None):
182 def execfile(fname, glob, loc=None, compiler=None):
182 loc = loc if (loc is not None) else glob
183 loc = loc if (loc is not None) else glob
183 with open(fname, 'rb') as f:
184 with open(fname, 'rb') as f:
184 compiler = compiler or compile
185 compiler = compiler or compile
185 exec(compiler(f.read(), fname, 'exec'), glob, loc)
186 exec(compiler(f.read(), fname, 'exec'), glob, loc)
186
187
187 # Refactor print statements in doctests.
188 # Refactor print statements in doctests.
188 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
189 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
189 def _print_statement_sub(match):
190 def _print_statement_sub(match):
190 expr = match.groups('expr')
191 expr = match.groups('expr')
191 return "print(%s)" % expr
192 return "print(%s)" % expr
192
193
193 @_modify_str_or_docstring
194 @_modify_str_or_docstring
194 def doctest_refactor_print(doc):
195 def doctest_refactor_print(doc):
195 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
196 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
196 unfortunately doesn't pick up on our doctests.
197 unfortunately doesn't pick up on our doctests.
197
198
198 Can accept a string or a function, so it can be used as a decorator."""
199 Can accept a string or a function, so it can be used as a decorator."""
199 return _print_statement_re.sub(_print_statement_sub, doc)
200 return _print_statement_re.sub(_print_statement_sub, doc)
200
201
201 # Abstract u'abc' syntax:
202 # Abstract u'abc' syntax:
202 @_modify_str_or_docstring
203 @_modify_str_or_docstring
203 def u_format(s):
204 def u_format(s):
204 """"{u}'abc'" --> "'abc'" (Python 3)
205 """"{u}'abc'" --> "'abc'" (Python 3)
205
206
206 Accepts a string or a function, so it can be used as a decorator."""
207 Accepts a string or a function, so it can be used as a decorator."""
207 return s.format(u='')
208 return s.format(u='')
208
209
209 def get_closure(f):
210 def get_closure(f):
210 """Get a function's closure attribute"""
211 """Get a function's closure attribute"""
211 return f.__closure__
212 return f.__closure__
212
213
213 else:
214 else:
214 PY3 = False
215 PY3 = False
215
216
216 # keep reference to builtin_mod because the kernel overrides that value
217 # keep reference to builtin_mod because the kernel overrides that value
217 # to forward requests to a frontend.
218 # to forward requests to a frontend.
218 def input(prompt=''):
219 def input(prompt=''):
219 return builtin_mod.raw_input(prompt)
220 return builtin_mod.raw_input(prompt)
220
221
221 builtin_mod_name = "__builtin__"
222 builtin_mod_name = "__builtin__"
222 import __builtin__ as builtin_mod
223 import __builtin__ as builtin_mod
223
224
224 str_to_unicode = decode
225 str_to_unicode = decode
225 unicode_to_str = encode
226 unicode_to_str = encode
226 str_to_bytes = no_code
227 str_to_bytes = no_code
227 bytes_to_str = no_code
228 bytes_to_str = no_code
228 cast_bytes_py2 = cast_bytes
229 cast_bytes_py2 = cast_bytes
229 cast_unicode_py2 = cast_unicode
230 cast_unicode_py2 = cast_unicode
230 buffer_to_bytes_py2 = buffer_to_bytes
231 buffer_to_bytes_py2 = buffer_to_bytes
231
232
232 string_types = (str, unicode)
233 string_types = (str, unicode)
233 unicode_type = unicode
234 unicode_type = unicode
234
235
235 import re
236 import re
236 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
237 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
237 def isidentifier(s, dotted=False):
238 def isidentifier(s, dotted=False):
238 if dotted:
239 if dotted:
239 return all(isidentifier(a) for a in s.split("."))
240 return all(isidentifier(a) for a in s.split("."))
240 return bool(_name_re.match(s))
241 return bool(_name_re.match(s))
241
242
242 xrange = xrange
243 xrange = xrange
243 def iteritems(d): return d.iteritems()
244 def iteritems(d): return d.iteritems()
244 def itervalues(d): return d.itervalues()
245 def itervalues(d): return d.itervalues()
245 getcwd = os.getcwdu
246 getcwd = os.getcwdu
246
247
247 def MethodType(func, instance):
248 def MethodType(func, instance):
248 return types.MethodType(func, instance, type(instance))
249 return types.MethodType(func, instance, type(instance))
249
250
250 def doctest_refactor_print(func_or_str):
251 def doctest_refactor_print(func_or_str):
251 return func_or_str
252 return func_or_str
252
253
253 def get_closure(f):
254 def get_closure(f):
254 """Get a function's closure attribute"""
255 """Get a function's closure attribute"""
255 return f.func_closure
256 return f.func_closure
256
257
257 which = _shutil_which
258 which = _shutil_which
258
259
259 # Abstract u'abc' syntax:
260 # Abstract u'abc' syntax:
260 @_modify_str_or_docstring
261 @_modify_str_or_docstring
261 def u_format(s):
262 def u_format(s):
262 """"{u}'abc'" --> "u'abc'" (Python 2)
263 """"{u}'abc'" --> "u'abc'" (Python 2)
263
264
264 Accepts a string or a function, so it can be used as a decorator."""
265 Accepts a string or a function, so it can be used as a decorator."""
265 return s.format(u='u')
266 return s.format(u='u')
266
267
267 if sys.platform == 'win32':
268 if sys.platform == 'win32':
268 def execfile(fname, glob=None, loc=None, compiler=None):
269 def execfile(fname, glob=None, loc=None, compiler=None):
269 loc = loc if (loc is not None) else glob
270 loc = loc if (loc is not None) else glob
270 scripttext = builtin_mod.open(fname).read()+ '\n'
271 scripttext = builtin_mod.open(fname).read()+ '\n'
271 # compile converts unicode filename to str assuming
272 # compile converts unicode filename to str assuming
272 # ascii. Let's do the conversion before calling compile
273 # ascii. Let's do the conversion before calling compile
273 if isinstance(fname, unicode):
274 if isinstance(fname, unicode):
274 filename = unicode_to_str(fname)
275 filename = unicode_to_str(fname)
275 else:
276 else:
276 filename = fname
277 filename = fname
277 compiler = compiler or compile
278 compiler = compiler or compile
278 exec(compiler(scripttext, filename, 'exec'), glob, loc)
279 exec(compiler(scripttext, filename, 'exec'), glob, loc)
279
280
280 else:
281 else:
281 def execfile(fname, glob=None, loc=None, compiler=None):
282 def execfile(fname, glob=None, loc=None, compiler=None):
282 if isinstance(fname, unicode):
283 if isinstance(fname, unicode):
283 filename = fname.encode(sys.getfilesystemencoding())
284 filename = fname.encode(sys.getfilesystemencoding())
284 else:
285 else:
285 filename = fname
286 filename = fname
286 where = [ns for ns in [glob, loc] if ns is not None]
287 where = [ns for ns in [glob, loc] if ns is not None]
287 if compiler is None:
288 if compiler is None:
288 builtin_mod.execfile(filename, *where)
289 builtin_mod.execfile(filename, *where)
289 else:
290 else:
290 scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
291 scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
291 exec(compiler(scripttext, filename, 'exec'), glob, loc)
292 exec(compiler(scripttext, filename, 'exec'), glob, loc)
292
293
293
294
294 PY2 = not PY3
295 PY2 = not PY3
296 PYPY = platform.python_implementation() == "PyPy"
295
297
296
298
297 def annotate(**kwargs):
299 def annotate(**kwargs):
298 """Python 3 compatible function annotation for Python 2."""
300 """Python 3 compatible function annotation for Python 2."""
299 if not kwargs:
301 if not kwargs:
300 raise ValueError('annotations must be provided as keyword arguments')
302 raise ValueError('annotations must be provided as keyword arguments')
301 def dec(f):
303 def dec(f):
302 if hasattr(f, '__annotations__'):
304 if hasattr(f, '__annotations__'):
303 for k, v in kwargs.items():
305 for k, v in kwargs.items():
304 f.__annotations__[k] = v
306 f.__annotations__[k] = v
305 else:
307 else:
306 f.__annotations__ = kwargs
308 f.__annotations__ = kwargs
307 return f
309 return f
308 return dec
310 return dec
309
311
310
312
311 # Parts below taken from six:
313 # Parts below taken from six:
312 # Copyright (c) 2010-2013 Benjamin Peterson
314 # Copyright (c) 2010-2013 Benjamin Peterson
313 #
315 #
314 # Permission is hereby granted, free of charge, to any person obtaining a copy
316 # Permission is hereby granted, free of charge, to any person obtaining a copy
315 # of this software and associated documentation files (the "Software"), to deal
317 # of this software and associated documentation files (the "Software"), to deal
316 # in the Software without restriction, including without limitation the rights
318 # in the Software without restriction, including without limitation the rights
317 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
319 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
318 # copies of the Software, and to permit persons to whom the Software is
320 # copies of the Software, and to permit persons to whom the Software is
319 # furnished to do so, subject to the following conditions:
321 # furnished to do so, subject to the following conditions:
320 #
322 #
321 # The above copyright notice and this permission notice shall be included in all
323 # The above copyright notice and this permission notice shall be included in all
322 # copies or substantial portions of the Software.
324 # copies or substantial portions of the Software.
323 #
325 #
324 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
326 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
325 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
327 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
326 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
328 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
327 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
329 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
328 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
330 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
329 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
331 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
330 # SOFTWARE.
332 # SOFTWARE.
331
333
332 def with_metaclass(meta, *bases):
334 def with_metaclass(meta, *bases):
333 """Create a base class with a metaclass."""
335 """Create a base class with a metaclass."""
334 return meta("_NewBase", bases, {})
336 return meta("_NewBase", bases, {})
@@ -1,44 +1,28 b''
1 # Tox (http://tox.testrun.org/) is a tool for running tests
1 ; Tox (http://tox.testrun.org/) is a virtualenv manager for running tests in
2 # in multiple virtualenvs. This configuration file will run the
2 ; multiple environments. This configuration file gets the requirements from
3 # test suite on all supported python versions. To use it, "pip install tox"
3 ; setup.py like a "pip install ipython[test]". To create the environments, it
4 # and then run "tox" from this directory.
4 ; requires every interpreter available/installed.
5
5 ; -- Commands --
6 # Building the source distribution requires `invoke` and `lessc` to be on your PATH.
6 ; pip install tox # Installs tox
7 # "pip install invoke" will install invoke. Less can be installed by
7 ; tox # Runs the tests (call from the directory with tox.ini)
8 # node.js' (http://nodejs.org/) package manager npm:
8 ; tox -r # Ditto, but forcing the virtual environments to be rebuilt
9 # "npm install -g less".
9 ; tox -e py35,pypy # Runs only in the selected environments
10
10 ; tox -- --all -j # Runs "iptest --all -j" in every environment
11 # Javascript tests need additional dependencies that can be installed
12 # using node.js' package manager npm:
13 # [*] casperjs: "npm install -g casperjs"
14 # [*] slimerjs: "npm install -g slimerjs"
15 # [*] phantomjs: "npm install -g phantomjs"
16
17 # Note: qt4 versions break some tests with tornado versions >=4.0.
18
11
19 [tox]
12 [tox]
20 envlist = py27, py33, py34
13 envlist = py{36,35,34,33,27,py}
14 skip_missing_interpreters = True
15 toxworkdir = /tmp/tox_ipython
21
16
22 [testenv]
17 [testenv]
18 ; PyPy requires its Numpy fork instead of "pip install numpy"
19 ; Other IPython/testing dependencies should be in setup.py, not here
23 deps =
20 deps =
24 pyzmq
21 pypy: https://bitbucket.org/pypy/numpy/get/master.zip
25 nose
22 py{36,35,34,33,27}: matplotlib
26 tornado<4.0
23 .[test]
27 jinja2
28 sphinx
29 pygments
30 jsonpointer
31 jsonschema
32 mistune
33
24
34 # To avoid loading IPython module in the current directory, change
25 ; It's just to avoid loading the IPython package in the current directory
35 # current directory to ".tox/py*/tmp" before running test.
36 changedir = {envtmpdir}
26 changedir = {envtmpdir}
37
27
38 commands =
28 commands = iptest {posargs}
39 iptest --all
40
41 [testenv:py27]
42 deps=
43 mock
44 {[testenv]deps}
General Comments 0
You need to be logged in to leave comments. Login now