Show More
@@ -0,0 +1,51 b'' | |||||
|
1 | """Tests for IPython.core.ultratb | |||
|
2 | """ | |||
|
3 | ||||
|
4 | import os.path | |||
|
5 | import unittest | |||
|
6 | ||||
|
7 | from IPython.testing import tools as tt | |||
|
8 | from IPython.utils.syspathcontext import prepended_to_syspath | |||
|
9 | from IPython.utils.tempdir import TemporaryDirectory | |||
|
10 | ||||
|
11 | ip = get_ipython() | |||
|
12 | ||||
|
13 | file_1 = """1 | |||
|
14 | 2 | |||
|
15 | 3 | |||
|
16 | def f(): | |||
|
17 | 1/0 | |||
|
18 | """ | |||
|
19 | ||||
|
20 | file_2 = """def f(): | |||
|
21 | 1/0 | |||
|
22 | """ | |||
|
23 | ||||
|
24 | class ChangedPyFileTest(unittest.TestCase): | |||
|
25 | def test_changing_py_file(self): | |||
|
26 | """Traceback produced if the line where the error occurred is missing? | |||
|
27 | ||||
|
28 | https://github.com/ipython/ipython/issues/1456 | |||
|
29 | """ | |||
|
30 | with TemporaryDirectory() as td: | |||
|
31 | fname = os.path.join(td, "foo.py") | |||
|
32 | with open(fname, "w") as f: | |||
|
33 | f.write(file_1) | |||
|
34 | ||||
|
35 | with prepended_to_syspath(td): | |||
|
36 | ip.run_cell("import foo") | |||
|
37 | ||||
|
38 | with tt.AssertPrints("ZeroDivisionError"): | |||
|
39 | ip.run_cell("foo.f()") | |||
|
40 | ||||
|
41 | # Make the file shorter, so the line of the error is missing. | |||
|
42 | with open(fname, "w") as f: | |||
|
43 | f.write(file_2) | |||
|
44 | ||||
|
45 | # For some reason, this was failing on the *second* call after | |||
|
46 | # changing the file, so we call f() twice. | |||
|
47 | with tt.AssertNotPrints("Internal Python error", channel='stderr'): | |||
|
48 | with tt.AssertPrints("ZeroDivisionError"): | |||
|
49 | ip.run_cell("foo.f()") | |||
|
50 | with tt.AssertPrints("ZeroDivisionError"): | |||
|
51 | ip.run_cell("foo.f()") |
@@ -1,1245 +1,1238 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | ultratb.py -- Spice up your tracebacks! |
|
3 | ultratb.py -- Spice up your tracebacks! | |
4 |
|
4 | |||
5 | * ColorTB |
|
5 | * ColorTB | |
6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
6 | I've always found it a bit hard to visually parse tracebacks in Python. The | |
7 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
7 | ColorTB class is a solution to that problem. It colors the different parts of a | |
8 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
8 | traceback in a manner similar to what you would expect from a syntax-highlighting | |
9 | text editor. |
|
9 | text editor. | |
10 |
|
10 | |||
11 | Installation instructions for ColorTB: |
|
11 | Installation instructions for ColorTB: | |
12 | import sys,ultratb |
|
12 | import sys,ultratb | |
13 | sys.excepthook = ultratb.ColorTB() |
|
13 | sys.excepthook = ultratb.ColorTB() | |
14 |
|
14 | |||
15 | * VerboseTB |
|
15 | * VerboseTB | |
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds | |
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML | |
18 | and intended it for CGI programmers, but why should they have all the fun? I |
|
18 | and intended it for CGI programmers, but why should they have all the fun? I | |
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, | |
20 | but kind of neat, and maybe useful for long-running programs that you believe |
|
20 | but kind of neat, and maybe useful for long-running programs that you believe | |
21 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
21 | are bug-free. If a crash *does* occur in that type of program you want details. | |
22 | Give it a shot--you'll love it or you'll hate it. |
|
22 | Give it a shot--you'll love it or you'll hate it. | |
23 |
|
23 | |||
24 | Note: |
|
24 | Note: | |
25 |
|
25 | |||
26 | The Verbose mode prints the variables currently visible where the exception |
|
26 | The Verbose mode prints the variables currently visible where the exception | |
27 | happened (shortening their strings if too long). This can potentially be |
|
27 | happened (shortening their strings if too long). This can potentially be | |
28 | very slow, if you happen to have a huge data structure whose string |
|
28 | very slow, if you happen to have a huge data structure whose string | |
29 | representation is complex to compute. Your computer may appear to freeze for |
|
29 | representation is complex to compute. Your computer may appear to freeze for | |
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback | |
31 | with Ctrl-C (maybe hitting it more than once). |
|
31 | with Ctrl-C (maybe hitting it more than once). | |
32 |
|
32 | |||
33 | If you encounter this kind of situation often, you may want to use the |
|
33 | If you encounter this kind of situation often, you may want to use the | |
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting | |
35 | variables (but otherwise includes the information and context given by |
|
35 | variables (but otherwise includes the information and context given by | |
36 | Verbose). |
|
36 | Verbose). | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | Installation instructions for ColorTB: |
|
39 | Installation instructions for ColorTB: | |
40 | import sys,ultratb |
|
40 | import sys,ultratb | |
41 | sys.excepthook = ultratb.VerboseTB() |
|
41 | sys.excepthook = ultratb.VerboseTB() | |
42 |
|
42 | |||
43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
43 | Note: Much of the code in this module was lifted verbatim from the standard | |
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. | |
45 |
|
45 | |||
46 | * Color schemes |
|
46 | * Color schemes | |
47 | The colors are defined in the class TBTools through the use of the |
|
47 | The colors are defined in the class TBTools through the use of the | |
48 | ColorSchemeTable class. Currently the following exist: |
|
48 | ColorSchemeTable class. Currently the following exist: | |
49 |
|
49 | |||
50 | - NoColor: allows all of this module to be used in any terminal (the color |
|
50 | - NoColor: allows all of this module to be used in any terminal (the color | |
51 | escapes are just dummy blank strings). |
|
51 | escapes are just dummy blank strings). | |
52 |
|
52 | |||
53 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
53 | - Linux: is meant to look good in a terminal like the Linux console (black | |
54 | or very dark background). |
|
54 | or very dark background). | |
55 |
|
55 | |||
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable | |
57 | in light background terminals. |
|
57 | in light background terminals. | |
58 |
|
58 | |||
59 | You can implement other color schemes easily, the syntax is fairly |
|
59 | You can implement other color schemes easily, the syntax is fairly | |
60 | self-explanatory. Please send back new schemes you develop to the author for |
|
60 | self-explanatory. Please send back new schemes you develop to the author for | |
61 | possible inclusion in future releases. |
|
61 | possible inclusion in future releases. | |
62 | """ |
|
62 | """ | |
63 |
|
63 | |||
64 | #***************************************************************************** |
|
64 | #***************************************************************************** | |
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> | |
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
67 | # |
|
67 | # | |
68 | # Distributed under the terms of the BSD License. The full license is in |
|
68 | # Distributed under the terms of the BSD License. The full license is in | |
69 | # the file COPYING, distributed as part of this software. |
|
69 | # the file COPYING, distributed as part of this software. | |
70 | #***************************************************************************** |
|
70 | #***************************************************************************** | |
71 |
|
71 | |||
72 | from __future__ import with_statement |
|
72 | from __future__ import with_statement | |
73 |
|
73 | |||
74 | import inspect |
|
74 | import inspect | |
75 | import keyword |
|
75 | import keyword | |
76 | import linecache |
|
76 | import linecache | |
77 | import os |
|
77 | import os | |
78 | import pydoc |
|
78 | import pydoc | |
79 | import re |
|
79 | import re | |
80 | import sys |
|
80 | import sys | |
81 | import time |
|
81 | import time | |
82 | import tokenize |
|
82 | import tokenize | |
83 | import traceback |
|
83 | import traceback | |
84 | import types |
|
84 | import types | |
85 |
|
85 | |||
86 | try: # Python 2 |
|
86 | try: # Python 2 | |
87 | generate_tokens = tokenize.generate_tokens |
|
87 | generate_tokens = tokenize.generate_tokens | |
88 | except AttributeError: # Python 3 |
|
88 | except AttributeError: # Python 3 | |
89 | generate_tokens = tokenize.tokenize |
|
89 | generate_tokens = tokenize.tokenize | |
90 |
|
90 | |||
91 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
91 | # For purposes of monkeypatching inspect to fix a bug in it. | |
92 | from inspect import getsourcefile, getfile, getmodule,\ |
|
92 | from inspect import getsourcefile, getfile, getmodule,\ | |
93 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
93 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode | |
94 |
|
94 | |||
95 | # IPython's own modules |
|
95 | # IPython's own modules | |
96 | # Modified pdb which doesn't damage IPython's readline handling |
|
96 | # Modified pdb which doesn't damage IPython's readline handling | |
97 | from IPython.core import debugger, ipapi |
|
97 | from IPython.core import debugger, ipapi | |
98 | from IPython.core.display_trap import DisplayTrap |
|
98 | from IPython.core.display_trap import DisplayTrap | |
99 | from IPython.core.excolors import exception_colors |
|
99 | from IPython.core.excolors import exception_colors | |
100 | from IPython.utils import PyColorize |
|
100 | from IPython.utils import PyColorize | |
101 | from IPython.utils import io |
|
101 | from IPython.utils import io | |
102 | from IPython.utils import py3compat |
|
102 | from IPython.utils import py3compat | |
103 | from IPython.utils import pyfile |
|
103 | from IPython.utils import pyfile | |
104 | from IPython.utils.data import uniq_stable |
|
104 | from IPython.utils.data import uniq_stable | |
105 | from IPython.utils.warn import info, error |
|
105 | from IPython.utils.warn import info, error | |
106 |
|
106 | |||
107 | # Globals |
|
107 | # Globals | |
108 | # amount of space to put line numbers before verbose tracebacks |
|
108 | # amount of space to put line numbers before verbose tracebacks | |
109 | INDENT_SIZE = 8 |
|
109 | INDENT_SIZE = 8 | |
110 |
|
110 | |||
111 | # Default color scheme. This is used, for example, by the traceback |
|
111 | # Default color scheme. This is used, for example, by the traceback | |
112 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
112 | # formatter. When running in an actual IPython instance, the user's rc.colors | |
113 | # value is used, but havinga module global makes this functionality available |
|
113 | # value is used, but havinga module global makes this functionality available | |
114 | # to users of ultratb who are NOT running inside ipython. |
|
114 | # to users of ultratb who are NOT running inside ipython. | |
115 | DEFAULT_SCHEME = 'NoColor' |
|
115 | DEFAULT_SCHEME = 'NoColor' | |
116 |
|
116 | |||
117 | #--------------------------------------------------------------------------- |
|
117 | #--------------------------------------------------------------------------- | |
118 | # Code begins |
|
118 | # Code begins | |
119 |
|
119 | |||
120 | # Utility functions |
|
120 | # Utility functions | |
121 | def inspect_error(): |
|
121 | def inspect_error(): | |
122 | """Print a message about internal inspect errors. |
|
122 | """Print a message about internal inspect errors. | |
123 |
|
123 | |||
124 | These are unfortunately quite common.""" |
|
124 | These are unfortunately quite common.""" | |
125 |
|
125 | |||
126 | error('Internal Python error in the inspect module.\n' |
|
126 | error('Internal Python error in the inspect module.\n' | |
127 | 'Below is the traceback from this internal error.\n') |
|
127 | 'Below is the traceback from this internal error.\n') | |
128 |
|
128 | |||
129 |
|
129 | # This function is a monkeypatch we apply to the Python inspect module. We have | ||
130 | # N.B. This function is a monkeypatch we are currently not applying. |
|
130 | # now found when it's needed (see discussion on issue gh-1456), and we have a | |
131 | # It was written some time ago, to fix an apparent Python bug with |
|
131 | # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if | |
132 | # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions |
|
132 | # the monkeypatch is not applied. TK, Aug 2012. | |
133 | # the bug occurred, so we can't tell if it has been fixed. If it reappears, we |
|
|||
134 | # will apply the monkeypatch again. Also, note that findsource() is not called |
|
|||
135 | # by our code at this time - we don't know if it was when the monkeypatch was |
|
|||
136 | # written, or if the monkeypatch is needed for some other code (like a debugger). |
|
|||
137 | # For the discussion about not applying it, see gh-1229. TK, Jan 2011. |
|
|||
138 | def findsource(object): |
|
133 | def findsource(object): | |
139 | """Return the entire source file and starting line number for an object. |
|
134 | """Return the entire source file and starting line number for an object. | |
140 |
|
135 | |||
141 | The argument may be a module, class, method, function, traceback, frame, |
|
136 | The argument may be a module, class, method, function, traceback, frame, | |
142 | or code object. The source code is returned as a list of all the lines |
|
137 | or code object. The source code is returned as a list of all the lines | |
143 | in the file and the line number indexes a line in that list. An IOError |
|
138 | in the file and the line number indexes a line in that list. An IOError | |
144 | is raised if the source code cannot be retrieved. |
|
139 | is raised if the source code cannot be retrieved. | |
145 |
|
140 | |||
146 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
141 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" | |
147 |
|
142 | |||
148 | file = getsourcefile(object) or getfile(object) |
|
143 | file = getsourcefile(object) or getfile(object) | |
149 | # If the object is a frame, then trying to get the globals dict from its |
|
144 | # If the object is a frame, then trying to get the globals dict from its | |
150 | # module won't work. Instead, the frame object itself has the globals |
|
145 | # module won't work. Instead, the frame object itself has the globals | |
151 | # dictionary. |
|
146 | # dictionary. | |
152 | globals_dict = None |
|
147 | globals_dict = None | |
153 | if inspect.isframe(object): |
|
148 | if inspect.isframe(object): | |
154 | # XXX: can this ever be false? |
|
149 | # XXX: can this ever be false? | |
155 | globals_dict = object.f_globals |
|
150 | globals_dict = object.f_globals | |
156 | else: |
|
151 | else: | |
157 | module = getmodule(object, file) |
|
152 | module = getmodule(object, file) | |
158 | if module: |
|
153 | if module: | |
159 | globals_dict = module.__dict__ |
|
154 | globals_dict = module.__dict__ | |
160 | lines = linecache.getlines(file, globals_dict) |
|
155 | lines = linecache.getlines(file, globals_dict) | |
161 | if not lines: |
|
156 | if not lines: | |
162 | raise IOError('could not get source code') |
|
157 | raise IOError('could not get source code') | |
163 |
|
158 | |||
164 | if ismodule(object): |
|
159 | if ismodule(object): | |
165 | return lines, 0 |
|
160 | return lines, 0 | |
166 |
|
161 | |||
167 | if isclass(object): |
|
162 | if isclass(object): | |
168 | name = object.__name__ |
|
163 | name = object.__name__ | |
169 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
164 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') | |
170 | # make some effort to find the best matching class definition: |
|
165 | # make some effort to find the best matching class definition: | |
171 | # use the one with the least indentation, which is the one |
|
166 | # use the one with the least indentation, which is the one | |
172 | # that's most probably not inside a function definition. |
|
167 | # that's most probably not inside a function definition. | |
173 | candidates = [] |
|
168 | candidates = [] | |
174 | for i in range(len(lines)): |
|
169 | for i in range(len(lines)): | |
175 | match = pat.match(lines[i]) |
|
170 | match = pat.match(lines[i]) | |
176 | if match: |
|
171 | if match: | |
177 | # if it's at toplevel, it's already the best one |
|
172 | # if it's at toplevel, it's already the best one | |
178 | if lines[i][0] == 'c': |
|
173 | if lines[i][0] == 'c': | |
179 | return lines, i |
|
174 | return lines, i | |
180 | # else add whitespace to candidate list |
|
175 | # else add whitespace to candidate list | |
181 | candidates.append((match.group(1), i)) |
|
176 | candidates.append((match.group(1), i)) | |
182 | if candidates: |
|
177 | if candidates: | |
183 | # this will sort by whitespace, and by line number, |
|
178 | # this will sort by whitespace, and by line number, | |
184 | # less whitespace first |
|
179 | # less whitespace first | |
185 | candidates.sort() |
|
180 | candidates.sort() | |
186 | return lines, candidates[0][1] |
|
181 | return lines, candidates[0][1] | |
187 | else: |
|
182 | else: | |
188 | raise IOError('could not find class definition') |
|
183 | raise IOError('could not find class definition') | |
189 |
|
184 | |||
190 | if ismethod(object): |
|
185 | if ismethod(object): | |
191 | object = object.im_func |
|
186 | object = object.im_func | |
192 | if isfunction(object): |
|
187 | if isfunction(object): | |
193 | object = object.func_code |
|
188 | object = object.func_code | |
194 | if istraceback(object): |
|
189 | if istraceback(object): | |
195 | object = object.tb_frame |
|
190 | object = object.tb_frame | |
196 | if isframe(object): |
|
191 | if isframe(object): | |
197 | object = object.f_code |
|
192 | object = object.f_code | |
198 | if iscode(object): |
|
193 | if iscode(object): | |
199 | if not hasattr(object, 'co_firstlineno'): |
|
194 | if not hasattr(object, 'co_firstlineno'): | |
200 | raise IOError('could not find function definition') |
|
195 | raise IOError('could not find function definition') | |
201 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
196 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') | |
202 | pmatch = pat.match |
|
197 | pmatch = pat.match | |
203 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
198 | # fperez - fix: sometimes, co_firstlineno can give a number larger than | |
204 | # the length of lines, which causes an error. Safeguard against that. |
|
199 | # the length of lines, which causes an error. Safeguard against that. | |
205 | lnum = min(object.co_firstlineno,len(lines))-1 |
|
200 | lnum = min(object.co_firstlineno,len(lines))-1 | |
206 | while lnum > 0: |
|
201 | while lnum > 0: | |
207 | if pmatch(lines[lnum]): break |
|
202 | if pmatch(lines[lnum]): break | |
208 | lnum -= 1 |
|
203 | lnum -= 1 | |
209 |
|
204 | |||
210 | return lines, lnum |
|
205 | return lines, lnum | |
211 | raise IOError('could not find code object') |
|
206 | raise IOError('could not find code object') | |
212 |
|
207 | |||
213 | # Not applying the monkeypatch - see above the function for details. TK, Jan 2012 |
|
208 | # Monkeypatch inspect to apply our bugfix. This code only works with Python >= 2.5 | |
214 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 |
|
209 | inspect.findsource = findsource | |
215 | #if sys.version_info[:2] >= (2,5): |
|
|||
216 | # inspect.findsource = findsource |
|
|||
217 |
|
210 | |||
218 | def fix_frame_records_filenames(records): |
|
211 | def fix_frame_records_filenames(records): | |
219 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
212 | """Try to fix the filenames in each record from inspect.getinnerframes(). | |
220 |
|
213 | |||
221 | Particularly, modules loaded from within zip files have useless filenames |
|
214 | Particularly, modules loaded from within zip files have useless filenames | |
222 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
215 | attached to their code object, and inspect.getinnerframes() just uses it. | |
223 | """ |
|
216 | """ | |
224 | fixed_records = [] |
|
217 | fixed_records = [] | |
225 | for frame, filename, line_no, func_name, lines, index in records: |
|
218 | for frame, filename, line_no, func_name, lines, index in records: | |
226 | # Look inside the frame's globals dictionary for __file__, which should |
|
219 | # Look inside the frame's globals dictionary for __file__, which should | |
227 | # be better. |
|
220 | # be better. | |
228 | better_fn = frame.f_globals.get('__file__', None) |
|
221 | better_fn = frame.f_globals.get('__file__', None) | |
229 | if isinstance(better_fn, str): |
|
222 | if isinstance(better_fn, str): | |
230 | # Check the type just in case someone did something weird with |
|
223 | # Check the type just in case someone did something weird with | |
231 | # __file__. It might also be None if the error occurred during |
|
224 | # __file__. It might also be None if the error occurred during | |
232 | # import. |
|
225 | # import. | |
233 | filename = better_fn |
|
226 | filename = better_fn | |
234 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
227 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) | |
235 | return fixed_records |
|
228 | return fixed_records | |
236 |
|
229 | |||
237 |
|
230 | |||
238 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): |
|
231 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): | |
239 | import linecache |
|
232 | import linecache | |
240 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
233 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 | |
241 |
|
234 | |||
242 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
235 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) | |
243 |
|
236 | |||
244 | # If the error is at the console, don't build any context, since it would |
|
237 | # If the error is at the console, don't build any context, since it would | |
245 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
238 | # otherwise produce 5 blank lines printed out (there is no file at the | |
246 | # console) |
|
239 | # console) | |
247 | rec_check = records[tb_offset:] |
|
240 | rec_check = records[tb_offset:] | |
248 | try: |
|
241 | try: | |
249 | rname = rec_check[0][1] |
|
242 | rname = rec_check[0][1] | |
250 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
243 | if rname == '<ipython console>' or rname.endswith('<string>'): | |
251 | return rec_check |
|
244 | return rec_check | |
252 | except IndexError: |
|
245 | except IndexError: | |
253 | pass |
|
246 | pass | |
254 |
|
247 | |||
255 | aux = traceback.extract_tb(etb) |
|
248 | aux = traceback.extract_tb(etb) | |
256 | assert len(records) == len(aux) |
|
249 | assert len(records) == len(aux) | |
257 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
250 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): | |
258 | maybeStart = lnum-1 - context//2 |
|
251 | maybeStart = lnum-1 - context//2 | |
259 | start = max(maybeStart, 0) |
|
252 | start = max(maybeStart, 0) | |
260 | end = start + context |
|
253 | end = start + context | |
261 | lines = linecache.getlines(file)[start:end] |
|
254 | lines = linecache.getlines(file)[start:end] | |
262 | buf = list(records[i]) |
|
255 | buf = list(records[i]) | |
263 | buf[LNUM_POS] = lnum |
|
256 | buf[LNUM_POS] = lnum | |
264 | buf[INDEX_POS] = lnum - 1 - start |
|
257 | buf[INDEX_POS] = lnum - 1 - start | |
265 | buf[LINES_POS] = lines |
|
258 | buf[LINES_POS] = lines | |
266 | records[i] = tuple(buf) |
|
259 | records[i] = tuple(buf) | |
267 | return records[tb_offset:] |
|
260 | return records[tb_offset:] | |
268 |
|
261 | |||
269 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
262 | # Helper function -- largely belongs to VerboseTB, but we need the same | |
270 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
263 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they | |
271 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
264 | # can be recognized properly by ipython.el's py-traceback-line-re | |
272 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
265 | # (SyntaxErrors have to be treated specially because they have no traceback) | |
273 |
|
266 | |||
274 | _parser = PyColorize.Parser() |
|
267 | _parser = PyColorize.Parser() | |
275 |
|
268 | |||
276 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): |
|
269 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): | |
277 | numbers_width = INDENT_SIZE - 1 |
|
270 | numbers_width = INDENT_SIZE - 1 | |
278 | res = [] |
|
271 | res = [] | |
279 | i = lnum - index |
|
272 | i = lnum - index | |
280 |
|
273 | |||
281 | # This lets us get fully syntax-highlighted tracebacks. |
|
274 | # This lets us get fully syntax-highlighted tracebacks. | |
282 | if scheme is None: |
|
275 | if scheme is None: | |
283 | ipinst = ipapi.get() |
|
276 | ipinst = ipapi.get() | |
284 | if ipinst is not None: |
|
277 | if ipinst is not None: | |
285 | scheme = ipinst.colors |
|
278 | scheme = ipinst.colors | |
286 | else: |
|
279 | else: | |
287 | scheme = DEFAULT_SCHEME |
|
280 | scheme = DEFAULT_SCHEME | |
288 |
|
281 | |||
289 | _line_format = _parser.format2 |
|
282 | _line_format = _parser.format2 | |
290 |
|
283 | |||
291 | for line in lines: |
|
284 | for line in lines: | |
292 | # FIXME: we need to ensure the source is a pure string at this point, |
|
285 | # FIXME: we need to ensure the source is a pure string at this point, | |
293 | # else the coloring code makes a royal mess. This is in need of a |
|
286 | # else the coloring code makes a royal mess. This is in need of a | |
294 | # serious refactoring, so that all of the ultratb and PyColorize code |
|
287 | # serious refactoring, so that all of the ultratb and PyColorize code | |
295 | # is unicode-safe. So for now this is rather an ugly hack, but |
|
288 | # is unicode-safe. So for now this is rather an ugly hack, but | |
296 | # necessary to at least have readable tracebacks. Improvements welcome! |
|
289 | # necessary to at least have readable tracebacks. Improvements welcome! | |
297 | line = py3compat.cast_bytes_py2(line, 'utf-8') |
|
290 | line = py3compat.cast_bytes_py2(line, 'utf-8') | |
298 |
|
291 | |||
299 | new_line, err = _line_format(line, 'str', scheme) |
|
292 | new_line, err = _line_format(line, 'str', scheme) | |
300 | if not err: line = new_line |
|
293 | if not err: line = new_line | |
301 |
|
294 | |||
302 | if i == lnum: |
|
295 | if i == lnum: | |
303 | # This is the line with the error |
|
296 | # This is the line with the error | |
304 | pad = numbers_width - len(str(i)) |
|
297 | pad = numbers_width - len(str(i)) | |
305 | if pad >= 3: |
|
298 | if pad >= 3: | |
306 | marker = '-'*(pad-3) + '-> ' |
|
299 | marker = '-'*(pad-3) + '-> ' | |
307 | elif pad == 2: |
|
300 | elif pad == 2: | |
308 | marker = '> ' |
|
301 | marker = '> ' | |
309 | elif pad == 1: |
|
302 | elif pad == 1: | |
310 | marker = '>' |
|
303 | marker = '>' | |
311 | else: |
|
304 | else: | |
312 | marker = '' |
|
305 | marker = '' | |
313 | num = marker + str(i) |
|
306 | num = marker + str(i) | |
314 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, |
|
307 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, | |
315 | Colors.line, line, Colors.Normal) |
|
308 | Colors.line, line, Colors.Normal) | |
316 | else: |
|
309 | else: | |
317 | num = '%*s' % (numbers_width,i) |
|
310 | num = '%*s' % (numbers_width,i) | |
318 | line = '%s%s%s %s' %(Colors.lineno, num, |
|
311 | line = '%s%s%s %s' %(Colors.lineno, num, | |
319 | Colors.Normal, line) |
|
312 | Colors.Normal, line) | |
320 |
|
313 | |||
321 | res.append(line) |
|
314 | res.append(line) | |
322 | if lvals and i == lnum: |
|
315 | if lvals and i == lnum: | |
323 | res.append(lvals + '\n') |
|
316 | res.append(lvals + '\n') | |
324 | i = i + 1 |
|
317 | i = i + 1 | |
325 | return res |
|
318 | return res | |
326 |
|
319 | |||
327 |
|
320 | |||
328 | #--------------------------------------------------------------------------- |
|
321 | #--------------------------------------------------------------------------- | |
329 | # Module classes |
|
322 | # Module classes | |
330 | class TBTools(object): |
|
323 | class TBTools(object): | |
331 | """Basic tools used by all traceback printer classes.""" |
|
324 | """Basic tools used by all traceback printer classes.""" | |
332 |
|
325 | |||
333 | # Number of frames to skip when reporting tracebacks |
|
326 | # Number of frames to skip when reporting tracebacks | |
334 | tb_offset = 0 |
|
327 | tb_offset = 0 | |
335 |
|
328 | |||
336 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None): |
|
329 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None): | |
337 | # Whether to call the interactive pdb debugger after printing |
|
330 | # Whether to call the interactive pdb debugger after printing | |
338 | # tracebacks or not |
|
331 | # tracebacks or not | |
339 | self.call_pdb = call_pdb |
|
332 | self.call_pdb = call_pdb | |
340 |
|
333 | |||
341 | # Output stream to write to. Note that we store the original value in |
|
334 | # Output stream to write to. Note that we store the original value in | |
342 | # a private attribute and then make the public ostream a property, so |
|
335 | # a private attribute and then make the public ostream a property, so | |
343 | # that we can delay accessing io.stdout until runtime. The way |
|
336 | # that we can delay accessing io.stdout until runtime. The way | |
344 | # things are written now, the io.stdout object is dynamically managed |
|
337 | # things are written now, the io.stdout object is dynamically managed | |
345 | # so a reference to it should NEVER be stored statically. This |
|
338 | # so a reference to it should NEVER be stored statically. This | |
346 | # property approach confines this detail to a single location, and all |
|
339 | # property approach confines this detail to a single location, and all | |
347 | # subclasses can simply access self.ostream for writing. |
|
340 | # subclasses can simply access self.ostream for writing. | |
348 | self._ostream = ostream |
|
341 | self._ostream = ostream | |
349 |
|
342 | |||
350 | # Create color table |
|
343 | # Create color table | |
351 | self.color_scheme_table = exception_colors() |
|
344 | self.color_scheme_table = exception_colors() | |
352 |
|
345 | |||
353 | self.set_colors(color_scheme) |
|
346 | self.set_colors(color_scheme) | |
354 | self.old_scheme = color_scheme # save initial value for toggles |
|
347 | self.old_scheme = color_scheme # save initial value for toggles | |
355 |
|
348 | |||
356 | if call_pdb: |
|
349 | if call_pdb: | |
357 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
350 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) | |
358 | else: |
|
351 | else: | |
359 | self.pdb = None |
|
352 | self.pdb = None | |
360 |
|
353 | |||
361 | def _get_ostream(self): |
|
354 | def _get_ostream(self): | |
362 | """Output stream that exceptions are written to. |
|
355 | """Output stream that exceptions are written to. | |
363 |
|
356 | |||
364 | Valid values are: |
|
357 | Valid values are: | |
365 |
|
358 | |||
366 | - None: the default, which means that IPython will dynamically resolve |
|
359 | - None: the default, which means that IPython will dynamically resolve | |
367 | to io.stdout. This ensures compatibility with most tools, including |
|
360 | to io.stdout. This ensures compatibility with most tools, including | |
368 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
361 | Windows (where plain stdout doesn't recognize ANSI escapes). | |
369 |
|
362 | |||
370 | - Any object with 'write' and 'flush' attributes. |
|
363 | - Any object with 'write' and 'flush' attributes. | |
371 | """ |
|
364 | """ | |
372 | return io.stdout if self._ostream is None else self._ostream |
|
365 | return io.stdout if self._ostream is None else self._ostream | |
373 |
|
366 | |||
374 | def _set_ostream(self, val): |
|
367 | def _set_ostream(self, val): | |
375 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
368 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) | |
376 | self._ostream = val |
|
369 | self._ostream = val | |
377 |
|
370 | |||
378 | ostream = property(_get_ostream, _set_ostream) |
|
371 | ostream = property(_get_ostream, _set_ostream) | |
379 |
|
372 | |||
380 | def set_colors(self,*args,**kw): |
|
373 | def set_colors(self,*args,**kw): | |
381 | """Shorthand access to the color table scheme selector method.""" |
|
374 | """Shorthand access to the color table scheme selector method.""" | |
382 |
|
375 | |||
383 | # Set own color table |
|
376 | # Set own color table | |
384 | self.color_scheme_table.set_active_scheme(*args,**kw) |
|
377 | self.color_scheme_table.set_active_scheme(*args,**kw) | |
385 | # for convenience, set Colors to the active scheme |
|
378 | # for convenience, set Colors to the active scheme | |
386 | self.Colors = self.color_scheme_table.active_colors |
|
379 | self.Colors = self.color_scheme_table.active_colors | |
387 | # Also set colors of debugger |
|
380 | # Also set colors of debugger | |
388 | if hasattr(self,'pdb') and self.pdb is not None: |
|
381 | if hasattr(self,'pdb') and self.pdb is not None: | |
389 | self.pdb.set_colors(*args,**kw) |
|
382 | self.pdb.set_colors(*args,**kw) | |
390 |
|
383 | |||
391 | def color_toggle(self): |
|
384 | def color_toggle(self): | |
392 | """Toggle between the currently active color scheme and NoColor.""" |
|
385 | """Toggle between the currently active color scheme and NoColor.""" | |
393 |
|
386 | |||
394 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
387 | if self.color_scheme_table.active_scheme_name == 'NoColor': | |
395 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
388 | self.color_scheme_table.set_active_scheme(self.old_scheme) | |
396 | self.Colors = self.color_scheme_table.active_colors |
|
389 | self.Colors = self.color_scheme_table.active_colors | |
397 | else: |
|
390 | else: | |
398 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
391 | self.old_scheme = self.color_scheme_table.active_scheme_name | |
399 | self.color_scheme_table.set_active_scheme('NoColor') |
|
392 | self.color_scheme_table.set_active_scheme('NoColor') | |
400 | self.Colors = self.color_scheme_table.active_colors |
|
393 | self.Colors = self.color_scheme_table.active_colors | |
401 |
|
394 | |||
402 | def stb2text(self, stb): |
|
395 | def stb2text(self, stb): | |
403 | """Convert a structured traceback (a list) to a string.""" |
|
396 | """Convert a structured traceback (a list) to a string.""" | |
404 | return '\n'.join(stb) |
|
397 | return '\n'.join(stb) | |
405 |
|
398 | |||
406 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
399 | def text(self, etype, value, tb, tb_offset=None, context=5): | |
407 | """Return formatted traceback. |
|
400 | """Return formatted traceback. | |
408 |
|
401 | |||
409 | Subclasses may override this if they add extra arguments. |
|
402 | Subclasses may override this if they add extra arguments. | |
410 | """ |
|
403 | """ | |
411 | tb_list = self.structured_traceback(etype, value, tb, |
|
404 | tb_list = self.structured_traceback(etype, value, tb, | |
412 | tb_offset, context) |
|
405 | tb_offset, context) | |
413 | return self.stb2text(tb_list) |
|
406 | return self.stb2text(tb_list) | |
414 |
|
407 | |||
415 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
408 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, | |
416 | context=5, mode=None): |
|
409 | context=5, mode=None): | |
417 | """Return a list of traceback frames. |
|
410 | """Return a list of traceback frames. | |
418 |
|
411 | |||
419 | Must be implemented by each class. |
|
412 | Must be implemented by each class. | |
420 | """ |
|
413 | """ | |
421 | raise NotImplementedError() |
|
414 | raise NotImplementedError() | |
422 |
|
415 | |||
423 |
|
416 | |||
424 | #--------------------------------------------------------------------------- |
|
417 | #--------------------------------------------------------------------------- | |
425 | class ListTB(TBTools): |
|
418 | class ListTB(TBTools): | |
426 | """Print traceback information from a traceback list, with optional color. |
|
419 | """Print traceback information from a traceback list, with optional color. | |
427 |
|
420 | |||
428 | Calling: requires 3 arguments: |
|
421 | Calling: requires 3 arguments: | |
429 | (etype, evalue, elist) |
|
422 | (etype, evalue, elist) | |
430 | as would be obtained by: |
|
423 | as would be obtained by: | |
431 | etype, evalue, tb = sys.exc_info() |
|
424 | etype, evalue, tb = sys.exc_info() | |
432 | if tb: |
|
425 | if tb: | |
433 | elist = traceback.extract_tb(tb) |
|
426 | elist = traceback.extract_tb(tb) | |
434 | else: |
|
427 | else: | |
435 | elist = None |
|
428 | elist = None | |
436 |
|
429 | |||
437 | It can thus be used by programs which need to process the traceback before |
|
430 | It can thus be used by programs which need to process the traceback before | |
438 | printing (such as console replacements based on the code module from the |
|
431 | printing (such as console replacements based on the code module from the | |
439 | standard library). |
|
432 | standard library). | |
440 |
|
433 | |||
441 | Because they are meant to be called without a full traceback (only a |
|
434 | Because they are meant to be called without a full traceback (only a | |
442 | list), instances of this class can't call the interactive pdb debugger.""" |
|
435 | list), instances of this class can't call the interactive pdb debugger.""" | |
443 |
|
436 | |||
444 | def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None): |
|
437 | def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None): | |
445 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
438 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
446 | ostream=ostream) |
|
439 | ostream=ostream) | |
447 |
|
440 | |||
448 | def __call__(self, etype, value, elist): |
|
441 | def __call__(self, etype, value, elist): | |
449 | self.ostream.flush() |
|
442 | self.ostream.flush() | |
450 | self.ostream.write(self.text(etype, value, elist)) |
|
443 | self.ostream.write(self.text(etype, value, elist)) | |
451 | self.ostream.write('\n') |
|
444 | self.ostream.write('\n') | |
452 |
|
445 | |||
453 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
446 | def structured_traceback(self, etype, value, elist, tb_offset=None, | |
454 | context=5): |
|
447 | context=5): | |
455 | """Return a color formatted string with the traceback info. |
|
448 | """Return a color formatted string with the traceback info. | |
456 |
|
449 | |||
457 | Parameters |
|
450 | Parameters | |
458 | ---------- |
|
451 | ---------- | |
459 | etype : exception type |
|
452 | etype : exception type | |
460 | Type of the exception raised. |
|
453 | Type of the exception raised. | |
461 |
|
454 | |||
462 | value : object |
|
455 | value : object | |
463 | Data stored in the exception |
|
456 | Data stored in the exception | |
464 |
|
457 | |||
465 | elist : list |
|
458 | elist : list | |
466 | List of frames, see class docstring for details. |
|
459 | List of frames, see class docstring for details. | |
467 |
|
460 | |||
468 | tb_offset : int, optional |
|
461 | tb_offset : int, optional | |
469 | Number of frames in the traceback to skip. If not given, the |
|
462 | Number of frames in the traceback to skip. If not given, the | |
470 | instance value is used (set in constructor). |
|
463 | instance value is used (set in constructor). | |
471 |
|
464 | |||
472 | context : int, optional |
|
465 | context : int, optional | |
473 | Number of lines of context information to print. |
|
466 | Number of lines of context information to print. | |
474 |
|
467 | |||
475 | Returns |
|
468 | Returns | |
476 | ------- |
|
469 | ------- | |
477 | String with formatted exception. |
|
470 | String with formatted exception. | |
478 | """ |
|
471 | """ | |
479 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
472 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
480 | Colors = self.Colors |
|
473 | Colors = self.Colors | |
481 | out_list = [] |
|
474 | out_list = [] | |
482 | if elist: |
|
475 | if elist: | |
483 |
|
476 | |||
484 | if tb_offset and len(elist) > tb_offset: |
|
477 | if tb_offset and len(elist) > tb_offset: | |
485 | elist = elist[tb_offset:] |
|
478 | elist = elist[tb_offset:] | |
486 |
|
479 | |||
487 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
480 | out_list.append('Traceback %s(most recent call last)%s:' % | |
488 | (Colors.normalEm, Colors.Normal) + '\n') |
|
481 | (Colors.normalEm, Colors.Normal) + '\n') | |
489 | out_list.extend(self._format_list(elist)) |
|
482 | out_list.extend(self._format_list(elist)) | |
490 | # The exception info should be a single entry in the list. |
|
483 | # The exception info should be a single entry in the list. | |
491 | lines = ''.join(self._format_exception_only(etype, value)) |
|
484 | lines = ''.join(self._format_exception_only(etype, value)) | |
492 | out_list.append(lines) |
|
485 | out_list.append(lines) | |
493 |
|
486 | |||
494 | # Note: this code originally read: |
|
487 | # Note: this code originally read: | |
495 |
|
488 | |||
496 | ## for line in lines[:-1]: |
|
489 | ## for line in lines[:-1]: | |
497 | ## out_list.append(" "+line) |
|
490 | ## out_list.append(" "+line) | |
498 | ## out_list.append(lines[-1]) |
|
491 | ## out_list.append(lines[-1]) | |
499 |
|
492 | |||
500 | # This means it was indenting everything but the last line by a little |
|
493 | # This means it was indenting everything but the last line by a little | |
501 | # bit. I've disabled this for now, but if we see ugliness somewhre we |
|
494 | # bit. I've disabled this for now, but if we see ugliness somewhre we | |
502 | # can restore it. |
|
495 | # can restore it. | |
503 |
|
496 | |||
504 | return out_list |
|
497 | return out_list | |
505 |
|
498 | |||
506 | def _format_list(self, extracted_list): |
|
499 | def _format_list(self, extracted_list): | |
507 | """Format a list of traceback entry tuples for printing. |
|
500 | """Format a list of traceback entry tuples for printing. | |
508 |
|
501 | |||
509 | Given a list of tuples as returned by extract_tb() or |
|
502 | Given a list of tuples as returned by extract_tb() or | |
510 | extract_stack(), return a list of strings ready for printing. |
|
503 | extract_stack(), return a list of strings ready for printing. | |
511 | Each string in the resulting list corresponds to the item with the |
|
504 | Each string in the resulting list corresponds to the item with the | |
512 | same index in the argument list. Each string ends in a newline; |
|
505 | same index in the argument list. Each string ends in a newline; | |
513 | the strings may contain internal newlines as well, for those items |
|
506 | the strings may contain internal newlines as well, for those items | |
514 | whose source text line is not None. |
|
507 | whose source text line is not None. | |
515 |
|
508 | |||
516 | Lifted almost verbatim from traceback.py |
|
509 | Lifted almost verbatim from traceback.py | |
517 | """ |
|
510 | """ | |
518 |
|
511 | |||
519 | Colors = self.Colors |
|
512 | Colors = self.Colors | |
520 | list = [] |
|
513 | list = [] | |
521 | for filename, lineno, name, line in extracted_list[:-1]: |
|
514 | for filename, lineno, name, line in extracted_list[:-1]: | |
522 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
515 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ | |
523 | (Colors.filename, filename, Colors.Normal, |
|
516 | (Colors.filename, filename, Colors.Normal, | |
524 | Colors.lineno, lineno, Colors.Normal, |
|
517 | Colors.lineno, lineno, Colors.Normal, | |
525 | Colors.name, name, Colors.Normal) |
|
518 | Colors.name, name, Colors.Normal) | |
526 | if line: |
|
519 | if line: | |
527 | item += ' %s\n' % line.strip() |
|
520 | item += ' %s\n' % line.strip() | |
528 | list.append(item) |
|
521 | list.append(item) | |
529 | # Emphasize the last entry |
|
522 | # Emphasize the last entry | |
530 | filename, lineno, name, line = extracted_list[-1] |
|
523 | filename, lineno, name, line = extracted_list[-1] | |
531 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
524 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ | |
532 | (Colors.normalEm, |
|
525 | (Colors.normalEm, | |
533 | Colors.filenameEm, filename, Colors.normalEm, |
|
526 | Colors.filenameEm, filename, Colors.normalEm, | |
534 | Colors.linenoEm, lineno, Colors.normalEm, |
|
527 | Colors.linenoEm, lineno, Colors.normalEm, | |
535 | Colors.nameEm, name, Colors.normalEm, |
|
528 | Colors.nameEm, name, Colors.normalEm, | |
536 | Colors.Normal) |
|
529 | Colors.Normal) | |
537 | if line: |
|
530 | if line: | |
538 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
531 | item += '%s %s%s\n' % (Colors.line, line.strip(), | |
539 | Colors.Normal) |
|
532 | Colors.Normal) | |
540 | list.append(item) |
|
533 | list.append(item) | |
541 | #from pprint import pformat; print 'LISTTB', pformat(list) # dbg |
|
534 | #from pprint import pformat; print 'LISTTB', pformat(list) # dbg | |
542 | return list |
|
535 | return list | |
543 |
|
536 | |||
544 | def _format_exception_only(self, etype, value): |
|
537 | def _format_exception_only(self, etype, value): | |
545 | """Format the exception part of a traceback. |
|
538 | """Format the exception part of a traceback. | |
546 |
|
539 | |||
547 | The arguments are the exception type and value such as given by |
|
540 | The arguments are the exception type and value such as given by | |
548 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
541 | sys.exc_info()[:2]. The return value is a list of strings, each ending | |
549 | in a newline. Normally, the list contains a single string; however, |
|
542 | in a newline. Normally, the list contains a single string; however, | |
550 | for SyntaxError exceptions, it contains several lines that (when |
|
543 | for SyntaxError exceptions, it contains several lines that (when | |
551 | printed) display detailed information about where the syntax error |
|
544 | printed) display detailed information about where the syntax error | |
552 | occurred. The message indicating which exception occurred is the |
|
545 | occurred. The message indicating which exception occurred is the | |
553 | always last string in the list. |
|
546 | always last string in the list. | |
554 |
|
547 | |||
555 | Also lifted nearly verbatim from traceback.py |
|
548 | Also lifted nearly verbatim from traceback.py | |
556 | """ |
|
549 | """ | |
557 |
|
550 | |||
558 | have_filedata = False |
|
551 | have_filedata = False | |
559 | Colors = self.Colors |
|
552 | Colors = self.Colors | |
560 | list = [] |
|
553 | list = [] | |
561 | stype = Colors.excName + etype.__name__ + Colors.Normal |
|
554 | stype = Colors.excName + etype.__name__ + Colors.Normal | |
562 | if value is None: |
|
555 | if value is None: | |
563 | # Not sure if this can still happen in Python 2.6 and above |
|
556 | # Not sure if this can still happen in Python 2.6 and above | |
564 | list.append( str(stype) + '\n') |
|
557 | list.append( str(stype) + '\n') | |
565 | else: |
|
558 | else: | |
566 | if etype is SyntaxError: |
|
559 | if etype is SyntaxError: | |
567 | have_filedata = True |
|
560 | have_filedata = True | |
568 | #print 'filename is',filename # dbg |
|
561 | #print 'filename is',filename # dbg | |
569 | if not value.filename: value.filename = "<string>" |
|
562 | if not value.filename: value.filename = "<string>" | |
570 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ |
|
563 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ | |
571 | (Colors.normalEm, |
|
564 | (Colors.normalEm, | |
572 | Colors.filenameEm, value.filename, Colors.normalEm, |
|
565 | Colors.filenameEm, value.filename, Colors.normalEm, | |
573 | Colors.linenoEm, value.lineno, Colors.Normal )) |
|
566 | Colors.linenoEm, value.lineno, Colors.Normal )) | |
574 | if value.text is not None: |
|
567 | if value.text is not None: | |
575 | i = 0 |
|
568 | i = 0 | |
576 | while i < len(value.text) and value.text[i].isspace(): |
|
569 | while i < len(value.text) and value.text[i].isspace(): | |
577 | i += 1 |
|
570 | i += 1 | |
578 | list.append('%s %s%s\n' % (Colors.line, |
|
571 | list.append('%s %s%s\n' % (Colors.line, | |
579 | value.text.strip(), |
|
572 | value.text.strip(), | |
580 | Colors.Normal)) |
|
573 | Colors.Normal)) | |
581 | if value.offset is not None: |
|
574 | if value.offset is not None: | |
582 | s = ' ' |
|
575 | s = ' ' | |
583 | for c in value.text[i:value.offset-1]: |
|
576 | for c in value.text[i:value.offset-1]: | |
584 | if c.isspace(): |
|
577 | if c.isspace(): | |
585 | s += c |
|
578 | s += c | |
586 | else: |
|
579 | else: | |
587 | s += ' ' |
|
580 | s += ' ' | |
588 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
581 | list.append('%s%s^%s\n' % (Colors.caret, s, | |
589 | Colors.Normal) ) |
|
582 | Colors.Normal) ) | |
590 |
|
583 | |||
591 | try: |
|
584 | try: | |
592 | s = value.msg |
|
585 | s = value.msg | |
593 | except Exception: |
|
586 | except Exception: | |
594 | s = self._some_str(value) |
|
587 | s = self._some_str(value) | |
595 | if s: |
|
588 | if s: | |
596 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, |
|
589 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, | |
597 | Colors.Normal, s)) |
|
590 | Colors.Normal, s)) | |
598 | else: |
|
591 | else: | |
599 | list.append('%s\n' % str(stype)) |
|
592 | list.append('%s\n' % str(stype)) | |
600 |
|
593 | |||
601 | # sync with user hooks |
|
594 | # sync with user hooks | |
602 | if have_filedata: |
|
595 | if have_filedata: | |
603 | ipinst = ipapi.get() |
|
596 | ipinst = ipapi.get() | |
604 | if ipinst is not None: |
|
597 | if ipinst is not None: | |
605 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
598 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) | |
606 |
|
599 | |||
607 | return list |
|
600 | return list | |
608 |
|
601 | |||
609 | def get_exception_only(self, etype, value): |
|
602 | def get_exception_only(self, etype, value): | |
610 | """Only print the exception type and message, without a traceback. |
|
603 | """Only print the exception type and message, without a traceback. | |
611 |
|
604 | |||
612 | Parameters |
|
605 | Parameters | |
613 | ---------- |
|
606 | ---------- | |
614 | etype : exception type |
|
607 | etype : exception type | |
615 | value : exception value |
|
608 | value : exception value | |
616 | """ |
|
609 | """ | |
617 | return ListTB.structured_traceback(self, etype, value, []) |
|
610 | return ListTB.structured_traceback(self, etype, value, []) | |
618 |
|
611 | |||
619 |
|
612 | |||
620 | def show_exception_only(self, etype, evalue): |
|
613 | def show_exception_only(self, etype, evalue): | |
621 | """Only print the exception type and message, without a traceback. |
|
614 | """Only print the exception type and message, without a traceback. | |
622 |
|
615 | |||
623 | Parameters |
|
616 | Parameters | |
624 | ---------- |
|
617 | ---------- | |
625 | etype : exception type |
|
618 | etype : exception type | |
626 | value : exception value |
|
619 | value : exception value | |
627 | """ |
|
620 | """ | |
628 | # This method needs to use __call__ from *this* class, not the one from |
|
621 | # This method needs to use __call__ from *this* class, not the one from | |
629 | # a subclass whose signature or behavior may be different |
|
622 | # a subclass whose signature or behavior may be different | |
630 | ostream = self.ostream |
|
623 | ostream = self.ostream | |
631 | ostream.flush() |
|
624 | ostream.flush() | |
632 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
625 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) | |
633 | ostream.flush() |
|
626 | ostream.flush() | |
634 |
|
627 | |||
635 | def _some_str(self, value): |
|
628 | def _some_str(self, value): | |
636 | # Lifted from traceback.py |
|
629 | # Lifted from traceback.py | |
637 | try: |
|
630 | try: | |
638 | return str(value) |
|
631 | return str(value) | |
639 | except: |
|
632 | except: | |
640 | return '<unprintable %s object>' % type(value).__name__ |
|
633 | return '<unprintable %s object>' % type(value).__name__ | |
641 |
|
634 | |||
642 | #---------------------------------------------------------------------------- |
|
635 | #---------------------------------------------------------------------------- | |
643 | class VerboseTB(TBTools): |
|
636 | class VerboseTB(TBTools): | |
644 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
637 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead | |
645 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
638 | of HTML. Requires inspect and pydoc. Crazy, man. | |
646 |
|
639 | |||
647 | Modified version which optionally strips the topmost entries from the |
|
640 | Modified version which optionally strips the topmost entries from the | |
648 | traceback, to be used with alternate interpreters (because their own code |
|
641 | traceback, to be used with alternate interpreters (because their own code | |
649 | would appear in the traceback).""" |
|
642 | would appear in the traceback).""" | |
650 |
|
643 | |||
651 | def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None, |
|
644 | def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None, | |
652 | tb_offset=0, long_header=False, include_vars=True, |
|
645 | tb_offset=0, long_header=False, include_vars=True, | |
653 | check_cache=None): |
|
646 | check_cache=None): | |
654 | """Specify traceback offset, headers and color scheme. |
|
647 | """Specify traceback offset, headers and color scheme. | |
655 |
|
648 | |||
656 | Define how many frames to drop from the tracebacks. Calling it with |
|
649 | Define how many frames to drop from the tracebacks. Calling it with | |
657 | tb_offset=1 allows use of this handler in interpreters which will have |
|
650 | tb_offset=1 allows use of this handler in interpreters which will have | |
658 | their own code at the top of the traceback (VerboseTB will first |
|
651 | their own code at the top of the traceback (VerboseTB will first | |
659 | remove that frame before printing the traceback info).""" |
|
652 | remove that frame before printing the traceback info).""" | |
660 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
653 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
661 | ostream=ostream) |
|
654 | ostream=ostream) | |
662 | self.tb_offset = tb_offset |
|
655 | self.tb_offset = tb_offset | |
663 | self.long_header = long_header |
|
656 | self.long_header = long_header | |
664 | self.include_vars = include_vars |
|
657 | self.include_vars = include_vars | |
665 | # By default we use linecache.checkcache, but the user can provide a |
|
658 | # By default we use linecache.checkcache, but the user can provide a | |
666 | # different check_cache implementation. This is used by the IPython |
|
659 | # different check_cache implementation. This is used by the IPython | |
667 | # kernel to provide tracebacks for interactive code that is cached, |
|
660 | # kernel to provide tracebacks for interactive code that is cached, | |
668 | # by a compiler instance that flushes the linecache but preserves its |
|
661 | # by a compiler instance that flushes the linecache but preserves its | |
669 | # own code cache. |
|
662 | # own code cache. | |
670 | if check_cache is None: |
|
663 | if check_cache is None: | |
671 | check_cache = linecache.checkcache |
|
664 | check_cache = linecache.checkcache | |
672 | self.check_cache = check_cache |
|
665 | self.check_cache = check_cache | |
673 |
|
666 | |||
674 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
667 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, | |
675 | context=5): |
|
668 | context=5): | |
676 | """Return a nice text document describing the traceback.""" |
|
669 | """Return a nice text document describing the traceback.""" | |
677 |
|
670 | |||
678 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
671 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
679 |
|
672 | |||
680 | # some locals |
|
673 | # some locals | |
681 | try: |
|
674 | try: | |
682 | etype = etype.__name__ |
|
675 | etype = etype.__name__ | |
683 | except AttributeError: |
|
676 | except AttributeError: | |
684 | pass |
|
677 | pass | |
685 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
678 | Colors = self.Colors # just a shorthand + quicker name lookup | |
686 | ColorsNormal = Colors.Normal # used a lot |
|
679 | ColorsNormal = Colors.Normal # used a lot | |
687 | col_scheme = self.color_scheme_table.active_scheme_name |
|
680 | col_scheme = self.color_scheme_table.active_scheme_name | |
688 | indent = ' '*INDENT_SIZE |
|
681 | indent = ' '*INDENT_SIZE | |
689 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) |
|
682 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) | |
690 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
683 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) | |
691 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) |
|
684 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) | |
692 |
|
685 | |||
693 | # some internal-use functions |
|
686 | # some internal-use functions | |
694 | def text_repr(value): |
|
687 | def text_repr(value): | |
695 | """Hopefully pretty robust repr equivalent.""" |
|
688 | """Hopefully pretty robust repr equivalent.""" | |
696 | # this is pretty horrible but should always return *something* |
|
689 | # this is pretty horrible but should always return *something* | |
697 | try: |
|
690 | try: | |
698 | return pydoc.text.repr(value) |
|
691 | return pydoc.text.repr(value) | |
699 | except KeyboardInterrupt: |
|
692 | except KeyboardInterrupt: | |
700 | raise |
|
693 | raise | |
701 | except: |
|
694 | except: | |
702 | try: |
|
695 | try: | |
703 | return repr(value) |
|
696 | return repr(value) | |
704 | except KeyboardInterrupt: |
|
697 | except KeyboardInterrupt: | |
705 | raise |
|
698 | raise | |
706 | except: |
|
699 | except: | |
707 | try: |
|
700 | try: | |
708 | # all still in an except block so we catch |
|
701 | # all still in an except block so we catch | |
709 | # getattr raising |
|
702 | # getattr raising | |
710 | name = getattr(value, '__name__', None) |
|
703 | name = getattr(value, '__name__', None) | |
711 | if name: |
|
704 | if name: | |
712 | # ick, recursion |
|
705 | # ick, recursion | |
713 | return text_repr(name) |
|
706 | return text_repr(name) | |
714 | klass = getattr(value, '__class__', None) |
|
707 | klass = getattr(value, '__class__', None) | |
715 | if klass: |
|
708 | if klass: | |
716 | return '%s instance' % text_repr(klass) |
|
709 | return '%s instance' % text_repr(klass) | |
717 | except KeyboardInterrupt: |
|
710 | except KeyboardInterrupt: | |
718 | raise |
|
711 | raise | |
719 | except: |
|
712 | except: | |
720 | return 'UNRECOVERABLE REPR FAILURE' |
|
713 | return 'UNRECOVERABLE REPR FAILURE' | |
721 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) |
|
714 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) | |
722 | def nullrepr(value, repr=text_repr): return '' |
|
715 | def nullrepr(value, repr=text_repr): return '' | |
723 |
|
716 | |||
724 | # meat of the code begins |
|
717 | # meat of the code begins | |
725 | try: |
|
718 | try: | |
726 | etype = etype.__name__ |
|
719 | etype = etype.__name__ | |
727 | except AttributeError: |
|
720 | except AttributeError: | |
728 | pass |
|
721 | pass | |
729 |
|
722 | |||
730 | if self.long_header: |
|
723 | if self.long_header: | |
731 | # Header with the exception type, python version, and date |
|
724 | # Header with the exception type, python version, and date | |
732 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
725 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable | |
733 | date = time.ctime(time.time()) |
|
726 | date = time.ctime(time.time()) | |
734 |
|
727 | |||
735 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
728 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, | |
736 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
729 | exc, ' '*(75-len(str(etype))-len(pyver)), | |
737 | pyver, date.rjust(75) ) |
|
730 | pyver, date.rjust(75) ) | |
738 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
731 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ | |
739 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
732 | "\ncalls leading up to the error, with the most recent (innermost) call last." | |
740 | else: |
|
733 | else: | |
741 | # Simplified header |
|
734 | # Simplified header | |
742 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
735 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, | |
743 | 'Traceback (most recent call last)'.\ |
|
736 | 'Traceback (most recent call last)'.\ | |
744 | rjust(75 - len(str(etype)) ) ) |
|
737 | rjust(75 - len(str(etype)) ) ) | |
745 | frames = [] |
|
738 | frames = [] | |
746 | # Flush cache before calling inspect. This helps alleviate some of the |
|
739 | # Flush cache before calling inspect. This helps alleviate some of the | |
747 | # problems with python 2.3's inspect.py. |
|
740 | # problems with python 2.3's inspect.py. | |
748 | ##self.check_cache() |
|
741 | ##self.check_cache() | |
749 | # Drop topmost frames if requested |
|
742 | # Drop topmost frames if requested | |
750 | try: |
|
743 | try: | |
751 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
744 | # Try the default getinnerframes and Alex's: Alex's fixes some | |
752 | # problems, but it generates empty tracebacks for console errors |
|
745 | # problems, but it generates empty tracebacks for console errors | |
753 | # (5 blanks lines) where none should be returned. |
|
746 | # (5 blanks lines) where none should be returned. | |
754 | #records = inspect.getinnerframes(etb, context)[tb_offset:] |
|
747 | #records = inspect.getinnerframes(etb, context)[tb_offset:] | |
755 | #print 'python records:', records # dbg |
|
748 | #print 'python records:', records # dbg | |
756 | records = _fixed_getinnerframes(etb, context, tb_offset) |
|
749 | records = _fixed_getinnerframes(etb, context, tb_offset) | |
757 | #print 'alex records:', records # dbg |
|
750 | #print 'alex records:', records # dbg | |
758 | except: |
|
751 | except: | |
759 |
|
752 | |||
760 | # FIXME: I've been getting many crash reports from python 2.3 |
|
753 | # FIXME: I've been getting many crash reports from python 2.3 | |
761 | # users, traceable to inspect.py. If I can find a small test-case |
|
754 | # users, traceable to inspect.py. If I can find a small test-case | |
762 | # to reproduce this, I should either write a better workaround or |
|
755 | # to reproduce this, I should either write a better workaround or | |
763 | # file a bug report against inspect (if that's the real problem). |
|
756 | # file a bug report against inspect (if that's the real problem). | |
764 | # So far, I haven't been able to find an isolated example to |
|
757 | # So far, I haven't been able to find an isolated example to | |
765 | # reproduce the problem. |
|
758 | # reproduce the problem. | |
766 | inspect_error() |
|
759 | inspect_error() | |
767 | traceback.print_exc(file=self.ostream) |
|
760 | traceback.print_exc(file=self.ostream) | |
768 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
761 | info('\nUnfortunately, your original traceback can not be constructed.\n') | |
769 | return '' |
|
762 | return '' | |
770 |
|
763 | |||
771 | # build some color string templates outside these nested loops |
|
764 | # build some color string templates outside these nested loops | |
772 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) |
|
765 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) | |
773 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
766 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, | |
774 | ColorsNormal) |
|
767 | ColorsNormal) | |
775 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
768 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ | |
776 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
769 | (Colors.vName, Colors.valEm, ColorsNormal) | |
777 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
770 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) | |
778 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
771 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, | |
779 | Colors.vName, ColorsNormal) |
|
772 | Colors.vName, ColorsNormal) | |
780 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
773 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) | |
781 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
774 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) | |
782 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, |
|
775 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, | |
783 | ColorsNormal) |
|
776 | ColorsNormal) | |
784 |
|
777 | |||
785 | # now, loop over all records printing context and info |
|
778 | # now, loop over all records printing context and info | |
786 | abspath = os.path.abspath |
|
779 | abspath = os.path.abspath | |
787 | for frame, file, lnum, func, lines, index in records: |
|
780 | for frame, file, lnum, func, lines, index in records: | |
788 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
781 | #print '*** record:',file,lnum,func,lines,index # dbg | |
789 |
|
782 | |||
790 | if not file: |
|
783 | if not file: | |
791 | file = '?' |
|
784 | file = '?' | |
792 | elif not(file.startswith("<") and file.endswith(">")): |
|
785 | elif not(file.startswith("<") and file.endswith(">")): | |
793 | # Guess that filenames like <string> aren't real filenames, so |
|
786 | # Guess that filenames like <string> aren't real filenames, so | |
794 | # don't call abspath on them. |
|
787 | # don't call abspath on them. | |
795 | try: |
|
788 | try: | |
796 | file = abspath(file) |
|
789 | file = abspath(file) | |
797 | except OSError: |
|
790 | except OSError: | |
798 | # Not sure if this can still happen: abspath now works with |
|
791 | # Not sure if this can still happen: abspath now works with | |
799 | # file names like <string> |
|
792 | # file names like <string> | |
800 | pass |
|
793 | pass | |
801 |
|
794 | |||
802 | link = tpl_link % file |
|
795 | link = tpl_link % file | |
803 | args, varargs, varkw, locals = inspect.getargvalues(frame) |
|
796 | args, varargs, varkw, locals = inspect.getargvalues(frame) | |
804 |
|
797 | |||
805 | if func == '?': |
|
798 | if func == '?': | |
806 | call = '' |
|
799 | call = '' | |
807 | else: |
|
800 | else: | |
808 | # Decide whether to include variable details or not |
|
801 | # Decide whether to include variable details or not | |
809 | var_repr = self.include_vars and eqrepr or nullrepr |
|
802 | var_repr = self.include_vars and eqrepr or nullrepr | |
810 | try: |
|
803 | try: | |
811 | call = tpl_call % (func,inspect.formatargvalues(args, |
|
804 | call = tpl_call % (func,inspect.formatargvalues(args, | |
812 | varargs, varkw, |
|
805 | varargs, varkw, | |
813 | locals,formatvalue=var_repr)) |
|
806 | locals,formatvalue=var_repr)) | |
814 | except KeyError: |
|
807 | except KeyError: | |
815 | # This happens in situations like errors inside generator |
|
808 | # This happens in situations like errors inside generator | |
816 | # expressions, where local variables are listed in the |
|
809 | # expressions, where local variables are listed in the | |
817 | # line, but can't be extracted from the frame. I'm not |
|
810 | # line, but can't be extracted from the frame. I'm not | |
818 | # 100% sure this isn't actually a bug in inspect itself, |
|
811 | # 100% sure this isn't actually a bug in inspect itself, | |
819 | # but since there's no info for us to compute with, the |
|
812 | # but since there's no info for us to compute with, the | |
820 | # best we can do is report the failure and move on. Here |
|
813 | # best we can do is report the failure and move on. Here | |
821 | # we must *not* call any traceback construction again, |
|
814 | # we must *not* call any traceback construction again, | |
822 | # because that would mess up use of %debug later on. So we |
|
815 | # because that would mess up use of %debug later on. So we | |
823 | # simply report the failure and move on. The only |
|
816 | # simply report the failure and move on. The only | |
824 | # limitation will be that this frame won't have locals |
|
817 | # limitation will be that this frame won't have locals | |
825 | # listed in the call signature. Quite subtle problem... |
|
818 | # listed in the call signature. Quite subtle problem... | |
826 | # I can't think of a good way to validate this in a unit |
|
819 | # I can't think of a good way to validate this in a unit | |
827 | # test, but running a script consisting of: |
|
820 | # test, but running a script consisting of: | |
828 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
821 | # dict( (k,v.strip()) for (k,v) in range(10) ) | |
829 | # will illustrate the error, if this exception catch is |
|
822 | # will illustrate the error, if this exception catch is | |
830 | # disabled. |
|
823 | # disabled. | |
831 | call = tpl_call_fail % func |
|
824 | call = tpl_call_fail % func | |
832 |
|
825 | |||
833 | # Don't attempt to tokenize binary files. |
|
826 | # Don't attempt to tokenize binary files. | |
834 | if file.endswith(('.so', '.pyd', '.dll')): |
|
827 | if file.endswith(('.so', '.pyd', '.dll')): | |
835 | frames.append('%s %s\n' % (link,call)) |
|
828 | frames.append('%s %s\n' % (link,call)) | |
836 | continue |
|
829 | continue | |
837 | elif file.endswith(('.pyc','.pyo')): |
|
830 | elif file.endswith(('.pyc','.pyo')): | |
838 | # Look up the corresponding source file. |
|
831 | # Look up the corresponding source file. | |
839 | file = pyfile.source_from_cache(file) |
|
832 | file = pyfile.source_from_cache(file) | |
840 |
|
833 | |||
841 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
834 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): | |
842 | line = getline(file, lnum[0]) |
|
835 | line = getline(file, lnum[0]) | |
843 | lnum[0] += 1 |
|
836 | lnum[0] += 1 | |
844 | return line |
|
837 | return line | |
845 |
|
838 | |||
846 | # Build the list of names on this line of code where the exception |
|
839 | # Build the list of names on this line of code where the exception | |
847 | # occurred. |
|
840 | # occurred. | |
848 | try: |
|
841 | try: | |
849 | names = [] |
|
842 | names = [] | |
850 | name_cont = False |
|
843 | name_cont = False | |
851 |
|
844 | |||
852 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
845 | for token_type, token, start, end, line in generate_tokens(linereader): | |
853 | # build composite names |
|
846 | # build composite names | |
854 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
847 | if token_type == tokenize.NAME and token not in keyword.kwlist: | |
855 | if name_cont: |
|
848 | if name_cont: | |
856 | # Continuation of a dotted name |
|
849 | # Continuation of a dotted name | |
857 | try: |
|
850 | try: | |
858 | names[-1].append(token) |
|
851 | names[-1].append(token) | |
859 | except IndexError: |
|
852 | except IndexError: | |
860 | names.append([token]) |
|
853 | names.append([token]) | |
861 | name_cont = False |
|
854 | name_cont = False | |
862 | else: |
|
855 | else: | |
863 | # Regular new names. We append everything, the caller |
|
856 | # Regular new names. We append everything, the caller | |
864 | # will be responsible for pruning the list later. It's |
|
857 | # will be responsible for pruning the list later. It's | |
865 | # very tricky to try to prune as we go, b/c composite |
|
858 | # very tricky to try to prune as we go, b/c composite | |
866 | # names can fool us. The pruning at the end is easy |
|
859 | # names can fool us. The pruning at the end is easy | |
867 | # to do (or the caller can print a list with repeated |
|
860 | # to do (or the caller can print a list with repeated | |
868 | # names if so desired. |
|
861 | # names if so desired. | |
869 | names.append([token]) |
|
862 | names.append([token]) | |
870 | elif token == '.': |
|
863 | elif token == '.': | |
871 | name_cont = True |
|
864 | name_cont = True | |
872 | elif token_type == tokenize.NEWLINE: |
|
865 | elif token_type == tokenize.NEWLINE: | |
873 | break |
|
866 | break | |
874 |
|
867 | |||
875 | except (IndexError, UnicodeDecodeError): |
|
868 | except (IndexError, UnicodeDecodeError): | |
876 | # signals exit of tokenizer |
|
869 | # signals exit of tokenizer | |
877 | pass |
|
870 | pass | |
878 | except tokenize.TokenError as msg: |
|
871 | except tokenize.TokenError as msg: | |
879 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
872 | _m = ("An unexpected error occurred while tokenizing input\n" | |
880 | "The following traceback may be corrupted or invalid\n" |
|
873 | "The following traceback may be corrupted or invalid\n" | |
881 | "The error message is: %s\n" % msg) |
|
874 | "The error message is: %s\n" % msg) | |
882 | error(_m) |
|
875 | error(_m) | |
883 |
|
876 | |||
884 | # Join composite names (e.g. "dict.fromkeys") |
|
877 | # Join composite names (e.g. "dict.fromkeys") | |
885 | names = ['.'.join(n) for n in names] |
|
878 | names = ['.'.join(n) for n in names] | |
886 | # prune names list of duplicates, but keep the right order |
|
879 | # prune names list of duplicates, but keep the right order | |
887 | unique_names = uniq_stable(names) |
|
880 | unique_names = uniq_stable(names) | |
888 |
|
881 | |||
889 | # Start loop over vars |
|
882 | # Start loop over vars | |
890 | lvals = [] |
|
883 | lvals = [] | |
891 | if self.include_vars: |
|
884 | if self.include_vars: | |
892 | for name_full in unique_names: |
|
885 | for name_full in unique_names: | |
893 | name_base = name_full.split('.',1)[0] |
|
886 | name_base = name_full.split('.',1)[0] | |
894 | if name_base in frame.f_code.co_varnames: |
|
887 | if name_base in frame.f_code.co_varnames: | |
895 | if name_base in locals: |
|
888 | if name_base in locals: | |
896 | try: |
|
889 | try: | |
897 | value = repr(eval(name_full,locals)) |
|
890 | value = repr(eval(name_full,locals)) | |
898 | except: |
|
891 | except: | |
899 | value = undefined |
|
892 | value = undefined | |
900 | else: |
|
893 | else: | |
901 | value = undefined |
|
894 | value = undefined | |
902 | name = tpl_local_var % name_full |
|
895 | name = tpl_local_var % name_full | |
903 | else: |
|
896 | else: | |
904 | if name_base in frame.f_globals: |
|
897 | if name_base in frame.f_globals: | |
905 | try: |
|
898 | try: | |
906 | value = repr(eval(name_full,frame.f_globals)) |
|
899 | value = repr(eval(name_full,frame.f_globals)) | |
907 | except: |
|
900 | except: | |
908 | value = undefined |
|
901 | value = undefined | |
909 | else: |
|
902 | else: | |
910 | value = undefined |
|
903 | value = undefined | |
911 | name = tpl_global_var % name_full |
|
904 | name = tpl_global_var % name_full | |
912 | lvals.append(tpl_name_val % (name,value)) |
|
905 | lvals.append(tpl_name_val % (name,value)) | |
913 | if lvals: |
|
906 | if lvals: | |
914 | lvals = '%s%s' % (indent,em_normal.join(lvals)) |
|
907 | lvals = '%s%s' % (indent,em_normal.join(lvals)) | |
915 | else: |
|
908 | else: | |
916 | lvals = '' |
|
909 | lvals = '' | |
917 |
|
910 | |||
918 | level = '%s %s\n' % (link,call) |
|
911 | level = '%s %s\n' % (link,call) | |
919 |
|
912 | |||
920 | if index is None: |
|
913 | if index is None: | |
921 | frames.append(level) |
|
914 | frames.append(level) | |
922 | else: |
|
915 | else: | |
923 | frames.append('%s%s' % (level,''.join( |
|
916 | frames.append('%s%s' % (level,''.join( | |
924 | _format_traceback_lines(lnum,index,lines,Colors,lvals, |
|
917 | _format_traceback_lines(lnum,index,lines,Colors,lvals, | |
925 | col_scheme)))) |
|
918 | col_scheme)))) | |
926 |
|
919 | |||
927 | # Get (safely) a string form of the exception info |
|
920 | # Get (safely) a string form of the exception info | |
928 | try: |
|
921 | try: | |
929 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
922 | etype_str,evalue_str = map(str,(etype,evalue)) | |
930 | except: |
|
923 | except: | |
931 | # User exception is improperly defined. |
|
924 | # User exception is improperly defined. | |
932 | etype,evalue = str,sys.exc_info()[:2] |
|
925 | etype,evalue = str,sys.exc_info()[:2] | |
933 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
926 | etype_str,evalue_str = map(str,(etype,evalue)) | |
934 | # ... and format it |
|
927 | # ... and format it | |
935 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, |
|
928 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, | |
936 | ColorsNormal, evalue_str)] |
|
929 | ColorsNormal, evalue_str)] | |
937 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: |
|
930 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: | |
938 | try: |
|
931 | try: | |
939 | names = [w for w in dir(evalue) if isinstance(w, basestring)] |
|
932 | names = [w for w in dir(evalue) if isinstance(w, basestring)] | |
940 | except: |
|
933 | except: | |
941 | # Every now and then, an object with funny inernals blows up |
|
934 | # Every now and then, an object with funny inernals blows up | |
942 | # when dir() is called on it. We do the best we can to report |
|
935 | # when dir() is called on it. We do the best we can to report | |
943 | # the problem and continue |
|
936 | # the problem and continue | |
944 | _m = '%sException reporting error (object with broken dir())%s:' |
|
937 | _m = '%sException reporting error (object with broken dir())%s:' | |
945 | exception.append(_m % (Colors.excName,ColorsNormal)) |
|
938 | exception.append(_m % (Colors.excName,ColorsNormal)) | |
946 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) |
|
939 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) | |
947 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, |
|
940 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, | |
948 | ColorsNormal, evalue_str)) |
|
941 | ColorsNormal, evalue_str)) | |
949 | names = [] |
|
942 | names = [] | |
950 | for name in names: |
|
943 | for name in names: | |
951 | value = text_repr(getattr(evalue, name)) |
|
944 | value = text_repr(getattr(evalue, name)) | |
952 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
945 | exception.append('\n%s%s = %s' % (indent, name, value)) | |
953 |
|
946 | |||
954 | # vds: >> |
|
947 | # vds: >> | |
955 | if records: |
|
948 | if records: | |
956 | filepath, lnum = records[-1][1:3] |
|
949 | filepath, lnum = records[-1][1:3] | |
957 | #print "file:", str(file), "linenb", str(lnum) # dbg |
|
950 | #print "file:", str(file), "linenb", str(lnum) # dbg | |
958 | filepath = os.path.abspath(filepath) |
|
951 | filepath = os.path.abspath(filepath) | |
959 | ipinst = ipapi.get() |
|
952 | ipinst = ipapi.get() | |
960 | if ipinst is not None: |
|
953 | if ipinst is not None: | |
961 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
954 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) | |
962 | # vds: << |
|
955 | # vds: << | |
963 |
|
956 | |||
964 | # return all our info assembled as a single string |
|
957 | # return all our info assembled as a single string | |
965 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) |
|
958 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) | |
966 | return [head] + frames + [''.join(exception[0])] |
|
959 | return [head] + frames + [''.join(exception[0])] | |
967 |
|
960 | |||
968 | def debugger(self,force=False): |
|
961 | def debugger(self,force=False): | |
969 | """Call up the pdb debugger if desired, always clean up the tb |
|
962 | """Call up the pdb debugger if desired, always clean up the tb | |
970 | reference. |
|
963 | reference. | |
971 |
|
964 | |||
972 | Keywords: |
|
965 | Keywords: | |
973 |
|
966 | |||
974 | - force(False): by default, this routine checks the instance call_pdb |
|
967 | - force(False): by default, this routine checks the instance call_pdb | |
975 | flag and does not actually invoke the debugger if the flag is false. |
|
968 | flag and does not actually invoke the debugger if the flag is false. | |
976 | The 'force' option forces the debugger to activate even if the flag |
|
969 | The 'force' option forces the debugger to activate even if the flag | |
977 | is false. |
|
970 | is false. | |
978 |
|
971 | |||
979 | If the call_pdb flag is set, the pdb interactive debugger is |
|
972 | If the call_pdb flag is set, the pdb interactive debugger is | |
980 | invoked. In all cases, the self.tb reference to the current traceback |
|
973 | invoked. In all cases, the self.tb reference to the current traceback | |
981 | is deleted to prevent lingering references which hamper memory |
|
974 | is deleted to prevent lingering references which hamper memory | |
982 | management. |
|
975 | management. | |
983 |
|
976 | |||
984 | Note that each call to pdb() does an 'import readline', so if your app |
|
977 | Note that each call to pdb() does an 'import readline', so if your app | |
985 | requires a special setup for the readline completers, you'll have to |
|
978 | requires a special setup for the readline completers, you'll have to | |
986 | fix that by hand after invoking the exception handler.""" |
|
979 | fix that by hand after invoking the exception handler.""" | |
987 |
|
980 | |||
988 | if force or self.call_pdb: |
|
981 | if force or self.call_pdb: | |
989 | if self.pdb is None: |
|
982 | if self.pdb is None: | |
990 | self.pdb = debugger.Pdb( |
|
983 | self.pdb = debugger.Pdb( | |
991 | self.color_scheme_table.active_scheme_name) |
|
984 | self.color_scheme_table.active_scheme_name) | |
992 | # the system displayhook may have changed, restore the original |
|
985 | # the system displayhook may have changed, restore the original | |
993 | # for pdb |
|
986 | # for pdb | |
994 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
987 | display_trap = DisplayTrap(hook=sys.__displayhook__) | |
995 | with display_trap: |
|
988 | with display_trap: | |
996 | self.pdb.reset() |
|
989 | self.pdb.reset() | |
997 | # Find the right frame so we don't pop up inside ipython itself |
|
990 | # Find the right frame so we don't pop up inside ipython itself | |
998 | if hasattr(self,'tb') and self.tb is not None: |
|
991 | if hasattr(self,'tb') and self.tb is not None: | |
999 | etb = self.tb |
|
992 | etb = self.tb | |
1000 | else: |
|
993 | else: | |
1001 | etb = self.tb = sys.last_traceback |
|
994 | etb = self.tb = sys.last_traceback | |
1002 | while self.tb is not None and self.tb.tb_next is not None: |
|
995 | while self.tb is not None and self.tb.tb_next is not None: | |
1003 | self.tb = self.tb.tb_next |
|
996 | self.tb = self.tb.tb_next | |
1004 | if etb and etb.tb_next: |
|
997 | if etb and etb.tb_next: | |
1005 | etb = etb.tb_next |
|
998 | etb = etb.tb_next | |
1006 | self.pdb.botframe = etb.tb_frame |
|
999 | self.pdb.botframe = etb.tb_frame | |
1007 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1000 | self.pdb.interaction(self.tb.tb_frame, self.tb) | |
1008 |
|
1001 | |||
1009 | if hasattr(self,'tb'): |
|
1002 | if hasattr(self,'tb'): | |
1010 | del self.tb |
|
1003 | del self.tb | |
1011 |
|
1004 | |||
1012 | def handler(self, info=None): |
|
1005 | def handler(self, info=None): | |
1013 | (etype, evalue, etb) = info or sys.exc_info() |
|
1006 | (etype, evalue, etb) = info or sys.exc_info() | |
1014 | self.tb = etb |
|
1007 | self.tb = etb | |
1015 | ostream = self.ostream |
|
1008 | ostream = self.ostream | |
1016 | ostream.flush() |
|
1009 | ostream.flush() | |
1017 | ostream.write(self.text(etype, evalue, etb)) |
|
1010 | ostream.write(self.text(etype, evalue, etb)) | |
1018 | ostream.write('\n') |
|
1011 | ostream.write('\n') | |
1019 | ostream.flush() |
|
1012 | ostream.flush() | |
1020 |
|
1013 | |||
1021 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1014 | # Changed so an instance can just be called as VerboseTB_inst() and print | |
1022 | # out the right info on its own. |
|
1015 | # out the right info on its own. | |
1023 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1016 | def __call__(self, etype=None, evalue=None, etb=None): | |
1024 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1017 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" | |
1025 | if etb is None: |
|
1018 | if etb is None: | |
1026 | self.handler() |
|
1019 | self.handler() | |
1027 | else: |
|
1020 | else: | |
1028 | self.handler((etype, evalue, etb)) |
|
1021 | self.handler((etype, evalue, etb)) | |
1029 | try: |
|
1022 | try: | |
1030 | self.debugger() |
|
1023 | self.debugger() | |
1031 | except KeyboardInterrupt: |
|
1024 | except KeyboardInterrupt: | |
1032 | print "\nKeyboardInterrupt" |
|
1025 | print "\nKeyboardInterrupt" | |
1033 |
|
1026 | |||
1034 | #---------------------------------------------------------------------------- |
|
1027 | #---------------------------------------------------------------------------- | |
1035 | class FormattedTB(VerboseTB, ListTB): |
|
1028 | class FormattedTB(VerboseTB, ListTB): | |
1036 | """Subclass ListTB but allow calling with a traceback. |
|
1029 | """Subclass ListTB but allow calling with a traceback. | |
1037 |
|
1030 | |||
1038 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1031 | It can thus be used as a sys.excepthook for Python > 2.1. | |
1039 |
|
1032 | |||
1040 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1033 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. | |
1041 |
|
1034 | |||
1042 | Allows a tb_offset to be specified. This is useful for situations where |
|
1035 | Allows a tb_offset to be specified. This is useful for situations where | |
1043 | one needs to remove a number of topmost frames from the traceback (such as |
|
1036 | one needs to remove a number of topmost frames from the traceback (such as | |
1044 | occurs with python programs that themselves execute other python code, |
|
1037 | occurs with python programs that themselves execute other python code, | |
1045 | like Python shells). """ |
|
1038 | like Python shells). """ | |
1046 |
|
1039 | |||
1047 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1040 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, | |
1048 | ostream=None, |
|
1041 | ostream=None, | |
1049 | tb_offset=0, long_header=False, include_vars=False, |
|
1042 | tb_offset=0, long_header=False, include_vars=False, | |
1050 | check_cache=None): |
|
1043 | check_cache=None): | |
1051 |
|
1044 | |||
1052 | # NEVER change the order of this list. Put new modes at the end: |
|
1045 | # NEVER change the order of this list. Put new modes at the end: | |
1053 | self.valid_modes = ['Plain','Context','Verbose'] |
|
1046 | self.valid_modes = ['Plain','Context','Verbose'] | |
1054 | self.verbose_modes = self.valid_modes[1:3] |
|
1047 | self.verbose_modes = self.valid_modes[1:3] | |
1055 |
|
1048 | |||
1056 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1049 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
1057 | ostream=ostream, tb_offset=tb_offset, |
|
1050 | ostream=ostream, tb_offset=tb_offset, | |
1058 | long_header=long_header, include_vars=include_vars, |
|
1051 | long_header=long_header, include_vars=include_vars, | |
1059 | check_cache=check_cache) |
|
1052 | check_cache=check_cache) | |
1060 |
|
1053 | |||
1061 | # Different types of tracebacks are joined with different separators to |
|
1054 | # Different types of tracebacks are joined with different separators to | |
1062 | # form a single string. They are taken from this dict |
|
1055 | # form a single string. They are taken from this dict | |
1063 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1056 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') | |
1064 | # set_mode also sets the tb_join_char attribute |
|
1057 | # set_mode also sets the tb_join_char attribute | |
1065 | self.set_mode(mode) |
|
1058 | self.set_mode(mode) | |
1066 |
|
1059 | |||
1067 | def _extract_tb(self,tb): |
|
1060 | def _extract_tb(self,tb): | |
1068 | if tb: |
|
1061 | if tb: | |
1069 | return traceback.extract_tb(tb) |
|
1062 | return traceback.extract_tb(tb) | |
1070 | else: |
|
1063 | else: | |
1071 | return None |
|
1064 | return None | |
1072 |
|
1065 | |||
1073 | def structured_traceback(self, etype, value, tb, tb_offset=None, context=5): |
|
1066 | def structured_traceback(self, etype, value, tb, tb_offset=None, context=5): | |
1074 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1067 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
1075 | mode = self.mode |
|
1068 | mode = self.mode | |
1076 | if mode in self.verbose_modes: |
|
1069 | if mode in self.verbose_modes: | |
1077 | # Verbose modes need a full traceback |
|
1070 | # Verbose modes need a full traceback | |
1078 | return VerboseTB.structured_traceback( |
|
1071 | return VerboseTB.structured_traceback( | |
1079 | self, etype, value, tb, tb_offset, context |
|
1072 | self, etype, value, tb, tb_offset, context | |
1080 | ) |
|
1073 | ) | |
1081 | else: |
|
1074 | else: | |
1082 | # We must check the source cache because otherwise we can print |
|
1075 | # We must check the source cache because otherwise we can print | |
1083 | # out-of-date source code. |
|
1076 | # out-of-date source code. | |
1084 | self.check_cache() |
|
1077 | self.check_cache() | |
1085 | # Now we can extract and format the exception |
|
1078 | # Now we can extract and format the exception | |
1086 | elist = self._extract_tb(tb) |
|
1079 | elist = self._extract_tb(tb) | |
1087 | return ListTB.structured_traceback( |
|
1080 | return ListTB.structured_traceback( | |
1088 | self, etype, value, elist, tb_offset, context |
|
1081 | self, etype, value, elist, tb_offset, context | |
1089 | ) |
|
1082 | ) | |
1090 |
|
1083 | |||
1091 | def stb2text(self, stb): |
|
1084 | def stb2text(self, stb): | |
1092 | """Convert a structured traceback (a list) to a string.""" |
|
1085 | """Convert a structured traceback (a list) to a string.""" | |
1093 | return self.tb_join_char.join(stb) |
|
1086 | return self.tb_join_char.join(stb) | |
1094 |
|
1087 | |||
1095 |
|
1088 | |||
1096 | def set_mode(self,mode=None): |
|
1089 | def set_mode(self,mode=None): | |
1097 | """Switch to the desired mode. |
|
1090 | """Switch to the desired mode. | |
1098 |
|
1091 | |||
1099 | If mode is not specified, cycles through the available modes.""" |
|
1092 | If mode is not specified, cycles through the available modes.""" | |
1100 |
|
1093 | |||
1101 | if not mode: |
|
1094 | if not mode: | |
1102 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ |
|
1095 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ | |
1103 | len(self.valid_modes) |
|
1096 | len(self.valid_modes) | |
1104 | self.mode = self.valid_modes[new_idx] |
|
1097 | self.mode = self.valid_modes[new_idx] | |
1105 | elif mode not in self.valid_modes: |
|
1098 | elif mode not in self.valid_modes: | |
1106 | raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n' |
|
1099 | raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n' | |
1107 | 'Valid modes: '+str(self.valid_modes)) |
|
1100 | 'Valid modes: '+str(self.valid_modes)) | |
1108 | else: |
|
1101 | else: | |
1109 | self.mode = mode |
|
1102 | self.mode = mode | |
1110 | # include variable details only in 'Verbose' mode |
|
1103 | # include variable details only in 'Verbose' mode | |
1111 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1104 | self.include_vars = (self.mode == self.valid_modes[2]) | |
1112 | # Set the join character for generating text tracebacks |
|
1105 | # Set the join character for generating text tracebacks | |
1113 | self.tb_join_char = self._join_chars[self.mode] |
|
1106 | self.tb_join_char = self._join_chars[self.mode] | |
1114 |
|
1107 | |||
1115 | # some convenient shorcuts |
|
1108 | # some convenient shorcuts | |
1116 | def plain(self): |
|
1109 | def plain(self): | |
1117 | self.set_mode(self.valid_modes[0]) |
|
1110 | self.set_mode(self.valid_modes[0]) | |
1118 |
|
1111 | |||
1119 | def context(self): |
|
1112 | def context(self): | |
1120 | self.set_mode(self.valid_modes[1]) |
|
1113 | self.set_mode(self.valid_modes[1]) | |
1121 |
|
1114 | |||
1122 | def verbose(self): |
|
1115 | def verbose(self): | |
1123 | self.set_mode(self.valid_modes[2]) |
|
1116 | self.set_mode(self.valid_modes[2]) | |
1124 |
|
1117 | |||
1125 | #---------------------------------------------------------------------------- |
|
1118 | #---------------------------------------------------------------------------- | |
1126 | class AutoFormattedTB(FormattedTB): |
|
1119 | class AutoFormattedTB(FormattedTB): | |
1127 | """A traceback printer which can be called on the fly. |
|
1120 | """A traceback printer which can be called on the fly. | |
1128 |
|
1121 | |||
1129 | It will find out about exceptions by itself. |
|
1122 | It will find out about exceptions by itself. | |
1130 |
|
1123 | |||
1131 | A brief example: |
|
1124 | A brief example: | |
1132 |
|
1125 | |||
1133 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1126 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') | |
1134 | try: |
|
1127 | try: | |
1135 | ... |
|
1128 | ... | |
1136 | except: |
|
1129 | except: | |
1137 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1130 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object | |
1138 | """ |
|
1131 | """ | |
1139 |
|
1132 | |||
1140 | def __call__(self,etype=None,evalue=None,etb=None, |
|
1133 | def __call__(self,etype=None,evalue=None,etb=None, | |
1141 | out=None,tb_offset=None): |
|
1134 | out=None,tb_offset=None): | |
1142 | """Print out a formatted exception traceback. |
|
1135 | """Print out a formatted exception traceback. | |
1143 |
|
1136 | |||
1144 | Optional arguments: |
|
1137 | Optional arguments: | |
1145 | - out: an open file-like object to direct output to. |
|
1138 | - out: an open file-like object to direct output to. | |
1146 |
|
1139 | |||
1147 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1140 | - tb_offset: the number of frames to skip over in the stack, on a | |
1148 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1141 | per-call basis (this overrides temporarily the instance's tb_offset | |
1149 | given at initialization time. """ |
|
1142 | given at initialization time. """ | |
1150 |
|
1143 | |||
1151 |
|
1144 | |||
1152 | if out is None: |
|
1145 | if out is None: | |
1153 | out = self.ostream |
|
1146 | out = self.ostream | |
1154 | out.flush() |
|
1147 | out.flush() | |
1155 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1148 | out.write(self.text(etype, evalue, etb, tb_offset)) | |
1156 | out.write('\n') |
|
1149 | out.write('\n') | |
1157 | out.flush() |
|
1150 | out.flush() | |
1158 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1151 | # FIXME: we should remove the auto pdb behavior from here and leave | |
1159 | # that to the clients. |
|
1152 | # that to the clients. | |
1160 | try: |
|
1153 | try: | |
1161 | self.debugger() |
|
1154 | self.debugger() | |
1162 | except KeyboardInterrupt: |
|
1155 | except KeyboardInterrupt: | |
1163 | print "\nKeyboardInterrupt" |
|
1156 | print "\nKeyboardInterrupt" | |
1164 |
|
1157 | |||
1165 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1158 | def structured_traceback(self, etype=None, value=None, tb=None, | |
1166 | tb_offset=None, context=5): |
|
1159 | tb_offset=None, context=5): | |
1167 | if etype is None: |
|
1160 | if etype is None: | |
1168 | etype,value,tb = sys.exc_info() |
|
1161 | etype,value,tb = sys.exc_info() | |
1169 | self.tb = tb |
|
1162 | self.tb = tb | |
1170 | return FormattedTB.structured_traceback( |
|
1163 | return FormattedTB.structured_traceback( | |
1171 | self, etype, value, tb, tb_offset, context) |
|
1164 | self, etype, value, tb, tb_offset, context) | |
1172 |
|
1165 | |||
1173 | #--------------------------------------------------------------------------- |
|
1166 | #--------------------------------------------------------------------------- | |
1174 |
|
1167 | |||
1175 | # A simple class to preserve Nathan's original functionality. |
|
1168 | # A simple class to preserve Nathan's original functionality. | |
1176 | class ColorTB(FormattedTB): |
|
1169 | class ColorTB(FormattedTB): | |
1177 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1170 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" | |
1178 | def __init__(self,color_scheme='Linux',call_pdb=0): |
|
1171 | def __init__(self,color_scheme='Linux',call_pdb=0): | |
1179 | FormattedTB.__init__(self,color_scheme=color_scheme, |
|
1172 | FormattedTB.__init__(self,color_scheme=color_scheme, | |
1180 | call_pdb=call_pdb) |
|
1173 | call_pdb=call_pdb) | |
1181 |
|
1174 | |||
1182 |
|
1175 | |||
1183 | class SyntaxTB(ListTB): |
|
1176 | class SyntaxTB(ListTB): | |
1184 | """Extension which holds some state: the last exception value""" |
|
1177 | """Extension which holds some state: the last exception value""" | |
1185 |
|
1178 | |||
1186 | def __init__(self,color_scheme = 'NoColor'): |
|
1179 | def __init__(self,color_scheme = 'NoColor'): | |
1187 | ListTB.__init__(self,color_scheme) |
|
1180 | ListTB.__init__(self,color_scheme) | |
1188 | self.last_syntax_error = None |
|
1181 | self.last_syntax_error = None | |
1189 |
|
1182 | |||
1190 | def __call__(self, etype, value, elist): |
|
1183 | def __call__(self, etype, value, elist): | |
1191 | self.last_syntax_error = value |
|
1184 | self.last_syntax_error = value | |
1192 | ListTB.__call__(self,etype,value,elist) |
|
1185 | ListTB.__call__(self,etype,value,elist) | |
1193 |
|
1186 | |||
1194 | def clear_err_state(self): |
|
1187 | def clear_err_state(self): | |
1195 | """Return the current error state and clear it""" |
|
1188 | """Return the current error state and clear it""" | |
1196 | e = self.last_syntax_error |
|
1189 | e = self.last_syntax_error | |
1197 | self.last_syntax_error = None |
|
1190 | self.last_syntax_error = None | |
1198 | return e |
|
1191 | return e | |
1199 |
|
1192 | |||
1200 | def stb2text(self, stb): |
|
1193 | def stb2text(self, stb): | |
1201 | """Convert a structured traceback (a list) to a string.""" |
|
1194 | """Convert a structured traceback (a list) to a string.""" | |
1202 | return ''.join(stb) |
|
1195 | return ''.join(stb) | |
1203 |
|
1196 | |||
1204 |
|
1197 | |||
1205 | #---------------------------------------------------------------------------- |
|
1198 | #---------------------------------------------------------------------------- | |
1206 | # module testing (minimal) |
|
1199 | # module testing (minimal) | |
1207 | if __name__ == "__main__": |
|
1200 | if __name__ == "__main__": | |
1208 | def spam(c, d_e): |
|
1201 | def spam(c, d_e): | |
1209 | (d, e) = d_e |
|
1202 | (d, e) = d_e | |
1210 | x = c + d |
|
1203 | x = c + d | |
1211 | y = c * d |
|
1204 | y = c * d | |
1212 | foo(x, y) |
|
1205 | foo(x, y) | |
1213 |
|
1206 | |||
1214 | def foo(a, b, bar=1): |
|
1207 | def foo(a, b, bar=1): | |
1215 | eggs(a, b + bar) |
|
1208 | eggs(a, b + bar) | |
1216 |
|
1209 | |||
1217 | def eggs(f, g, z=globals()): |
|
1210 | def eggs(f, g, z=globals()): | |
1218 | h = f + g |
|
1211 | h = f + g | |
1219 | i = f - g |
|
1212 | i = f - g | |
1220 | return h / i |
|
1213 | return h / i | |
1221 |
|
1214 | |||
1222 | print '' |
|
1215 | print '' | |
1223 | print '*** Before ***' |
|
1216 | print '*** Before ***' | |
1224 | try: |
|
1217 | try: | |
1225 | print spam(1, (2, 3)) |
|
1218 | print spam(1, (2, 3)) | |
1226 | except: |
|
1219 | except: | |
1227 | traceback.print_exc() |
|
1220 | traceback.print_exc() | |
1228 | print '' |
|
1221 | print '' | |
1229 |
|
1222 | |||
1230 | handler = ColorTB() |
|
1223 | handler = ColorTB() | |
1231 | print '*** ColorTB ***' |
|
1224 | print '*** ColorTB ***' | |
1232 | try: |
|
1225 | try: | |
1233 | print spam(1, (2, 3)) |
|
1226 | print spam(1, (2, 3)) | |
1234 | except: |
|
1227 | except: | |
1235 | handler(*sys.exc_info()) |
|
1228 | handler(*sys.exc_info()) | |
1236 | print '' |
|
1229 | print '' | |
1237 |
|
1230 | |||
1238 | handler = VerboseTB() |
|
1231 | handler = VerboseTB() | |
1239 | print '*** VerboseTB ***' |
|
1232 | print '*** VerboseTB ***' | |
1240 | try: |
|
1233 | try: | |
1241 | print spam(1, (2, 3)) |
|
1234 | print spam(1, (2, 3)) | |
1242 | except: |
|
1235 | except: | |
1243 | handler(*sys.exc_info()) |
|
1236 | handler(*sys.exc_info()) | |
1244 | print '' |
|
1237 | print '' | |
1245 |
|
1238 |
@@ -1,382 +1,391 b'' | |||||
1 | """Generic testing tools. |
|
1 | """Generic testing tools. | |
2 |
|
2 | |||
3 | Authors |
|
3 | Authors | |
4 | ------- |
|
4 | ------- | |
5 | - Fernando Perez <Fernando.Perez@berkeley.edu> |
|
5 | - Fernando Perez <Fernando.Perez@berkeley.edu> | |
6 | """ |
|
6 | """ | |
7 |
|
7 | |||
8 | from __future__ import absolute_import |
|
8 | from __future__ import absolute_import | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2009-2011 The IPython Development Team |
|
11 | # Copyright (C) 2009-2011 The IPython Development Team | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Imports |
|
18 | # Imports | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | import os |
|
21 | import os | |
22 | import re |
|
22 | import re | |
23 | import sys |
|
23 | import sys | |
24 | import tempfile |
|
24 | import tempfile | |
25 |
|
25 | |||
26 | from contextlib import contextmanager |
|
26 | from contextlib import contextmanager | |
27 | from io import StringIO |
|
27 | from io import StringIO | |
28 |
|
28 | |||
29 | try: |
|
29 | try: | |
30 | # These tools are used by parts of the runtime, so we make the nose |
|
30 | # These tools are used by parts of the runtime, so we make the nose | |
31 | # dependency optional at this point. Nose is a hard dependency to run the |
|
31 | # dependency optional at this point. Nose is a hard dependency to run the | |
32 | # test suite, but NOT to use ipython itself. |
|
32 | # test suite, but NOT to use ipython itself. | |
33 | import nose.tools as nt |
|
33 | import nose.tools as nt | |
34 | has_nose = True |
|
34 | has_nose = True | |
35 | except ImportError: |
|
35 | except ImportError: | |
36 | has_nose = False |
|
36 | has_nose = False | |
37 |
|
37 | |||
38 | from IPython.config.loader import Config |
|
38 | from IPython.config.loader import Config | |
39 | from IPython.utils.process import find_cmd, getoutputerror |
|
39 | from IPython.utils.process import find_cmd, getoutputerror | |
40 | from IPython.utils.text import list_strings |
|
40 | from IPython.utils.text import list_strings | |
41 | from IPython.utils.io import temp_pyfile, Tee |
|
41 | from IPython.utils.io import temp_pyfile, Tee | |
42 | from IPython.utils import py3compat |
|
42 | from IPython.utils import py3compat | |
43 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
43 | from IPython.utils.encoding import DEFAULT_ENCODING | |
44 |
|
44 | |||
45 | from . import decorators as dec |
|
45 | from . import decorators as dec | |
46 | from . import skipdoctest |
|
46 | from . import skipdoctest | |
47 |
|
47 | |||
48 | #----------------------------------------------------------------------------- |
|
48 | #----------------------------------------------------------------------------- | |
49 | # Functions and classes |
|
49 | # Functions and classes | |
50 | #----------------------------------------------------------------------------- |
|
50 | #----------------------------------------------------------------------------- | |
51 |
|
51 | |||
52 | # The docstring for full_path doctests differently on win32 (different path |
|
52 | # The docstring for full_path doctests differently on win32 (different path | |
53 | # separator) so just skip the doctest there. The example remains informative. |
|
53 | # separator) so just skip the doctest there. The example remains informative. | |
54 | doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco |
|
54 | doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco | |
55 |
|
55 | |||
56 | @doctest_deco |
|
56 | @doctest_deco | |
57 | def full_path(startPath,files): |
|
57 | def full_path(startPath,files): | |
58 | """Make full paths for all the listed files, based on startPath. |
|
58 | """Make full paths for all the listed files, based on startPath. | |
59 |
|
59 | |||
60 | Only the base part of startPath is kept, since this routine is typically |
|
60 | Only the base part of startPath is kept, since this routine is typically | |
61 | used with a script's __file__ variable as startPath. The base of startPath |
|
61 | used with a script's __file__ variable as startPath. The base of startPath | |
62 | is then prepended to all the listed files, forming the output list. |
|
62 | is then prepended to all the listed files, forming the output list. | |
63 |
|
63 | |||
64 | Parameters |
|
64 | Parameters | |
65 | ---------- |
|
65 | ---------- | |
66 | startPath : string |
|
66 | startPath : string | |
67 | Initial path to use as the base for the results. This path is split |
|
67 | Initial path to use as the base for the results. This path is split | |
68 | using os.path.split() and only its first component is kept. |
|
68 | using os.path.split() and only its first component is kept. | |
69 |
|
69 | |||
70 | files : string or list |
|
70 | files : string or list | |
71 | One or more files. |
|
71 | One or more files. | |
72 |
|
72 | |||
73 | Examples |
|
73 | Examples | |
74 | -------- |
|
74 | -------- | |
75 |
|
75 | |||
76 | >>> full_path('/foo/bar.py',['a.txt','b.txt']) |
|
76 | >>> full_path('/foo/bar.py',['a.txt','b.txt']) | |
77 | ['/foo/a.txt', '/foo/b.txt'] |
|
77 | ['/foo/a.txt', '/foo/b.txt'] | |
78 |
|
78 | |||
79 | >>> full_path('/foo',['a.txt','b.txt']) |
|
79 | >>> full_path('/foo',['a.txt','b.txt']) | |
80 | ['/a.txt', '/b.txt'] |
|
80 | ['/a.txt', '/b.txt'] | |
81 |
|
81 | |||
82 | If a single file is given, the output is still a list: |
|
82 | If a single file is given, the output is still a list: | |
83 | >>> full_path('/foo','a.txt') |
|
83 | >>> full_path('/foo','a.txt') | |
84 | ['/a.txt'] |
|
84 | ['/a.txt'] | |
85 | """ |
|
85 | """ | |
86 |
|
86 | |||
87 | files = list_strings(files) |
|
87 | files = list_strings(files) | |
88 | base = os.path.split(startPath)[0] |
|
88 | base = os.path.split(startPath)[0] | |
89 | return [ os.path.join(base,f) for f in files ] |
|
89 | return [ os.path.join(base,f) for f in files ] | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | def parse_test_output(txt): |
|
92 | def parse_test_output(txt): | |
93 | """Parse the output of a test run and return errors, failures. |
|
93 | """Parse the output of a test run and return errors, failures. | |
94 |
|
94 | |||
95 | Parameters |
|
95 | Parameters | |
96 | ---------- |
|
96 | ---------- | |
97 | txt : str |
|
97 | txt : str | |
98 | Text output of a test run, assumed to contain a line of one of the |
|
98 | Text output of a test run, assumed to contain a line of one of the | |
99 | following forms:: |
|
99 | following forms:: | |
100 | 'FAILED (errors=1)' |
|
100 | 'FAILED (errors=1)' | |
101 | 'FAILED (failures=1)' |
|
101 | 'FAILED (failures=1)' | |
102 | 'FAILED (errors=1, failures=1)' |
|
102 | 'FAILED (errors=1, failures=1)' | |
103 |
|
103 | |||
104 | Returns |
|
104 | Returns | |
105 | ------- |
|
105 | ------- | |
106 | nerr, nfail: number of errors and failures. |
|
106 | nerr, nfail: number of errors and failures. | |
107 | """ |
|
107 | """ | |
108 |
|
108 | |||
109 | err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE) |
|
109 | err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE) | |
110 | if err_m: |
|
110 | if err_m: | |
111 | nerr = int(err_m.group(1)) |
|
111 | nerr = int(err_m.group(1)) | |
112 | nfail = 0 |
|
112 | nfail = 0 | |
113 | return nerr, nfail |
|
113 | return nerr, nfail | |
114 |
|
114 | |||
115 | fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE) |
|
115 | fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE) | |
116 | if fail_m: |
|
116 | if fail_m: | |
117 | nerr = 0 |
|
117 | nerr = 0 | |
118 | nfail = int(fail_m.group(1)) |
|
118 | nfail = int(fail_m.group(1)) | |
119 | return nerr, nfail |
|
119 | return nerr, nfail | |
120 |
|
120 | |||
121 | both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt, |
|
121 | both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt, | |
122 | re.MULTILINE) |
|
122 | re.MULTILINE) | |
123 | if both_m: |
|
123 | if both_m: | |
124 | nerr = int(both_m.group(1)) |
|
124 | nerr = int(both_m.group(1)) | |
125 | nfail = int(both_m.group(2)) |
|
125 | nfail = int(both_m.group(2)) | |
126 | return nerr, nfail |
|
126 | return nerr, nfail | |
127 |
|
127 | |||
128 | # If the input didn't match any of these forms, assume no error/failures |
|
128 | # If the input didn't match any of these forms, assume no error/failures | |
129 | return 0, 0 |
|
129 | return 0, 0 | |
130 |
|
130 | |||
131 |
|
131 | |||
132 | # So nose doesn't think this is a test |
|
132 | # So nose doesn't think this is a test | |
133 | parse_test_output.__test__ = False |
|
133 | parse_test_output.__test__ = False | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | def default_argv(): |
|
136 | def default_argv(): | |
137 | """Return a valid default argv for creating testing instances of ipython""" |
|
137 | """Return a valid default argv for creating testing instances of ipython""" | |
138 |
|
138 | |||
139 | return ['--quick', # so no config file is loaded |
|
139 | return ['--quick', # so no config file is loaded | |
140 | # Other defaults to minimize side effects on stdout |
|
140 | # Other defaults to minimize side effects on stdout | |
141 | '--colors=NoColor', '--no-term-title','--no-banner', |
|
141 | '--colors=NoColor', '--no-term-title','--no-banner', | |
142 | '--autocall=0'] |
|
142 | '--autocall=0'] | |
143 |
|
143 | |||
144 |
|
144 | |||
145 | def default_config(): |
|
145 | def default_config(): | |
146 | """Return a config object with good defaults for testing.""" |
|
146 | """Return a config object with good defaults for testing.""" | |
147 | config = Config() |
|
147 | config = Config() | |
148 | config.TerminalInteractiveShell.colors = 'NoColor' |
|
148 | config.TerminalInteractiveShell.colors = 'NoColor' | |
149 | config.TerminalTerminalInteractiveShell.term_title = False, |
|
149 | config.TerminalTerminalInteractiveShell.term_title = False, | |
150 | config.TerminalInteractiveShell.autocall = 0 |
|
150 | config.TerminalInteractiveShell.autocall = 0 | |
151 | config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite') |
|
151 | config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite') | |
152 | config.HistoryManager.db_cache_size = 10000 |
|
152 | config.HistoryManager.db_cache_size = 10000 | |
153 | return config |
|
153 | return config | |
154 |
|
154 | |||
155 |
|
155 | |||
156 | def ipexec(fname, options=None): |
|
156 | def ipexec(fname, options=None): | |
157 | """Utility to call 'ipython filename'. |
|
157 | """Utility to call 'ipython filename'. | |
158 |
|
158 | |||
159 | Starts IPython witha minimal and safe configuration to make startup as fast |
|
159 | Starts IPython witha minimal and safe configuration to make startup as fast | |
160 | as possible. |
|
160 | as possible. | |
161 |
|
161 | |||
162 | Note that this starts IPython in a subprocess! |
|
162 | Note that this starts IPython in a subprocess! | |
163 |
|
163 | |||
164 | Parameters |
|
164 | Parameters | |
165 | ---------- |
|
165 | ---------- | |
166 | fname : str |
|
166 | fname : str | |
167 | Name of file to be executed (should have .py or .ipy extension). |
|
167 | Name of file to be executed (should have .py or .ipy extension). | |
168 |
|
168 | |||
169 | options : optional, list |
|
169 | options : optional, list | |
170 | Extra command-line flags to be passed to IPython. |
|
170 | Extra command-line flags to be passed to IPython. | |
171 |
|
171 | |||
172 | Returns |
|
172 | Returns | |
173 | ------- |
|
173 | ------- | |
174 | (stdout, stderr) of ipython subprocess. |
|
174 | (stdout, stderr) of ipython subprocess. | |
175 | """ |
|
175 | """ | |
176 | if options is None: options = [] |
|
176 | if options is None: options = [] | |
177 |
|
177 | |||
178 | # For these subprocess calls, eliminate all prompt printing so we only see |
|
178 | # For these subprocess calls, eliminate all prompt printing so we only see | |
179 | # output from script execution |
|
179 | # output from script execution | |
180 | prompt_opts = [ '--PromptManager.in_template=""', |
|
180 | prompt_opts = [ '--PromptManager.in_template=""', | |
181 | '--PromptManager.in2_template=""', |
|
181 | '--PromptManager.in2_template=""', | |
182 | '--PromptManager.out_template=""' |
|
182 | '--PromptManager.out_template=""' | |
183 | ] |
|
183 | ] | |
184 | cmdargs = ' '.join(default_argv() + prompt_opts + options) |
|
184 | cmdargs = ' '.join(default_argv() + prompt_opts + options) | |
185 |
|
185 | |||
186 | _ip = get_ipython() |
|
186 | _ip = get_ipython() | |
187 | test_dir = os.path.dirname(__file__) |
|
187 | test_dir = os.path.dirname(__file__) | |
188 |
|
188 | |||
189 | ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython') |
|
189 | ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython') | |
190 | # Absolute path for filename |
|
190 | # Absolute path for filename | |
191 | full_fname = os.path.join(test_dir, fname) |
|
191 | full_fname = os.path.join(test_dir, fname) | |
192 | full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname) |
|
192 | full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname) | |
193 | #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg |
|
193 | #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg | |
194 | out, err = getoutputerror(full_cmd) |
|
194 | out, err = getoutputerror(full_cmd) | |
195 | # `import readline` causes 'ESC[?1034h' to be output sometimes, |
|
195 | # `import readline` causes 'ESC[?1034h' to be output sometimes, | |
196 | # so strip that out before doing comparisons |
|
196 | # so strip that out before doing comparisons | |
197 | if out: |
|
197 | if out: | |
198 | out = re.sub(r'\x1b\[[^h]+h', '', out) |
|
198 | out = re.sub(r'\x1b\[[^h]+h', '', out) | |
199 | return out, err |
|
199 | return out, err | |
200 |
|
200 | |||
201 |
|
201 | |||
202 | def ipexec_validate(fname, expected_out, expected_err='', |
|
202 | def ipexec_validate(fname, expected_out, expected_err='', | |
203 | options=None): |
|
203 | options=None): | |
204 | """Utility to call 'ipython filename' and validate output/error. |
|
204 | """Utility to call 'ipython filename' and validate output/error. | |
205 |
|
205 | |||
206 | This function raises an AssertionError if the validation fails. |
|
206 | This function raises an AssertionError if the validation fails. | |
207 |
|
207 | |||
208 | Note that this starts IPython in a subprocess! |
|
208 | Note that this starts IPython in a subprocess! | |
209 |
|
209 | |||
210 | Parameters |
|
210 | Parameters | |
211 | ---------- |
|
211 | ---------- | |
212 | fname : str |
|
212 | fname : str | |
213 | Name of the file to be executed (should have .py or .ipy extension). |
|
213 | Name of the file to be executed (should have .py or .ipy extension). | |
214 |
|
214 | |||
215 | expected_out : str |
|
215 | expected_out : str | |
216 | Expected stdout of the process. |
|
216 | Expected stdout of the process. | |
217 |
|
217 | |||
218 | expected_err : optional, str |
|
218 | expected_err : optional, str | |
219 | Expected stderr of the process. |
|
219 | Expected stderr of the process. | |
220 |
|
220 | |||
221 | options : optional, list |
|
221 | options : optional, list | |
222 | Extra command-line flags to be passed to IPython. |
|
222 | Extra command-line flags to be passed to IPython. | |
223 |
|
223 | |||
224 | Returns |
|
224 | Returns | |
225 | ------- |
|
225 | ------- | |
226 | None |
|
226 | None | |
227 | """ |
|
227 | """ | |
228 |
|
228 | |||
229 | import nose.tools as nt |
|
229 | import nose.tools as nt | |
230 |
|
230 | |||
231 | out, err = ipexec(fname, options) |
|
231 | out, err = ipexec(fname, options) | |
232 | #print 'OUT', out # dbg |
|
232 | #print 'OUT', out # dbg | |
233 | #print 'ERR', err # dbg |
|
233 | #print 'ERR', err # dbg | |
234 | # If there are any errors, we must check those befor stdout, as they may be |
|
234 | # If there are any errors, we must check those befor stdout, as they may be | |
235 | # more informative than simply having an empty stdout. |
|
235 | # more informative than simply having an empty stdout. | |
236 | if err: |
|
236 | if err: | |
237 | if expected_err: |
|
237 | if expected_err: | |
238 | nt.assert_equal(err.strip(), expected_err.strip()) |
|
238 | nt.assert_equal(err.strip(), expected_err.strip()) | |
239 | else: |
|
239 | else: | |
240 | raise ValueError('Running file %r produced error: %r' % |
|
240 | raise ValueError('Running file %r produced error: %r' % | |
241 | (fname, err)) |
|
241 | (fname, err)) | |
242 | # If no errors or output on stderr was expected, match stdout |
|
242 | # If no errors or output on stderr was expected, match stdout | |
243 | nt.assert_equal(out.strip(), expected_out.strip()) |
|
243 | nt.assert_equal(out.strip(), expected_out.strip()) | |
244 |
|
244 | |||
245 |
|
245 | |||
246 | class TempFileMixin(object): |
|
246 | class TempFileMixin(object): | |
247 | """Utility class to create temporary Python/IPython files. |
|
247 | """Utility class to create temporary Python/IPython files. | |
248 |
|
248 | |||
249 | Meant as a mixin class for test cases.""" |
|
249 | Meant as a mixin class for test cases.""" | |
250 |
|
250 | |||
251 | def mktmp(self, src, ext='.py'): |
|
251 | def mktmp(self, src, ext='.py'): | |
252 | """Make a valid python temp file.""" |
|
252 | """Make a valid python temp file.""" | |
253 | fname, f = temp_pyfile(src, ext) |
|
253 | fname, f = temp_pyfile(src, ext) | |
254 | self.tmpfile = f |
|
254 | self.tmpfile = f | |
255 | self.fname = fname |
|
255 | self.fname = fname | |
256 |
|
256 | |||
257 | def tearDown(self): |
|
257 | def tearDown(self): | |
258 | if hasattr(self, 'tmpfile'): |
|
258 | if hasattr(self, 'tmpfile'): | |
259 | # If the tmpfile wasn't made because of skipped tests, like in |
|
259 | # If the tmpfile wasn't made because of skipped tests, like in | |
260 | # win32, there's nothing to cleanup. |
|
260 | # win32, there's nothing to cleanup. | |
261 | self.tmpfile.close() |
|
261 | self.tmpfile.close() | |
262 | try: |
|
262 | try: | |
263 | os.unlink(self.fname) |
|
263 | os.unlink(self.fname) | |
264 | except: |
|
264 | except: | |
265 | # On Windows, even though we close the file, we still can't |
|
265 | # On Windows, even though we close the file, we still can't | |
266 | # delete it. I have no clue why |
|
266 | # delete it. I have no clue why | |
267 | pass |
|
267 | pass | |
268 |
|
268 | |||
269 | pair_fail_msg = ("Testing {0}\n\n" |
|
269 | pair_fail_msg = ("Testing {0}\n\n" | |
270 | "In:\n" |
|
270 | "In:\n" | |
271 | " {1!r}\n" |
|
271 | " {1!r}\n" | |
272 | "Expected:\n" |
|
272 | "Expected:\n" | |
273 | " {2!r}\n" |
|
273 | " {2!r}\n" | |
274 | "Got:\n" |
|
274 | "Got:\n" | |
275 | " {3!r}\n") |
|
275 | " {3!r}\n") | |
276 | def check_pairs(func, pairs): |
|
276 | def check_pairs(func, pairs): | |
277 | """Utility function for the common case of checking a function with a |
|
277 | """Utility function for the common case of checking a function with a | |
278 | sequence of input/output pairs. |
|
278 | sequence of input/output pairs. | |
279 |
|
279 | |||
280 | Parameters |
|
280 | Parameters | |
281 | ---------- |
|
281 | ---------- | |
282 | func : callable |
|
282 | func : callable | |
283 | The function to be tested. Should accept a single argument. |
|
283 | The function to be tested. Should accept a single argument. | |
284 | pairs : iterable |
|
284 | pairs : iterable | |
285 | A list of (input, expected_output) tuples. |
|
285 | A list of (input, expected_output) tuples. | |
286 |
|
286 | |||
287 | Returns |
|
287 | Returns | |
288 | ------- |
|
288 | ------- | |
289 | None. Raises an AssertionError if any output does not match the expected |
|
289 | None. Raises an AssertionError if any output does not match the expected | |
290 | value. |
|
290 | value. | |
291 | """ |
|
291 | """ | |
292 | name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>")) |
|
292 | name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>")) | |
293 | for inp, expected in pairs: |
|
293 | for inp, expected in pairs: | |
294 | out = func(inp) |
|
294 | out = func(inp) | |
295 | assert out == expected, pair_fail_msg.format(name, inp, expected, out) |
|
295 | assert out == expected, pair_fail_msg.format(name, inp, expected, out) | |
296 |
|
296 | |||
297 |
|
297 | |||
298 | if py3compat.PY3: |
|
298 | if py3compat.PY3: | |
299 | MyStringIO = StringIO |
|
299 | MyStringIO = StringIO | |
300 | else: |
|
300 | else: | |
301 | # In Python 2, stdout/stderr can have either bytes or unicode written to them, |
|
301 | # In Python 2, stdout/stderr can have either bytes or unicode written to them, | |
302 | # so we need a class that can handle both. |
|
302 | # so we need a class that can handle both. | |
303 | class MyStringIO(StringIO): |
|
303 | class MyStringIO(StringIO): | |
304 | def write(self, s): |
|
304 | def write(self, s): | |
305 | s = py3compat.cast_unicode(s, encoding=DEFAULT_ENCODING) |
|
305 | s = py3compat.cast_unicode(s, encoding=DEFAULT_ENCODING) | |
306 | super(MyStringIO, self).write(s) |
|
306 | super(MyStringIO, self).write(s) | |
307 |
|
307 | |||
308 | notprinted_msg = """Did not find {0!r} in printed output (on {1}): |
|
308 | notprinted_msg = """Did not find {0!r} in printed output (on {1}): | |
309 | {2!r}""" |
|
309 | ------- | |
|
310 | {2!s} | |||
|
311 | ------- | |||
|
312 | """ | |||
310 |
|
313 | |||
311 | class AssertPrints(object): |
|
314 | class AssertPrints(object): | |
312 | """Context manager for testing that code prints certain text. |
|
315 | """Context manager for testing that code prints certain text. | |
313 |
|
316 | |||
314 | Examples |
|
317 | Examples | |
315 | -------- |
|
318 | -------- | |
316 | >>> with AssertPrints("abc", suppress=False): |
|
319 | >>> with AssertPrints("abc", suppress=False): | |
317 | ... print "abcd" |
|
320 | ... print "abcd" | |
318 | ... print "def" |
|
321 | ... print "def" | |
319 | ... |
|
322 | ... | |
320 | abcd |
|
323 | abcd | |
321 | def |
|
324 | def | |
322 | """ |
|
325 | """ | |
323 | def __init__(self, s, channel='stdout', suppress=True): |
|
326 | def __init__(self, s, channel='stdout', suppress=True): | |
324 | self.s = s |
|
327 | self.s = s | |
325 | self.channel = channel |
|
328 | self.channel = channel | |
326 | self.suppress = suppress |
|
329 | self.suppress = suppress | |
327 |
|
330 | |||
328 | def __enter__(self): |
|
331 | def __enter__(self): | |
329 | self.orig_stream = getattr(sys, self.channel) |
|
332 | self.orig_stream = getattr(sys, self.channel) | |
330 | self.buffer = MyStringIO() |
|
333 | self.buffer = MyStringIO() | |
331 | self.tee = Tee(self.buffer, channel=self.channel) |
|
334 | self.tee = Tee(self.buffer, channel=self.channel) | |
332 | setattr(sys, self.channel, self.buffer if self.suppress else self.tee) |
|
335 | setattr(sys, self.channel, self.buffer if self.suppress else self.tee) | |
333 |
|
336 | |||
334 | def __exit__(self, etype, value, traceback): |
|
337 | def __exit__(self, etype, value, traceback): | |
335 | self.tee.flush() |
|
338 | self.tee.flush() | |
336 | setattr(sys, self.channel, self.orig_stream) |
|
339 | setattr(sys, self.channel, self.orig_stream) | |
337 | printed = self.buffer.getvalue() |
|
340 | printed = self.buffer.getvalue() | |
338 | assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed) |
|
341 | assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed) | |
339 | return False |
|
342 | return False | |
340 |
|
343 | |||
|
344 | printed_msg = """Found {0!r} in printed output (on {1}): | |||
|
345 | ------- | |||
|
346 | {2!s} | |||
|
347 | ------- | |||
|
348 | """ | |||
|
349 | ||||
341 | class AssertNotPrints(AssertPrints): |
|
350 | class AssertNotPrints(AssertPrints): | |
342 | """Context manager for checking that certain output *isn't* produced. |
|
351 | """Context manager for checking that certain output *isn't* produced. | |
343 |
|
352 | |||
344 | Counterpart of AssertPrints""" |
|
353 | Counterpart of AssertPrints""" | |
345 | def __exit__(self, etype, value, traceback): |
|
354 | def __exit__(self, etype, value, traceback): | |
346 | self.tee.flush() |
|
355 | self.tee.flush() | |
347 | setattr(sys, self.channel, self.orig_stream) |
|
356 | setattr(sys, self.channel, self.orig_stream) | |
348 | printed = self.buffer.getvalue() |
|
357 | printed = self.buffer.getvalue() | |
349 |
assert self.s not in printed, |
|
358 | assert self.s not in printed, printed_msg.format(self.s, self.channel, printed) | |
350 | return False |
|
359 | return False | |
351 |
|
360 | |||
352 | @contextmanager |
|
361 | @contextmanager | |
353 | def mute_warn(): |
|
362 | def mute_warn(): | |
354 | from IPython.utils import warn |
|
363 | from IPython.utils import warn | |
355 | save_warn = warn.warn |
|
364 | save_warn = warn.warn | |
356 | warn.warn = lambda *a, **kw: None |
|
365 | warn.warn = lambda *a, **kw: None | |
357 | try: |
|
366 | try: | |
358 | yield |
|
367 | yield | |
359 | finally: |
|
368 | finally: | |
360 | warn.warn = save_warn |
|
369 | warn.warn = save_warn | |
361 |
|
370 | |||
362 | @contextmanager |
|
371 | @contextmanager | |
363 | def make_tempfile(name): |
|
372 | def make_tempfile(name): | |
364 | """ Create an empty, named, temporary file for the duration of the context. |
|
373 | """ Create an empty, named, temporary file for the duration of the context. | |
365 | """ |
|
374 | """ | |
366 | f = open(name, 'w') |
|
375 | f = open(name, 'w') | |
367 | f.close() |
|
376 | f.close() | |
368 | try: |
|
377 | try: | |
369 | yield |
|
378 | yield | |
370 | finally: |
|
379 | finally: | |
371 | os.unlink(name) |
|
380 | os.unlink(name) | |
372 |
|
381 | |||
373 |
|
382 | |||
374 | @contextmanager |
|
383 | @contextmanager | |
375 | def monkeypatch(obj, name, attr): |
|
384 | def monkeypatch(obj, name, attr): | |
376 | """ |
|
385 | """ | |
377 | Context manager to replace attribute named `name` in `obj` with `attr`. |
|
386 | Context manager to replace attribute named `name` in `obj` with `attr`. | |
378 | """ |
|
387 | """ | |
379 | orig = getattr(obj, name) |
|
388 | orig = getattr(obj, name) | |
380 | setattr(obj, name, attr) |
|
389 | setattr(obj, name, attr) | |
381 | yield |
|
390 | yield | |
382 | setattr(obj, name, orig) |
|
391 | setattr(obj, name, orig) |
General Comments 0
You need to be logged in to leave comments.
Login now