blob: 5bce2af68a960df8fb5e126d3c7e86bbe5483598 [file] [log] [blame]
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +00001"""Test cases for traceback module"""
2
Benjamin Petersone6528212008-07-15 15:32:09 +00003from _testcapi import traceback_print, exception_print
Christian Heimes81ee3ef2008-05-04 22:42:01 +00004from io import StringIO
5import sys
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +00006import unittest
Benjamin Petersone6528212008-07-15 15:32:09 +00007import re
Benjamin Peterson26d64ae2010-09-20 21:47:37 +00008from test.support import run_unittest, Error, captured_output
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +00009from test.support import TESTFN, unlink
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000010
11import traceback
12
Christian Heimes81ee3ef2008-05-04 22:42:01 +000013
Benjamin Petersone6528212008-07-15 15:32:09 +000014class SyntaxTracebackCases(unittest.TestCase):
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000015 # For now, a very minimal set of tests. I want to be sure that
16 # formatting of SyntaxErrors works based on changes for 2.1.
17
18 def get_exception_format(self, func, exc):
19 try:
20 func()
Guido van Rossumb940e112007-01-10 16:19:56 +000021 except exc as value:
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000022 return traceback.format_exception_only(exc, value)
23 else:
Collin Winter3add4d72007-08-29 23:37:32 +000024 raise ValueError("call did not raise exception")
Tim Peters7e01e282001-04-08 07:44:07 +000025
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000026 def syntax_error_with_caret(self):
27 compile("def fact(x):\n\treturn x!\n", "?", "exec")
28
Georg Brandl751899a2009-06-04 19:41:00 +000029 def syntax_error_with_caret_2(self):
30 compile("1 +\n", "?", "exec")
31
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000032 def syntax_error_bad_indentation(self):
Georg Brandl88fc6642007-02-09 21:28:07 +000033 compile("def spam():\n print(1)\n print(2)", "?", "exec")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000034
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000035 def test_caret(self):
36 err = self.get_exception_format(self.syntax_error_with_caret,
37 SyntaxError)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000038 self.assertEqual(len(err), 4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000039 self.assertTrue(err[1].strip() == "return x!")
Benjamin Peterson577473f2010-01-19 00:09:57 +000040 self.assertIn("^", err[2]) # third line has caret
Guido van Rossume61fd5b2007-07-11 12:20:59 +000041 self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place
Tim Peters7e01e282001-04-08 07:44:07 +000042
Georg Brandl751899a2009-06-04 19:41:00 +000043 err = self.get_exception_format(self.syntax_error_with_caret_2,
44 SyntaxError)
Benjamin Peterson577473f2010-01-19 00:09:57 +000045 self.assertIn("^", err[2]) # third line has caret
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000046 self.assertTrue(err[2].count('\n') == 1) # and no additional newline
47 self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place
Georg Brandl751899a2009-06-04 19:41:00 +000048
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000049 def test_nocaret(self):
Benjamin Peterson26d64ae2010-09-20 21:47:37 +000050 exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
51 err = traceback.format_exception_only(SyntaxError, exc)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000052 self.assertEqual(len(err), 3)
Benjamin Peterson26d64ae2010-09-20 21:47:37 +000053 self.assertEqual(err[1].strip(), "bad syntax")
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000054
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000055 def test_bad_indentation(self):
56 err = self.get_exception_format(self.syntax_error_bad_indentation,
57 IndentationError)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000058 self.assertEqual(len(err), 4)
59 self.assertEqual(err[1].strip(), "print(2)")
Benjamin Peterson577473f2010-01-19 00:09:57 +000060 self.assertIn("^", err[2])
Guido van Rossume61fd5b2007-07-11 12:20:59 +000061 self.assertEqual(err[1].find(")"), err[2].find("^"))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062
Thomas Wouters477c8d52006-05-27 19:21:47 +000063 def test_base_exception(self):
64 # Test that exceptions derived from BaseException are formatted right
65 e = KeyboardInterrupt()
66 lst = traceback.format_exception_only(e.__class__, e)
67 self.assertEqual(lst, ['KeyboardInterrupt\n'])
68
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069 def test_format_exception_only_bad__str__(self):
70 class X(Exception):
71 def __str__(self):
72 1/0
73 err = traceback.format_exception_only(X, X())
74 self.assertEqual(len(err), 1)
75 str_value = '<unprintable %s object>' % X.__name__
Georg Brandl1a3284e2007-12-02 09:40:06 +000076 if X.__module__ in ('__main__', 'builtins'):
Brett Cannon44c52612007-02-27 00:12:43 +000077 str_name = X.__name__
78 else:
79 str_name = '.'.join([X.__module__, X.__name__])
80 self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081
Thomas Wouters89f507f2006-12-13 04:49:30 +000082 def test_without_exception(self):
83 err = traceback.format_exception_only(None, None)
84 self.assertEqual(err, ['None\n'])
85
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +000086 def test_encoded_file(self):
87 # Test that tracebacks are correctly printed for encoded source files:
88 # - correct line number (Issue2384)
89 # - respect file encoding (Issue3975)
90 import tempfile, sys, subprocess, os
91
92 # The spawned subprocess has its stdout redirected to a PIPE, and its
93 # encoding may be different from the current interpreter, on Windows
94 # at least.
95 process = subprocess.Popen([sys.executable, "-c",
96 "import sys; print(sys.stdout.encoding)"],
97 stdout=subprocess.PIPE,
98 stderr=subprocess.STDOUT)
99 stdout, stderr = process.communicate()
100 output_encoding = str(stdout, 'ascii').splitlines()[0]
101
102 def do_test(firstlines, message, charset, lineno):
103 # Raise the message in a subprocess, and catch the output
104 try:
105 output = open(TESTFN, "w", encoding=charset)
106 output.write("""{0}if 1:
107 import traceback;
108 raise RuntimeError('{1}')
109 """.format(firstlines, message))
110 output.close()
111 process = subprocess.Popen([sys.executable, TESTFN],
112 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
113 stdout, stderr = process.communicate()
114 stdout = stdout.decode(output_encoding).splitlines()
115 finally:
116 unlink(TESTFN)
117
118 # The source lines are encoded with the 'backslashreplace' handler
119 encoded_message = message.encode(output_encoding,
120 'backslashreplace')
121 # and we just decoded them with the output_encoding.
122 message_ascii = encoded_message.decode(output_encoding)
123
124 err_line = "raise RuntimeError('{0}')".format(message_ascii)
125 err_msg = "RuntimeError: {0}".format(message_ascii)
126
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000127 self.assertIn(("line %s" % lineno), stdout[1],
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000128 "Invalid line number: {0!r} instead of {1}".format(
129 stdout[1], lineno))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000130 self.assertTrue(stdout[2].endswith(err_line),
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000131 "Invalid traceback line: {0!r} instead of {1!r}".format(
132 stdout[2], err_line))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000133 self.assertTrue(stdout[3] == err_msg,
Amaury Forgeot d'Arccf8016a2008-10-09 23:37:48 +0000134 "Invalid error message: {0!r} instead of {1!r}".format(
135 stdout[3], err_msg))
136
137 do_test("", "foo", "ascii", 3)
138 for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"):
139 if charset == "ascii":
140 text = "foo"
141 elif charset == "GBK":
142 text = "\u4E02\u5100"
143 else:
144 text = "h\xe9 ho"
145 do_test("# coding: {0}\n".format(charset),
146 text, charset, 4)
147 do_test("#!shebang\n# coding: {0}\n".format(charset),
148 text, charset, 5)
149
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000151class TracebackFormatTests(unittest.TestCase):
152
Georg Brandl236f7972009-04-05 14:28:42 +0000153 def test_traceback_format(self):
154 try:
155 raise KeyError('blah')
156 except KeyError:
157 type_, value, tb = sys.exc_info()
158 traceback_fmt = 'Traceback (most recent call last):\n' + \
159 ''.join(traceback.format_tb(tb))
160 file_ = StringIO()
161 traceback_print(tb, file_)
162 python_fmt = file_.getvalue()
163 else:
164 raise Error("unable to create test traceback string")
165
166 # Make sure that Python and the traceback module format the same thing
Ezio Melottib3aedd42010-11-20 19:04:17 +0000167 self.assertEqual(traceback_fmt, python_fmt)
Georg Brandl236f7972009-04-05 14:28:42 +0000168
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000169 # Make sure that the traceback is properly indented.
Georg Brandl236f7972009-04-05 14:28:42 +0000170 tb_lines = python_fmt.splitlines()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000171 self.assertEqual(len(tb_lines), 3)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000172 banner, location, source_line = tb_lines
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000173 self.assertTrue(banner.startswith('Traceback'))
174 self.assertTrue(location.startswith(' File'))
175 self.assertTrue(source_line.startswith(' raise'))
Benjamin Petersone6528212008-07-15 15:32:09 +0000176
177
178cause_message = (
179 "\nThe above exception was the direct cause "
180 "of the following exception:\n\n")
181
182context_message = (
183 "\nDuring handling of the above exception, "
184 "another exception occurred:\n\n")
185
186boundaries = re.compile(
187 '(%s|%s)' % (re.escape(cause_message), re.escape(context_message)))
188
189
190class BaseExceptionReportingTests:
191
192 def get_exception(self, exception_or_callable):
193 if isinstance(exception_or_callable, Exception):
194 return exception_or_callable
195 try:
196 exception_or_callable()
197 except Exception as e:
198 return e
199
200 def zero_div(self):
201 1/0 # In zero_div
202
203 def check_zero_div(self, msg):
204 lines = msg.splitlines()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000205 self.assertTrue(lines[-3].startswith(' File'))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000206 self.assertIn('1/0 # In zero_div', lines[-2])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000207 self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1])
Benjamin Petersone6528212008-07-15 15:32:09 +0000208
209 def test_simple(self):
210 try:
211 1/0 # Marker
212 except ZeroDivisionError as _:
213 e = _
214 lines = self.get_report(e).splitlines()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000215 self.assertEqual(len(lines), 4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000216 self.assertTrue(lines[0].startswith('Traceback'))
217 self.assertTrue(lines[1].startswith(' File'))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000218 self.assertIn('1/0 # Marker', lines[2])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000219 self.assertTrue(lines[3].startswith('ZeroDivisionError'))
Benjamin Petersone6528212008-07-15 15:32:09 +0000220
221 def test_cause(self):
222 def inner_raise():
223 try:
224 self.zero_div()
225 except ZeroDivisionError as e:
226 raise KeyError from e
227 def outer_raise():
228 inner_raise() # Marker
229 blocks = boundaries.split(self.get_report(outer_raise))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000230 self.assertEqual(len(blocks), 3)
231 self.assertEqual(blocks[1], cause_message)
Benjamin Petersone6528212008-07-15 15:32:09 +0000232 self.check_zero_div(blocks[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000233 self.assertIn('inner_raise() # Marker', blocks[2])
Benjamin Petersone6528212008-07-15 15:32:09 +0000234
235 def test_context(self):
236 def inner_raise():
237 try:
238 self.zero_div()
239 except ZeroDivisionError:
240 raise KeyError
241 def outer_raise():
242 inner_raise() # Marker
243 blocks = boundaries.split(self.get_report(outer_raise))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000244 self.assertEqual(len(blocks), 3)
245 self.assertEqual(blocks[1], context_message)
Benjamin Petersone6528212008-07-15 15:32:09 +0000246 self.check_zero_div(blocks[0])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000247 self.assertIn('inner_raise() # Marker', blocks[2])
Benjamin Petersone6528212008-07-15 15:32:09 +0000248
Nick Coghlanab7bf212012-02-26 17:49:52 +1000249 def test_context_suppression(self):
250 try:
251 try:
252 raise Exception
253 except:
254 raise ZeroDivisionError from None
255 except ZeroDivisionError as _:
256 e = _
257 lines = self.get_report(e).splitlines()
258 self.assertEqual(len(lines), 4)
259 self.assertTrue(lines[0].startswith('Traceback'))
260 self.assertTrue(lines[1].startswith(' File'))
261 self.assertIn('ZeroDivisionError from None', lines[2])
262 self.assertTrue(lines[3].startswith('ZeroDivisionError'))
263
Antoine Pitrou7b0d4a22009-11-28 16:12:28 +0000264 def test_cause_and_context(self):
265 # When both a cause and a context are set, only the cause should be
266 # displayed and the context should be muted.
267 def inner_raise():
268 try:
269 self.zero_div()
270 except ZeroDivisionError as _e:
271 e = _e
272 try:
273 xyzzy
274 except NameError:
275 raise KeyError from e
276 def outer_raise():
277 inner_raise() # Marker
278 blocks = boundaries.split(self.get_report(outer_raise))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000279 self.assertEqual(len(blocks), 3)
280 self.assertEqual(blocks[1], cause_message)
Antoine Pitrou7b0d4a22009-11-28 16:12:28 +0000281 self.check_zero_div(blocks[0])
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000282 self.assertIn('inner_raise() # Marker', blocks[2])
Antoine Pitrou7b0d4a22009-11-28 16:12:28 +0000283
Benjamin Petersone6528212008-07-15 15:32:09 +0000284 def test_cause_recursive(self):
285 def inner_raise():
286 try:
287 try:
288 self.zero_div()
289 except ZeroDivisionError as e:
290 z = e
291 raise KeyError from e
292 except KeyError as e:
293 raise z from e
294 def outer_raise():
295 inner_raise() # Marker
296 blocks = boundaries.split(self.get_report(outer_raise))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000297 self.assertEqual(len(blocks), 3)
298 self.assertEqual(blocks[1], cause_message)
Benjamin Petersone6528212008-07-15 15:32:09 +0000299 # The first block is the KeyError raised from the ZeroDivisionError
Benjamin Peterson577473f2010-01-19 00:09:57 +0000300 self.assertIn('raise KeyError from e', blocks[0])
301 self.assertNotIn('1/0', blocks[0])
Benjamin Petersone6528212008-07-15 15:32:09 +0000302 # The second block (apart from the boundary) is the ZeroDivisionError
303 # re-raised from the KeyError
Benjamin Peterson577473f2010-01-19 00:09:57 +0000304 self.assertIn('inner_raise() # Marker', blocks[2])
Benjamin Petersone6528212008-07-15 15:32:09 +0000305 self.check_zero_div(blocks[2])
306
Benjamin Peterson503d6c52010-10-24 02:52:05 +0000307 def test_syntax_error_offset_at_eol(self):
308 # See #10186.
309 def e():
310 raise SyntaxError('', ('', 0, 5, 'hello'))
311 msg = self.get_report(e).splitlines()
312 self.assertEqual(msg[-2], " ^")
Benjamin Petersona95e9772010-10-29 03:28:14 +0000313 def e():
314 exec("x = 5 | 4 |")
315 msg = self.get_report(e).splitlines()
316 self.assertEqual(msg[-2], ' ^')
Benjamin Petersone6528212008-07-15 15:32:09 +0000317
318
319class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
320 #
321 # This checks reporting through the 'traceback' module, with both
322 # format_exception() and print_exception().
323 #
324
325 def get_report(self, e):
326 e = self.get_exception(e)
327 s = ''.join(
328 traceback.format_exception(type(e), e, e.__traceback__))
329 with captured_output("stderr") as sio:
330 traceback.print_exception(type(e), e, e.__traceback__)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000331 self.assertEqual(sio.getvalue(), s)
Benjamin Petersone6528212008-07-15 15:32:09 +0000332 return s
333
334
335class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
336 #
337 # This checks built-in reporting by the interpreter.
338 #
339
340 def get_report(self, e):
341 e = self.get_exception(e)
342 with captured_output("stderr") as s:
343 exception_print(e)
344 return s.getvalue()
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000345
346
Fred Drake2e2be372001-09-20 21:33:42 +0000347def test_main():
Benjamin Petersone6528212008-07-15 15:32:09 +0000348 run_unittest(__name__)
Fred Drake2e2be372001-09-20 21:33:42 +0000349
350if __name__ == "__main__":
351 test_main()