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