1 | n/a | """Test cases for traceback module""" |
---|
2 | n/a | |
---|
3 | n/a | from collections import namedtuple |
---|
4 | n/a | from io import StringIO |
---|
5 | n/a | import linecache |
---|
6 | n/a | import sys |
---|
7 | n/a | import unittest |
---|
8 | n/a | import re |
---|
9 | n/a | from test import support |
---|
10 | n/a | from test.support import TESTFN, Error, captured_output, unlink, cpython_only |
---|
11 | n/a | from test.support.script_helper import assert_python_ok |
---|
12 | n/a | import textwrap |
---|
13 | n/a | |
---|
14 | n/a | import traceback |
---|
15 | n/a | |
---|
16 | n/a | |
---|
17 | n/a | test_code = namedtuple('code', ['co_filename', 'co_name']) |
---|
18 | n/a | test_frame = namedtuple('frame', ['f_code', 'f_globals', 'f_locals']) |
---|
19 | n/a | test_tb = namedtuple('tb', ['tb_frame', 'tb_lineno', 'tb_next']) |
---|
20 | n/a | |
---|
21 | n/a | |
---|
22 | n/a | class TracebackCases(unittest.TestCase): |
---|
23 | n/a | # For now, a very minimal set of tests. I want to be sure that |
---|
24 | n/a | # formatting of SyntaxErrors works based on changes for 2.1. |
---|
25 | n/a | |
---|
26 | n/a | def get_exception_format(self, func, exc): |
---|
27 | n/a | try: |
---|
28 | n/a | func() |
---|
29 | n/a | except exc as value: |
---|
30 | n/a | return traceback.format_exception_only(exc, value) |
---|
31 | n/a | else: |
---|
32 | n/a | raise ValueError("call did not raise exception") |
---|
33 | n/a | |
---|
34 | n/a | def syntax_error_with_caret(self): |
---|
35 | n/a | compile("def fact(x):\n\treturn x!\n", "?", "exec") |
---|
36 | n/a | |
---|
37 | n/a | def syntax_error_with_caret_2(self): |
---|
38 | n/a | compile("1 +\n", "?", "exec") |
---|
39 | n/a | |
---|
40 | n/a | def syntax_error_bad_indentation(self): |
---|
41 | n/a | compile("def spam():\n print(1)\n print(2)", "?", "exec") |
---|
42 | n/a | |
---|
43 | n/a | def syntax_error_with_caret_non_ascii(self): |
---|
44 | n/a | compile('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', "?", "exec") |
---|
45 | n/a | |
---|
46 | n/a | def syntax_error_bad_indentation2(self): |
---|
47 | n/a | compile(" print(2)", "?", "exec") |
---|
48 | n/a | |
---|
49 | n/a | def test_caret(self): |
---|
50 | n/a | err = self.get_exception_format(self.syntax_error_with_caret, |
---|
51 | n/a | SyntaxError) |
---|
52 | n/a | self.assertEqual(len(err), 4) |
---|
53 | n/a | self.assertTrue(err[1].strip() == "return x!") |
---|
54 | n/a | self.assertIn("^", err[2]) # third line has caret |
---|
55 | n/a | self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place |
---|
56 | n/a | |
---|
57 | n/a | err = self.get_exception_format(self.syntax_error_with_caret_2, |
---|
58 | n/a | SyntaxError) |
---|
59 | n/a | self.assertIn("^", err[2]) # third line has caret |
---|
60 | n/a | self.assertEqual(err[2].count('\n'), 1) # and no additional newline |
---|
61 | n/a | self.assertEqual(err[1].find("+"), err[2].find("^")) # in the right place |
---|
62 | n/a | |
---|
63 | n/a | err = self.get_exception_format(self.syntax_error_with_caret_non_ascii, |
---|
64 | n/a | SyntaxError) |
---|
65 | n/a | self.assertIn("^", err[2]) # third line has caret |
---|
66 | n/a | self.assertEqual(err[2].count('\n'), 1) # and no additional newline |
---|
67 | n/a | self.assertEqual(err[1].find("+"), err[2].find("^")) # in the right place |
---|
68 | n/a | |
---|
69 | n/a | def test_nocaret(self): |
---|
70 | n/a | exc = SyntaxError("error", ("x.py", 23, None, "bad syntax")) |
---|
71 | n/a | err = traceback.format_exception_only(SyntaxError, exc) |
---|
72 | n/a | self.assertEqual(len(err), 3) |
---|
73 | n/a | self.assertEqual(err[1].strip(), "bad syntax") |
---|
74 | n/a | |
---|
75 | n/a | def test_bad_indentation(self): |
---|
76 | n/a | err = self.get_exception_format(self.syntax_error_bad_indentation, |
---|
77 | n/a | IndentationError) |
---|
78 | n/a | self.assertEqual(len(err), 4) |
---|
79 | n/a | self.assertEqual(err[1].strip(), "print(2)") |
---|
80 | n/a | self.assertIn("^", err[2]) |
---|
81 | n/a | self.assertEqual(err[1].find(")"), err[2].find("^")) |
---|
82 | n/a | |
---|
83 | n/a | err = self.get_exception_format(self.syntax_error_bad_indentation2, |
---|
84 | n/a | IndentationError) |
---|
85 | n/a | self.assertEqual(len(err), 4) |
---|
86 | n/a | self.assertEqual(err[1].strip(), "print(2)") |
---|
87 | n/a | self.assertIn("^", err[2]) |
---|
88 | n/a | self.assertEqual(err[1].find("p"), err[2].find("^")) |
---|
89 | n/a | |
---|
90 | n/a | def test_base_exception(self): |
---|
91 | n/a | # Test that exceptions derived from BaseException are formatted right |
---|
92 | n/a | e = KeyboardInterrupt() |
---|
93 | n/a | lst = traceback.format_exception_only(e.__class__, e) |
---|
94 | n/a | self.assertEqual(lst, ['KeyboardInterrupt\n']) |
---|
95 | n/a | |
---|
96 | n/a | def test_format_exception_only_bad__str__(self): |
---|
97 | n/a | class X(Exception): |
---|
98 | n/a | def __str__(self): |
---|
99 | n/a | 1/0 |
---|
100 | n/a | err = traceback.format_exception_only(X, X()) |
---|
101 | n/a | self.assertEqual(len(err), 1) |
---|
102 | n/a | str_value = '<unprintable %s object>' % X.__name__ |
---|
103 | n/a | if X.__module__ in ('__main__', 'builtins'): |
---|
104 | n/a | str_name = X.__qualname__ |
---|
105 | n/a | else: |
---|
106 | n/a | str_name = '.'.join([X.__module__, X.__qualname__]) |
---|
107 | n/a | self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value)) |
---|
108 | n/a | |
---|
109 | n/a | def test_encoded_file(self): |
---|
110 | n/a | # Test that tracebacks are correctly printed for encoded source files: |
---|
111 | n/a | # - correct line number (Issue2384) |
---|
112 | n/a | # - respect file encoding (Issue3975) |
---|
113 | n/a | import tempfile, sys, subprocess, os |
---|
114 | n/a | |
---|
115 | n/a | # The spawned subprocess has its stdout redirected to a PIPE, and its |
---|
116 | n/a | # encoding may be different from the current interpreter, on Windows |
---|
117 | n/a | # at least. |
---|
118 | n/a | process = subprocess.Popen([sys.executable, "-c", |
---|
119 | n/a | "import sys; print(sys.stdout.encoding)"], |
---|
120 | n/a | stdout=subprocess.PIPE, |
---|
121 | n/a | stderr=subprocess.STDOUT) |
---|
122 | n/a | stdout, stderr = process.communicate() |
---|
123 | n/a | output_encoding = str(stdout, 'ascii').splitlines()[0] |
---|
124 | n/a | |
---|
125 | n/a | def do_test(firstlines, message, charset, lineno): |
---|
126 | n/a | # Raise the message in a subprocess, and catch the output |
---|
127 | n/a | try: |
---|
128 | n/a | with open(TESTFN, "w", encoding=charset) as output: |
---|
129 | n/a | output.write("""{0}if 1: |
---|
130 | n/a | import traceback; |
---|
131 | n/a | raise RuntimeError('{1}') |
---|
132 | n/a | """.format(firstlines, message)) |
---|
133 | n/a | |
---|
134 | n/a | process = subprocess.Popen([sys.executable, TESTFN], |
---|
135 | n/a | stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
---|
136 | n/a | stdout, stderr = process.communicate() |
---|
137 | n/a | stdout = stdout.decode(output_encoding).splitlines() |
---|
138 | n/a | finally: |
---|
139 | n/a | unlink(TESTFN) |
---|
140 | n/a | |
---|
141 | n/a | # The source lines are encoded with the 'backslashreplace' handler |
---|
142 | n/a | encoded_message = message.encode(output_encoding, |
---|
143 | n/a | 'backslashreplace') |
---|
144 | n/a | # and we just decoded them with the output_encoding. |
---|
145 | n/a | message_ascii = encoded_message.decode(output_encoding) |
---|
146 | n/a | |
---|
147 | n/a | err_line = "raise RuntimeError('{0}')".format(message_ascii) |
---|
148 | n/a | err_msg = "RuntimeError: {0}".format(message_ascii) |
---|
149 | n/a | |
---|
150 | n/a | self.assertIn(("line %s" % lineno), stdout[1], |
---|
151 | n/a | "Invalid line number: {0!r} instead of {1}".format( |
---|
152 | n/a | stdout[1], lineno)) |
---|
153 | n/a | self.assertTrue(stdout[2].endswith(err_line), |
---|
154 | n/a | "Invalid traceback line: {0!r} instead of {1!r}".format( |
---|
155 | n/a | stdout[2], err_line)) |
---|
156 | n/a | self.assertTrue(stdout[3] == err_msg, |
---|
157 | n/a | "Invalid error message: {0!r} instead of {1!r}".format( |
---|
158 | n/a | stdout[3], err_msg)) |
---|
159 | n/a | |
---|
160 | n/a | do_test("", "foo", "ascii", 3) |
---|
161 | n/a | for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"): |
---|
162 | n/a | if charset == "ascii": |
---|
163 | n/a | text = "foo" |
---|
164 | n/a | elif charset == "GBK": |
---|
165 | n/a | text = "\u4E02\u5100" |
---|
166 | n/a | else: |
---|
167 | n/a | text = "h\xe9 ho" |
---|
168 | n/a | do_test("# coding: {0}\n".format(charset), |
---|
169 | n/a | text, charset, 4) |
---|
170 | n/a | do_test("#!shebang\n# coding: {0}\n".format(charset), |
---|
171 | n/a | text, charset, 5) |
---|
172 | n/a | do_test(" \t\f\n# coding: {0}\n".format(charset), |
---|
173 | n/a | text, charset, 5) |
---|
174 | n/a | # Issue #18960: coding spec should have no effect |
---|
175 | n/a | do_test("x=0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5) |
---|
176 | n/a | |
---|
177 | n/a | @support.requires_type_collecting |
---|
178 | n/a | def test_print_traceback_at_exit(self): |
---|
179 | n/a | # Issue #22599: Ensure that it is possible to use the traceback module |
---|
180 | n/a | # to display an exception at Python exit |
---|
181 | n/a | code = textwrap.dedent(""" |
---|
182 | n/a | import sys |
---|
183 | n/a | import traceback |
---|
184 | n/a | |
---|
185 | n/a | class PrintExceptionAtExit(object): |
---|
186 | n/a | def __init__(self): |
---|
187 | n/a | try: |
---|
188 | n/a | x = 1 / 0 |
---|
189 | n/a | except Exception: |
---|
190 | n/a | self.exc_info = sys.exc_info() |
---|
191 | n/a | # self.exc_info[1] (traceback) contains frames: |
---|
192 | n/a | # explicitly clear the reference to self in the current |
---|
193 | n/a | # frame to break a reference cycle |
---|
194 | n/a | self = None |
---|
195 | n/a | |
---|
196 | n/a | def __del__(self): |
---|
197 | n/a | traceback.print_exception(*self.exc_info) |
---|
198 | n/a | |
---|
199 | n/a | # Keep a reference in the module namespace to call the destructor |
---|
200 | n/a | # when the module is unloaded |
---|
201 | n/a | obj = PrintExceptionAtExit() |
---|
202 | n/a | """) |
---|
203 | n/a | rc, stdout, stderr = assert_python_ok('-c', code) |
---|
204 | n/a | expected = [b'Traceback (most recent call last):', |
---|
205 | n/a | b' File "<string>", line 8, in __init__', |
---|
206 | n/a | b'ZeroDivisionError: division by zero'] |
---|
207 | n/a | self.assertEqual(stderr.splitlines(), expected) |
---|
208 | n/a | |
---|
209 | n/a | def test_print_exception(self): |
---|
210 | n/a | output = StringIO() |
---|
211 | n/a | traceback.print_exception( |
---|
212 | n/a | Exception, Exception("projector"), None, file=output |
---|
213 | n/a | ) |
---|
214 | n/a | self.assertEqual(output.getvalue(), "Exception: projector\n") |
---|
215 | n/a | |
---|
216 | n/a | |
---|
217 | n/a | class TracebackFormatTests(unittest.TestCase): |
---|
218 | n/a | |
---|
219 | n/a | def some_exception(self): |
---|
220 | n/a | raise KeyError('blah') |
---|
221 | n/a | |
---|
222 | n/a | @cpython_only |
---|
223 | n/a | def check_traceback_format(self, cleanup_func=None): |
---|
224 | n/a | from _testcapi import traceback_print |
---|
225 | n/a | try: |
---|
226 | n/a | self.some_exception() |
---|
227 | n/a | except KeyError: |
---|
228 | n/a | type_, value, tb = sys.exc_info() |
---|
229 | n/a | if cleanup_func is not None: |
---|
230 | n/a | # Clear the inner frames, not this one |
---|
231 | n/a | cleanup_func(tb.tb_next) |
---|
232 | n/a | traceback_fmt = 'Traceback (most recent call last):\n' + \ |
---|
233 | n/a | ''.join(traceback.format_tb(tb)) |
---|
234 | n/a | file_ = StringIO() |
---|
235 | n/a | traceback_print(tb, file_) |
---|
236 | n/a | python_fmt = file_.getvalue() |
---|
237 | n/a | # Call all _tb and _exc functions |
---|
238 | n/a | with captured_output("stderr") as tbstderr: |
---|
239 | n/a | traceback.print_tb(tb) |
---|
240 | n/a | tbfile = StringIO() |
---|
241 | n/a | traceback.print_tb(tb, file=tbfile) |
---|
242 | n/a | with captured_output("stderr") as excstderr: |
---|
243 | n/a | traceback.print_exc() |
---|
244 | n/a | excfmt = traceback.format_exc() |
---|
245 | n/a | excfile = StringIO() |
---|
246 | n/a | traceback.print_exc(file=excfile) |
---|
247 | n/a | else: |
---|
248 | n/a | raise Error("unable to create test traceback string") |
---|
249 | n/a | |
---|
250 | n/a | # Make sure that Python and the traceback module format the same thing |
---|
251 | n/a | self.assertEqual(traceback_fmt, python_fmt) |
---|
252 | n/a | # Now verify the _tb func output |
---|
253 | n/a | self.assertEqual(tbstderr.getvalue(), tbfile.getvalue()) |
---|
254 | n/a | # Now verify the _exc func output |
---|
255 | n/a | self.assertEqual(excstderr.getvalue(), excfile.getvalue()) |
---|
256 | n/a | self.assertEqual(excfmt, excfile.getvalue()) |
---|
257 | n/a | |
---|
258 | n/a | # Make sure that the traceback is properly indented. |
---|
259 | n/a | tb_lines = python_fmt.splitlines() |
---|
260 | n/a | self.assertEqual(len(tb_lines), 5) |
---|
261 | n/a | banner = tb_lines[0] |
---|
262 | n/a | location, source_line = tb_lines[-2:] |
---|
263 | n/a | self.assertTrue(banner.startswith('Traceback')) |
---|
264 | n/a | self.assertTrue(location.startswith(' File')) |
---|
265 | n/a | self.assertTrue(source_line.startswith(' raise')) |
---|
266 | n/a | |
---|
267 | n/a | def test_traceback_format(self): |
---|
268 | n/a | self.check_traceback_format() |
---|
269 | n/a | |
---|
270 | n/a | def test_traceback_format_with_cleared_frames(self): |
---|
271 | n/a | # Check that traceback formatting also works with a clear()ed frame |
---|
272 | n/a | def cleanup_tb(tb): |
---|
273 | n/a | tb.tb_frame.clear() |
---|
274 | n/a | self.check_traceback_format(cleanup_tb) |
---|
275 | n/a | |
---|
276 | n/a | def test_stack_format(self): |
---|
277 | n/a | # Verify _stack functions. Note we have to use _getframe(1) to |
---|
278 | n/a | # compare them without this frame appearing in the output |
---|
279 | n/a | with captured_output("stderr") as ststderr: |
---|
280 | n/a | traceback.print_stack(sys._getframe(1)) |
---|
281 | n/a | stfile = StringIO() |
---|
282 | n/a | traceback.print_stack(sys._getframe(1), file=stfile) |
---|
283 | n/a | self.assertEqual(ststderr.getvalue(), stfile.getvalue()) |
---|
284 | n/a | |
---|
285 | n/a | stfmt = traceback.format_stack(sys._getframe(1)) |
---|
286 | n/a | |
---|
287 | n/a | self.assertEqual(ststderr.getvalue(), "".join(stfmt)) |
---|
288 | n/a | |
---|
289 | n/a | def test_print_stack(self): |
---|
290 | n/a | def prn(): |
---|
291 | n/a | traceback.print_stack() |
---|
292 | n/a | with captured_output("stderr") as stderr: |
---|
293 | n/a | prn() |
---|
294 | n/a | lineno = prn.__code__.co_firstlineno |
---|
295 | n/a | self.assertEqual(stderr.getvalue().splitlines()[-4:], [ |
---|
296 | n/a | ' File "%s", line %d, in test_print_stack' % (__file__, lineno+3), |
---|
297 | n/a | ' prn()', |
---|
298 | n/a | ' File "%s", line %d, in prn' % (__file__, lineno+1), |
---|
299 | n/a | ' traceback.print_stack()', |
---|
300 | n/a | ]) |
---|
301 | n/a | |
---|
302 | n/a | # issue 26823 - Shrink recursive tracebacks |
---|
303 | n/a | def _check_recursive_traceback_display(self, render_exc): |
---|
304 | n/a | # Always show full diffs when this test fails |
---|
305 | n/a | # Note that rearranging things may require adjusting |
---|
306 | n/a | # the relative line numbers in the expected tracebacks |
---|
307 | n/a | self.maxDiff = None |
---|
308 | n/a | |
---|
309 | n/a | # Check hitting the recursion limit |
---|
310 | n/a | def f(): |
---|
311 | n/a | f() |
---|
312 | n/a | |
---|
313 | n/a | with captured_output("stderr") as stderr_f: |
---|
314 | n/a | try: |
---|
315 | n/a | f() |
---|
316 | n/a | except RecursionError as exc: |
---|
317 | n/a | render_exc() |
---|
318 | n/a | else: |
---|
319 | n/a | self.fail("no recursion occurred") |
---|
320 | n/a | |
---|
321 | n/a | lineno_f = f.__code__.co_firstlineno |
---|
322 | n/a | result_f = ( |
---|
323 | n/a | 'Traceback (most recent call last):\n' |
---|
324 | n/a | f' File "{__file__}", line {lineno_f+5}, in _check_recursive_traceback_display\n' |
---|
325 | n/a | ' f()\n' |
---|
326 | n/a | f' File "{__file__}", line {lineno_f+1}, in f\n' |
---|
327 | n/a | ' f()\n' |
---|
328 | n/a | f' File "{__file__}", line {lineno_f+1}, in f\n' |
---|
329 | n/a | ' f()\n' |
---|
330 | n/a | f' File "{__file__}", line {lineno_f+1}, in f\n' |
---|
331 | n/a | ' f()\n' |
---|
332 | n/a | # XXX: The following line changes depending on whether the tests |
---|
333 | n/a | # are run through the interactive interpreter or with -m |
---|
334 | n/a | # It also varies depending on the platform (stack size) |
---|
335 | n/a | # Fortunately, we don't care about exactness here, so we use regex |
---|
336 | n/a | r' \[Previous line repeated (\d+) more times\]' '\n' |
---|
337 | n/a | 'RecursionError: maximum recursion depth exceeded\n' |
---|
338 | n/a | ) |
---|
339 | n/a | |
---|
340 | n/a | expected = result_f.splitlines() |
---|
341 | n/a | actual = stderr_f.getvalue().splitlines() |
---|
342 | n/a | |
---|
343 | n/a | # Check the output text matches expectations |
---|
344 | n/a | # 2nd last line contains the repetition count |
---|
345 | n/a | self.assertEqual(actual[:-2], expected[:-2]) |
---|
346 | n/a | self.assertRegex(actual[-2], expected[-2]) |
---|
347 | n/a | self.assertEqual(actual[-1], expected[-1]) |
---|
348 | n/a | |
---|
349 | n/a | # Check the recursion count is roughly as expected |
---|
350 | n/a | rec_limit = sys.getrecursionlimit() |
---|
351 | n/a | self.assertIn(int(re.search(r"\d+", actual[-2]).group()), range(rec_limit-60, rec_limit)) |
---|
352 | n/a | |
---|
353 | n/a | # Check a known (limited) number of recursive invocations |
---|
354 | n/a | def g(count=10): |
---|
355 | n/a | if count: |
---|
356 | n/a | return g(count-1) |
---|
357 | n/a | raise ValueError |
---|
358 | n/a | |
---|
359 | n/a | with captured_output("stderr") as stderr_g: |
---|
360 | n/a | try: |
---|
361 | n/a | g() |
---|
362 | n/a | except ValueError as exc: |
---|
363 | n/a | render_exc() |
---|
364 | n/a | else: |
---|
365 | n/a | self.fail("no value error was raised") |
---|
366 | n/a | |
---|
367 | n/a | lineno_g = g.__code__.co_firstlineno |
---|
368 | n/a | result_g = ( |
---|
369 | n/a | f' File "{__file__}", line {lineno_g+2}, in g\n' |
---|
370 | n/a | ' return g(count-1)\n' |
---|
371 | n/a | f' File "{__file__}", line {lineno_g+2}, in g\n' |
---|
372 | n/a | ' return g(count-1)\n' |
---|
373 | n/a | f' File "{__file__}", line {lineno_g+2}, in g\n' |
---|
374 | n/a | ' return g(count-1)\n' |
---|
375 | n/a | ' [Previous line repeated 6 more times]\n' |
---|
376 | n/a | f' File "{__file__}", line {lineno_g+3}, in g\n' |
---|
377 | n/a | ' raise ValueError\n' |
---|
378 | n/a | 'ValueError\n' |
---|
379 | n/a | ) |
---|
380 | n/a | tb_line = ( |
---|
381 | n/a | 'Traceback (most recent call last):\n' |
---|
382 | n/a | f' File "{__file__}", line {lineno_g+7}, in _check_recursive_traceback_display\n' |
---|
383 | n/a | ' g()\n' |
---|
384 | n/a | ) |
---|
385 | n/a | expected = (tb_line + result_g).splitlines() |
---|
386 | n/a | actual = stderr_g.getvalue().splitlines() |
---|
387 | n/a | self.assertEqual(actual, expected) |
---|
388 | n/a | |
---|
389 | n/a | # Check 2 different repetitive sections |
---|
390 | n/a | def h(count=10): |
---|
391 | n/a | if count: |
---|
392 | n/a | return h(count-1) |
---|
393 | n/a | g() |
---|
394 | n/a | |
---|
395 | n/a | with captured_output("stderr") as stderr_h: |
---|
396 | n/a | try: |
---|
397 | n/a | h() |
---|
398 | n/a | except ValueError as exc: |
---|
399 | n/a | render_exc() |
---|
400 | n/a | else: |
---|
401 | n/a | self.fail("no value error was raised") |
---|
402 | n/a | |
---|
403 | n/a | lineno_h = h.__code__.co_firstlineno |
---|
404 | n/a | result_h = ( |
---|
405 | n/a | 'Traceback (most recent call last):\n' |
---|
406 | n/a | f' File "{__file__}", line {lineno_h+7}, in _check_recursive_traceback_display\n' |
---|
407 | n/a | ' h()\n' |
---|
408 | n/a | f' File "{__file__}", line {lineno_h+2}, in h\n' |
---|
409 | n/a | ' return h(count-1)\n' |
---|
410 | n/a | f' File "{__file__}", line {lineno_h+2}, in h\n' |
---|
411 | n/a | ' return h(count-1)\n' |
---|
412 | n/a | f' File "{__file__}", line {lineno_h+2}, in h\n' |
---|
413 | n/a | ' return h(count-1)\n' |
---|
414 | n/a | ' [Previous line repeated 6 more times]\n' |
---|
415 | n/a | f' File "{__file__}", line {lineno_h+3}, in h\n' |
---|
416 | n/a | ' g()\n' |
---|
417 | n/a | ) |
---|
418 | n/a | expected = (result_h + result_g).splitlines() |
---|
419 | n/a | actual = stderr_h.getvalue().splitlines() |
---|
420 | n/a | self.assertEqual(actual, expected) |
---|
421 | n/a | |
---|
422 | n/a | def test_recursive_traceback_python(self): |
---|
423 | n/a | self._check_recursive_traceback_display(traceback.print_exc) |
---|
424 | n/a | |
---|
425 | n/a | @cpython_only |
---|
426 | n/a | def test_recursive_traceback_cpython_internal(self): |
---|
427 | n/a | from _testcapi import exception_print |
---|
428 | n/a | def render_exc(): |
---|
429 | n/a | exc_type, exc_value, exc_tb = sys.exc_info() |
---|
430 | n/a | exception_print(exc_value) |
---|
431 | n/a | self._check_recursive_traceback_display(render_exc) |
---|
432 | n/a | |
---|
433 | n/a | def test_format_stack(self): |
---|
434 | n/a | def fmt(): |
---|
435 | n/a | return traceback.format_stack() |
---|
436 | n/a | result = fmt() |
---|
437 | n/a | lineno = fmt.__code__.co_firstlineno |
---|
438 | n/a | self.assertEqual(result[-2:], [ |
---|
439 | n/a | ' File "%s", line %d, in test_format_stack\n' |
---|
440 | n/a | ' result = fmt()\n' % (__file__, lineno+2), |
---|
441 | n/a | ' File "%s", line %d, in fmt\n' |
---|
442 | n/a | ' return traceback.format_stack()\n' % (__file__, lineno+1), |
---|
443 | n/a | ]) |
---|
444 | n/a | |
---|
445 | n/a | |
---|
446 | n/a | cause_message = ( |
---|
447 | n/a | "\nThe above exception was the direct cause " |
---|
448 | n/a | "of the following exception:\n\n") |
---|
449 | n/a | |
---|
450 | n/a | context_message = ( |
---|
451 | n/a | "\nDuring handling of the above exception, " |
---|
452 | n/a | "another exception occurred:\n\n") |
---|
453 | n/a | |
---|
454 | n/a | boundaries = re.compile( |
---|
455 | n/a | '(%s|%s)' % (re.escape(cause_message), re.escape(context_message))) |
---|
456 | n/a | |
---|
457 | n/a | |
---|
458 | n/a | class BaseExceptionReportingTests: |
---|
459 | n/a | |
---|
460 | n/a | def get_exception(self, exception_or_callable): |
---|
461 | n/a | if isinstance(exception_or_callable, Exception): |
---|
462 | n/a | return exception_or_callable |
---|
463 | n/a | try: |
---|
464 | n/a | exception_or_callable() |
---|
465 | n/a | except Exception as e: |
---|
466 | n/a | return e |
---|
467 | n/a | |
---|
468 | n/a | def zero_div(self): |
---|
469 | n/a | 1/0 # In zero_div |
---|
470 | n/a | |
---|
471 | n/a | def check_zero_div(self, msg): |
---|
472 | n/a | lines = msg.splitlines() |
---|
473 | n/a | self.assertTrue(lines[-3].startswith(' File')) |
---|
474 | n/a | self.assertIn('1/0 # In zero_div', lines[-2]) |
---|
475 | n/a | self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1]) |
---|
476 | n/a | |
---|
477 | n/a | def test_simple(self): |
---|
478 | n/a | try: |
---|
479 | n/a | 1/0 # Marker |
---|
480 | n/a | except ZeroDivisionError as _: |
---|
481 | n/a | e = _ |
---|
482 | n/a | lines = self.get_report(e).splitlines() |
---|
483 | n/a | self.assertEqual(len(lines), 4) |
---|
484 | n/a | self.assertTrue(lines[0].startswith('Traceback')) |
---|
485 | n/a | self.assertTrue(lines[1].startswith(' File')) |
---|
486 | n/a | self.assertIn('1/0 # Marker', lines[2]) |
---|
487 | n/a | self.assertTrue(lines[3].startswith('ZeroDivisionError')) |
---|
488 | n/a | |
---|
489 | n/a | def test_cause(self): |
---|
490 | n/a | def inner_raise(): |
---|
491 | n/a | try: |
---|
492 | n/a | self.zero_div() |
---|
493 | n/a | except ZeroDivisionError as e: |
---|
494 | n/a | raise KeyError from e |
---|
495 | n/a | def outer_raise(): |
---|
496 | n/a | inner_raise() # Marker |
---|
497 | n/a | blocks = boundaries.split(self.get_report(outer_raise)) |
---|
498 | n/a | self.assertEqual(len(blocks), 3) |
---|
499 | n/a | self.assertEqual(blocks[1], cause_message) |
---|
500 | n/a | self.check_zero_div(blocks[0]) |
---|
501 | n/a | self.assertIn('inner_raise() # Marker', blocks[2]) |
---|
502 | n/a | |
---|
503 | n/a | def test_context(self): |
---|
504 | n/a | def inner_raise(): |
---|
505 | n/a | try: |
---|
506 | n/a | self.zero_div() |
---|
507 | n/a | except ZeroDivisionError: |
---|
508 | n/a | raise KeyError |
---|
509 | n/a | def outer_raise(): |
---|
510 | n/a | inner_raise() # Marker |
---|
511 | n/a | blocks = boundaries.split(self.get_report(outer_raise)) |
---|
512 | n/a | self.assertEqual(len(blocks), 3) |
---|
513 | n/a | self.assertEqual(blocks[1], context_message) |
---|
514 | n/a | self.check_zero_div(blocks[0]) |
---|
515 | n/a | self.assertIn('inner_raise() # Marker', blocks[2]) |
---|
516 | n/a | |
---|
517 | n/a | def test_context_suppression(self): |
---|
518 | n/a | try: |
---|
519 | n/a | try: |
---|
520 | n/a | raise Exception |
---|
521 | n/a | except: |
---|
522 | n/a | raise ZeroDivisionError from None |
---|
523 | n/a | except ZeroDivisionError as _: |
---|
524 | n/a | e = _ |
---|
525 | n/a | lines = self.get_report(e).splitlines() |
---|
526 | n/a | self.assertEqual(len(lines), 4) |
---|
527 | n/a | self.assertTrue(lines[0].startswith('Traceback')) |
---|
528 | n/a | self.assertTrue(lines[1].startswith(' File')) |
---|
529 | n/a | self.assertIn('ZeroDivisionError from None', lines[2]) |
---|
530 | n/a | self.assertTrue(lines[3].startswith('ZeroDivisionError')) |
---|
531 | n/a | |
---|
532 | n/a | def test_cause_and_context(self): |
---|
533 | n/a | # When both a cause and a context are set, only the cause should be |
---|
534 | n/a | # displayed and the context should be muted. |
---|
535 | n/a | def inner_raise(): |
---|
536 | n/a | try: |
---|
537 | n/a | self.zero_div() |
---|
538 | n/a | except ZeroDivisionError as _e: |
---|
539 | n/a | e = _e |
---|
540 | n/a | try: |
---|
541 | n/a | xyzzy |
---|
542 | n/a | except NameError: |
---|
543 | n/a | raise KeyError from e |
---|
544 | n/a | def outer_raise(): |
---|
545 | n/a | inner_raise() # Marker |
---|
546 | n/a | blocks = boundaries.split(self.get_report(outer_raise)) |
---|
547 | n/a | self.assertEqual(len(blocks), 3) |
---|
548 | n/a | self.assertEqual(blocks[1], cause_message) |
---|
549 | n/a | self.check_zero_div(blocks[0]) |
---|
550 | n/a | self.assertIn('inner_raise() # Marker', blocks[2]) |
---|
551 | n/a | |
---|
552 | n/a | def test_cause_recursive(self): |
---|
553 | n/a | def inner_raise(): |
---|
554 | n/a | try: |
---|
555 | n/a | try: |
---|
556 | n/a | self.zero_div() |
---|
557 | n/a | except ZeroDivisionError as e: |
---|
558 | n/a | z = e |
---|
559 | n/a | raise KeyError from e |
---|
560 | n/a | except KeyError as e: |
---|
561 | n/a | raise z from e |
---|
562 | n/a | def outer_raise(): |
---|
563 | n/a | inner_raise() # Marker |
---|
564 | n/a | blocks = boundaries.split(self.get_report(outer_raise)) |
---|
565 | n/a | self.assertEqual(len(blocks), 3) |
---|
566 | n/a | self.assertEqual(blocks[1], cause_message) |
---|
567 | n/a | # The first block is the KeyError raised from the ZeroDivisionError |
---|
568 | n/a | self.assertIn('raise KeyError from e', blocks[0]) |
---|
569 | n/a | self.assertNotIn('1/0', blocks[0]) |
---|
570 | n/a | # The second block (apart from the boundary) is the ZeroDivisionError |
---|
571 | n/a | # re-raised from the KeyError |
---|
572 | n/a | self.assertIn('inner_raise() # Marker', blocks[2]) |
---|
573 | n/a | self.check_zero_div(blocks[2]) |
---|
574 | n/a | |
---|
575 | n/a | def test_syntax_error_offset_at_eol(self): |
---|
576 | n/a | # See #10186. |
---|
577 | n/a | def e(): |
---|
578 | n/a | raise SyntaxError('', ('', 0, 5, 'hello')) |
---|
579 | n/a | msg = self.get_report(e).splitlines() |
---|
580 | n/a | self.assertEqual(msg[-2], " ^") |
---|
581 | n/a | def e(): |
---|
582 | n/a | exec("x = 5 | 4 |") |
---|
583 | n/a | msg = self.get_report(e).splitlines() |
---|
584 | n/a | self.assertEqual(msg[-2], ' ^') |
---|
585 | n/a | |
---|
586 | n/a | def test_message_none(self): |
---|
587 | n/a | # A message that looks like "None" should not be treated specially |
---|
588 | n/a | err = self.get_report(Exception(None)) |
---|
589 | n/a | self.assertIn('Exception: None\n', err) |
---|
590 | n/a | err = self.get_report(Exception('None')) |
---|
591 | n/a | self.assertIn('Exception: None\n', err) |
---|
592 | n/a | err = self.get_report(Exception()) |
---|
593 | n/a | self.assertIn('Exception\n', err) |
---|
594 | n/a | err = self.get_report(Exception('')) |
---|
595 | n/a | self.assertIn('Exception\n', err) |
---|
596 | n/a | |
---|
597 | n/a | |
---|
598 | n/a | class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): |
---|
599 | n/a | # |
---|
600 | n/a | # This checks reporting through the 'traceback' module, with both |
---|
601 | n/a | # format_exception() and print_exception(). |
---|
602 | n/a | # |
---|
603 | n/a | |
---|
604 | n/a | def get_report(self, e): |
---|
605 | n/a | e = self.get_exception(e) |
---|
606 | n/a | s = ''.join( |
---|
607 | n/a | traceback.format_exception(type(e), e, e.__traceback__)) |
---|
608 | n/a | with captured_output("stderr") as sio: |
---|
609 | n/a | traceback.print_exception(type(e), e, e.__traceback__) |
---|
610 | n/a | self.assertEqual(sio.getvalue(), s) |
---|
611 | n/a | return s |
---|
612 | n/a | |
---|
613 | n/a | |
---|
614 | n/a | class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): |
---|
615 | n/a | # |
---|
616 | n/a | # This checks built-in reporting by the interpreter. |
---|
617 | n/a | # |
---|
618 | n/a | |
---|
619 | n/a | @cpython_only |
---|
620 | n/a | def get_report(self, e): |
---|
621 | n/a | from _testcapi import exception_print |
---|
622 | n/a | e = self.get_exception(e) |
---|
623 | n/a | with captured_output("stderr") as s: |
---|
624 | n/a | exception_print(e) |
---|
625 | n/a | return s.getvalue() |
---|
626 | n/a | |
---|
627 | n/a | |
---|
628 | n/a | class LimitTests(unittest.TestCase): |
---|
629 | n/a | |
---|
630 | n/a | ''' Tests for limit argument. |
---|
631 | n/a | It's enough to test extact_tb, extract_stack and format_exception ''' |
---|
632 | n/a | |
---|
633 | n/a | def last_raises1(self): |
---|
634 | n/a | raise Exception('Last raised') |
---|
635 | n/a | |
---|
636 | n/a | def last_raises2(self): |
---|
637 | n/a | self.last_raises1() |
---|
638 | n/a | |
---|
639 | n/a | def last_raises3(self): |
---|
640 | n/a | self.last_raises2() |
---|
641 | n/a | |
---|
642 | n/a | def last_raises4(self): |
---|
643 | n/a | self.last_raises3() |
---|
644 | n/a | |
---|
645 | n/a | def last_raises5(self): |
---|
646 | n/a | self.last_raises4() |
---|
647 | n/a | |
---|
648 | n/a | def last_returns_frame1(self): |
---|
649 | n/a | return sys._getframe() |
---|
650 | n/a | |
---|
651 | n/a | def last_returns_frame2(self): |
---|
652 | n/a | return self.last_returns_frame1() |
---|
653 | n/a | |
---|
654 | n/a | def last_returns_frame3(self): |
---|
655 | n/a | return self.last_returns_frame2() |
---|
656 | n/a | |
---|
657 | n/a | def last_returns_frame4(self): |
---|
658 | n/a | return self.last_returns_frame3() |
---|
659 | n/a | |
---|
660 | n/a | def last_returns_frame5(self): |
---|
661 | n/a | return self.last_returns_frame4() |
---|
662 | n/a | |
---|
663 | n/a | def test_extract_stack(self): |
---|
664 | n/a | frame = self.last_returns_frame5() |
---|
665 | n/a | def extract(**kwargs): |
---|
666 | n/a | return traceback.extract_stack(frame, **kwargs) |
---|
667 | n/a | def assertEqualExcept(actual, expected, ignore): |
---|
668 | n/a | self.assertEqual(actual[:ignore], expected[:ignore]) |
---|
669 | n/a | self.assertEqual(actual[ignore+1:], expected[ignore+1:]) |
---|
670 | n/a | self.assertEqual(len(actual), len(expected)) |
---|
671 | n/a | |
---|
672 | n/a | with support.swap_attr(sys, 'tracebacklimit', 1000): |
---|
673 | n/a | nolim = extract() |
---|
674 | n/a | self.assertGreater(len(nolim), 5) |
---|
675 | n/a | self.assertEqual(extract(limit=2), nolim[-2:]) |
---|
676 | n/a | assertEqualExcept(extract(limit=100), nolim[-100:], -5-1) |
---|
677 | n/a | self.assertEqual(extract(limit=-2), nolim[:2]) |
---|
678 | n/a | assertEqualExcept(extract(limit=-100), nolim[:100], len(nolim)-5-1) |
---|
679 | n/a | self.assertEqual(extract(limit=0), []) |
---|
680 | n/a | del sys.tracebacklimit |
---|
681 | n/a | assertEqualExcept(extract(), nolim, -5-1) |
---|
682 | n/a | sys.tracebacklimit = 2 |
---|
683 | n/a | self.assertEqual(extract(), nolim[-2:]) |
---|
684 | n/a | self.assertEqual(extract(limit=3), nolim[-3:]) |
---|
685 | n/a | self.assertEqual(extract(limit=-3), nolim[:3]) |
---|
686 | n/a | sys.tracebacklimit = 0 |
---|
687 | n/a | self.assertEqual(extract(), []) |
---|
688 | n/a | sys.tracebacklimit = -1 |
---|
689 | n/a | self.assertEqual(extract(), []) |
---|
690 | n/a | |
---|
691 | n/a | def test_extract_tb(self): |
---|
692 | n/a | try: |
---|
693 | n/a | self.last_raises5() |
---|
694 | n/a | except Exception: |
---|
695 | n/a | exc_type, exc_value, tb = sys.exc_info() |
---|
696 | n/a | def extract(**kwargs): |
---|
697 | n/a | return traceback.extract_tb(tb, **kwargs) |
---|
698 | n/a | |
---|
699 | n/a | with support.swap_attr(sys, 'tracebacklimit', 1000): |
---|
700 | n/a | nolim = extract() |
---|
701 | n/a | self.assertEqual(len(nolim), 5+1) |
---|
702 | n/a | self.assertEqual(extract(limit=2), nolim[:2]) |
---|
703 | n/a | self.assertEqual(extract(limit=10), nolim) |
---|
704 | n/a | self.assertEqual(extract(limit=-2), nolim[-2:]) |
---|
705 | n/a | self.assertEqual(extract(limit=-10), nolim) |
---|
706 | n/a | self.assertEqual(extract(limit=0), []) |
---|
707 | n/a | del sys.tracebacklimit |
---|
708 | n/a | self.assertEqual(extract(), nolim) |
---|
709 | n/a | sys.tracebacklimit = 2 |
---|
710 | n/a | self.assertEqual(extract(), nolim[:2]) |
---|
711 | n/a | self.assertEqual(extract(limit=3), nolim[:3]) |
---|
712 | n/a | self.assertEqual(extract(limit=-3), nolim[-3:]) |
---|
713 | n/a | sys.tracebacklimit = 0 |
---|
714 | n/a | self.assertEqual(extract(), []) |
---|
715 | n/a | sys.tracebacklimit = -1 |
---|
716 | n/a | self.assertEqual(extract(), []) |
---|
717 | n/a | |
---|
718 | n/a | def test_format_exception(self): |
---|
719 | n/a | try: |
---|
720 | n/a | self.last_raises5() |
---|
721 | n/a | except Exception: |
---|
722 | n/a | exc_type, exc_value, tb = sys.exc_info() |
---|
723 | n/a | # [1:-1] to exclude "Traceback (...)" header and |
---|
724 | n/a | # exception type and value |
---|
725 | n/a | def extract(**kwargs): |
---|
726 | n/a | return traceback.format_exception(exc_type, exc_value, tb, **kwargs)[1:-1] |
---|
727 | n/a | |
---|
728 | n/a | with support.swap_attr(sys, 'tracebacklimit', 1000): |
---|
729 | n/a | nolim = extract() |
---|
730 | n/a | self.assertEqual(len(nolim), 5+1) |
---|
731 | n/a | self.assertEqual(extract(limit=2), nolim[:2]) |
---|
732 | n/a | self.assertEqual(extract(limit=10), nolim) |
---|
733 | n/a | self.assertEqual(extract(limit=-2), nolim[-2:]) |
---|
734 | n/a | self.assertEqual(extract(limit=-10), nolim) |
---|
735 | n/a | self.assertEqual(extract(limit=0), []) |
---|
736 | n/a | del sys.tracebacklimit |
---|
737 | n/a | self.assertEqual(extract(), nolim) |
---|
738 | n/a | sys.tracebacklimit = 2 |
---|
739 | n/a | self.assertEqual(extract(), nolim[:2]) |
---|
740 | n/a | self.assertEqual(extract(limit=3), nolim[:3]) |
---|
741 | n/a | self.assertEqual(extract(limit=-3), nolim[-3:]) |
---|
742 | n/a | sys.tracebacklimit = 0 |
---|
743 | n/a | self.assertEqual(extract(), []) |
---|
744 | n/a | sys.tracebacklimit = -1 |
---|
745 | n/a | self.assertEqual(extract(), []) |
---|
746 | n/a | |
---|
747 | n/a | |
---|
748 | n/a | class MiscTracebackCases(unittest.TestCase): |
---|
749 | n/a | # |
---|
750 | n/a | # Check non-printing functions in traceback module |
---|
751 | n/a | # |
---|
752 | n/a | |
---|
753 | n/a | def test_clear(self): |
---|
754 | n/a | def outer(): |
---|
755 | n/a | middle() |
---|
756 | n/a | def middle(): |
---|
757 | n/a | inner() |
---|
758 | n/a | def inner(): |
---|
759 | n/a | i = 1 |
---|
760 | n/a | 1/0 |
---|
761 | n/a | |
---|
762 | n/a | try: |
---|
763 | n/a | outer() |
---|
764 | n/a | except: |
---|
765 | n/a | type_, value, tb = sys.exc_info() |
---|
766 | n/a | |
---|
767 | n/a | # Initial assertion: there's one local in the inner frame. |
---|
768 | n/a | inner_frame = tb.tb_next.tb_next.tb_next.tb_frame |
---|
769 | n/a | self.assertEqual(len(inner_frame.f_locals), 1) |
---|
770 | n/a | |
---|
771 | n/a | # Clear traceback frames |
---|
772 | n/a | traceback.clear_frames(tb) |
---|
773 | n/a | |
---|
774 | n/a | # Local variable dict should now be empty. |
---|
775 | n/a | self.assertEqual(len(inner_frame.f_locals), 0) |
---|
776 | n/a | |
---|
777 | n/a | def test_extract_stack(self): |
---|
778 | n/a | def extract(): |
---|
779 | n/a | return traceback.extract_stack() |
---|
780 | n/a | result = extract() |
---|
781 | n/a | lineno = extract.__code__.co_firstlineno |
---|
782 | n/a | self.assertEqual(result[-2:], [ |
---|
783 | n/a | (__file__, lineno+2, 'test_extract_stack', 'result = extract()'), |
---|
784 | n/a | (__file__, lineno+1, 'extract', 'return traceback.extract_stack()'), |
---|
785 | n/a | ]) |
---|
786 | n/a | |
---|
787 | n/a | |
---|
788 | n/a | class TestFrame(unittest.TestCase): |
---|
789 | n/a | |
---|
790 | n/a | def test_basics(self): |
---|
791 | n/a | linecache.clearcache() |
---|
792 | n/a | linecache.lazycache("f", globals()) |
---|
793 | n/a | f = traceback.FrameSummary("f", 1, "dummy") |
---|
794 | n/a | self.assertEqual(f, |
---|
795 | n/a | ("f", 1, "dummy", '"""Test cases for traceback module"""')) |
---|
796 | n/a | self.assertEqual(tuple(f), |
---|
797 | n/a | ("f", 1, "dummy", '"""Test cases for traceback module"""')) |
---|
798 | n/a | self.assertEqual(f, traceback.FrameSummary("f", 1, "dummy")) |
---|
799 | n/a | self.assertEqual(f, tuple(f)) |
---|
800 | n/a | # Since tuple.__eq__ doesn't support FrameSummary, the equality |
---|
801 | n/a | # operator fallbacks to FrameSummary.__eq__. |
---|
802 | n/a | self.assertEqual(tuple(f), f) |
---|
803 | n/a | self.assertIsNone(f.locals) |
---|
804 | n/a | |
---|
805 | n/a | def test_lazy_lines(self): |
---|
806 | n/a | linecache.clearcache() |
---|
807 | n/a | f = traceback.FrameSummary("f", 1, "dummy", lookup_line=False) |
---|
808 | n/a | self.assertEqual(None, f._line) |
---|
809 | n/a | linecache.lazycache("f", globals()) |
---|
810 | n/a | self.assertEqual( |
---|
811 | n/a | '"""Test cases for traceback module"""', |
---|
812 | n/a | f.line) |
---|
813 | n/a | |
---|
814 | n/a | def test_explicit_line(self): |
---|
815 | n/a | f = traceback.FrameSummary("f", 1, "dummy", line="line") |
---|
816 | n/a | self.assertEqual("line", f.line) |
---|
817 | n/a | |
---|
818 | n/a | |
---|
819 | n/a | class TestStack(unittest.TestCase): |
---|
820 | n/a | |
---|
821 | n/a | def test_walk_stack(self): |
---|
822 | n/a | def deeper(): |
---|
823 | n/a | return list(traceback.walk_stack(None)) |
---|
824 | n/a | s1 = list(traceback.walk_stack(None)) |
---|
825 | n/a | s2 = deeper() |
---|
826 | n/a | self.assertEqual(len(s2) - len(s1), 1) |
---|
827 | n/a | self.assertEqual(s2[1:], s1) |
---|
828 | n/a | |
---|
829 | n/a | def test_walk_tb(self): |
---|
830 | n/a | try: |
---|
831 | n/a | 1/0 |
---|
832 | n/a | except Exception: |
---|
833 | n/a | _, _, tb = sys.exc_info() |
---|
834 | n/a | s = list(traceback.walk_tb(tb)) |
---|
835 | n/a | self.assertEqual(len(s), 1) |
---|
836 | n/a | |
---|
837 | n/a | def test_extract_stack(self): |
---|
838 | n/a | s = traceback.StackSummary.extract(traceback.walk_stack(None)) |
---|
839 | n/a | self.assertIsInstance(s, traceback.StackSummary) |
---|
840 | n/a | |
---|
841 | n/a | def test_extract_stack_limit(self): |
---|
842 | n/a | s = traceback.StackSummary.extract(traceback.walk_stack(None), limit=5) |
---|
843 | n/a | self.assertEqual(len(s), 5) |
---|
844 | n/a | |
---|
845 | n/a | def test_extract_stack_lookup_lines(self): |
---|
846 | n/a | linecache.clearcache() |
---|
847 | n/a | linecache.updatecache('/foo.py', globals()) |
---|
848 | n/a | c = test_code('/foo.py', 'method') |
---|
849 | n/a | f = test_frame(c, None, None) |
---|
850 | n/a | s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=True) |
---|
851 | n/a | linecache.clearcache() |
---|
852 | n/a | self.assertEqual(s[0].line, "import sys") |
---|
853 | n/a | |
---|
854 | n/a | def test_extract_stackup_deferred_lookup_lines(self): |
---|
855 | n/a | linecache.clearcache() |
---|
856 | n/a | c = test_code('/foo.py', 'method') |
---|
857 | n/a | f = test_frame(c, None, None) |
---|
858 | n/a | s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=False) |
---|
859 | n/a | self.assertEqual({}, linecache.cache) |
---|
860 | n/a | linecache.updatecache('/foo.py', globals()) |
---|
861 | n/a | self.assertEqual(s[0].line, "import sys") |
---|
862 | n/a | |
---|
863 | n/a | def test_from_list(self): |
---|
864 | n/a | s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')]) |
---|
865 | n/a | self.assertEqual( |
---|
866 | n/a | [' File "foo.py", line 1, in fred\n line\n'], |
---|
867 | n/a | s.format()) |
---|
868 | n/a | |
---|
869 | n/a | def test_from_list_edited_stack(self): |
---|
870 | n/a | s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')]) |
---|
871 | n/a | s[0] = ('foo.py', 2, 'fred', 'line') |
---|
872 | n/a | s2 = traceback.StackSummary.from_list(s) |
---|
873 | n/a | self.assertEqual( |
---|
874 | n/a | [' File "foo.py", line 2, in fred\n line\n'], |
---|
875 | n/a | s2.format()) |
---|
876 | n/a | |
---|
877 | n/a | def test_format_smoke(self): |
---|
878 | n/a | # For detailed tests see the format_list tests, which consume the same |
---|
879 | n/a | # code. |
---|
880 | n/a | s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')]) |
---|
881 | n/a | self.assertEqual( |
---|
882 | n/a | [' File "foo.py", line 1, in fred\n line\n'], |
---|
883 | n/a | s.format()) |
---|
884 | n/a | |
---|
885 | n/a | def test_locals(self): |
---|
886 | n/a | linecache.updatecache('/foo.py', globals()) |
---|
887 | n/a | c = test_code('/foo.py', 'method') |
---|
888 | n/a | f = test_frame(c, globals(), {'something': 1}) |
---|
889 | n/a | s = traceback.StackSummary.extract(iter([(f, 6)]), capture_locals=True) |
---|
890 | n/a | self.assertEqual(s[0].locals, {'something': '1'}) |
---|
891 | n/a | |
---|
892 | n/a | def test_no_locals(self): |
---|
893 | n/a | linecache.updatecache('/foo.py', globals()) |
---|
894 | n/a | c = test_code('/foo.py', 'method') |
---|
895 | n/a | f = test_frame(c, globals(), {'something': 1}) |
---|
896 | n/a | s = traceback.StackSummary.extract(iter([(f, 6)])) |
---|
897 | n/a | self.assertEqual(s[0].locals, None) |
---|
898 | n/a | |
---|
899 | n/a | def test_format_locals(self): |
---|
900 | n/a | def some_inner(k, v): |
---|
901 | n/a | a = 1 |
---|
902 | n/a | b = 2 |
---|
903 | n/a | return traceback.StackSummary.extract( |
---|
904 | n/a | traceback.walk_stack(None), capture_locals=True, limit=1) |
---|
905 | n/a | s = some_inner(3, 4) |
---|
906 | n/a | self.assertEqual( |
---|
907 | n/a | [' File "%s", line %d, in some_inner\n' |
---|
908 | n/a | ' traceback.walk_stack(None), capture_locals=True, limit=1)\n' |
---|
909 | n/a | ' a = 1\n' |
---|
910 | n/a | ' b = 2\n' |
---|
911 | n/a | ' k = 3\n' |
---|
912 | n/a | ' v = 4\n' % (__file__, some_inner.__code__.co_firstlineno + 4) |
---|
913 | n/a | ], s.format()) |
---|
914 | n/a | |
---|
915 | n/a | class TestTracebackException(unittest.TestCase): |
---|
916 | n/a | |
---|
917 | n/a | def test_smoke(self): |
---|
918 | n/a | try: |
---|
919 | n/a | 1/0 |
---|
920 | n/a | except Exception: |
---|
921 | n/a | exc_info = sys.exc_info() |
---|
922 | n/a | exc = traceback.TracebackException(*exc_info) |
---|
923 | n/a | expected_stack = traceback.StackSummary.extract( |
---|
924 | n/a | traceback.walk_tb(exc_info[2])) |
---|
925 | n/a | self.assertEqual(None, exc.__cause__) |
---|
926 | n/a | self.assertEqual(None, exc.__context__) |
---|
927 | n/a | self.assertEqual(False, exc.__suppress_context__) |
---|
928 | n/a | self.assertEqual(expected_stack, exc.stack) |
---|
929 | n/a | self.assertEqual(exc_info[0], exc.exc_type) |
---|
930 | n/a | self.assertEqual(str(exc_info[1]), str(exc)) |
---|
931 | n/a | |
---|
932 | n/a | def test_from_exception(self): |
---|
933 | n/a | # Check all the parameters are accepted. |
---|
934 | n/a | def foo(): |
---|
935 | n/a | 1/0 |
---|
936 | n/a | try: |
---|
937 | n/a | foo() |
---|
938 | n/a | except Exception as e: |
---|
939 | n/a | exc_info = sys.exc_info() |
---|
940 | n/a | self.expected_stack = traceback.StackSummary.extract( |
---|
941 | n/a | traceback.walk_tb(exc_info[2]), limit=1, lookup_lines=False, |
---|
942 | n/a | capture_locals=True) |
---|
943 | n/a | self.exc = traceback.TracebackException.from_exception( |
---|
944 | n/a | e, limit=1, lookup_lines=False, capture_locals=True) |
---|
945 | n/a | expected_stack = self.expected_stack |
---|
946 | n/a | exc = self.exc |
---|
947 | n/a | self.assertEqual(None, exc.__cause__) |
---|
948 | n/a | self.assertEqual(None, exc.__context__) |
---|
949 | n/a | self.assertEqual(False, exc.__suppress_context__) |
---|
950 | n/a | self.assertEqual(expected_stack, exc.stack) |
---|
951 | n/a | self.assertEqual(exc_info[0], exc.exc_type) |
---|
952 | n/a | self.assertEqual(str(exc_info[1]), str(exc)) |
---|
953 | n/a | |
---|
954 | n/a | def test_cause(self): |
---|
955 | n/a | try: |
---|
956 | n/a | try: |
---|
957 | n/a | 1/0 |
---|
958 | n/a | finally: |
---|
959 | n/a | exc_info_context = sys.exc_info() |
---|
960 | n/a | exc_context = traceback.TracebackException(*exc_info_context) |
---|
961 | n/a | cause = Exception("cause") |
---|
962 | n/a | raise Exception("uh oh") from cause |
---|
963 | n/a | except Exception: |
---|
964 | n/a | exc_info = sys.exc_info() |
---|
965 | n/a | exc = traceback.TracebackException(*exc_info) |
---|
966 | n/a | expected_stack = traceback.StackSummary.extract( |
---|
967 | n/a | traceback.walk_tb(exc_info[2])) |
---|
968 | n/a | exc_cause = traceback.TracebackException(Exception, cause, None) |
---|
969 | n/a | self.assertEqual(exc_cause, exc.__cause__) |
---|
970 | n/a | self.assertEqual(exc_context, exc.__context__) |
---|
971 | n/a | self.assertEqual(True, exc.__suppress_context__) |
---|
972 | n/a | self.assertEqual(expected_stack, exc.stack) |
---|
973 | n/a | self.assertEqual(exc_info[0], exc.exc_type) |
---|
974 | n/a | self.assertEqual(str(exc_info[1]), str(exc)) |
---|
975 | n/a | |
---|
976 | n/a | def test_context(self): |
---|
977 | n/a | try: |
---|
978 | n/a | try: |
---|
979 | n/a | 1/0 |
---|
980 | n/a | finally: |
---|
981 | n/a | exc_info_context = sys.exc_info() |
---|
982 | n/a | exc_context = traceback.TracebackException(*exc_info_context) |
---|
983 | n/a | raise Exception("uh oh") |
---|
984 | n/a | except Exception: |
---|
985 | n/a | exc_info = sys.exc_info() |
---|
986 | n/a | exc = traceback.TracebackException(*exc_info) |
---|
987 | n/a | expected_stack = traceback.StackSummary.extract( |
---|
988 | n/a | traceback.walk_tb(exc_info[2])) |
---|
989 | n/a | self.assertEqual(None, exc.__cause__) |
---|
990 | n/a | self.assertEqual(exc_context, exc.__context__) |
---|
991 | n/a | self.assertEqual(False, exc.__suppress_context__) |
---|
992 | n/a | self.assertEqual(expected_stack, exc.stack) |
---|
993 | n/a | self.assertEqual(exc_info[0], exc.exc_type) |
---|
994 | n/a | self.assertEqual(str(exc_info[1]), str(exc)) |
---|
995 | n/a | |
---|
996 | n/a | def test_limit(self): |
---|
997 | n/a | def recurse(n): |
---|
998 | n/a | if n: |
---|
999 | n/a | recurse(n-1) |
---|
1000 | n/a | else: |
---|
1001 | n/a | 1/0 |
---|
1002 | n/a | try: |
---|
1003 | n/a | recurse(10) |
---|
1004 | n/a | except Exception: |
---|
1005 | n/a | exc_info = sys.exc_info() |
---|
1006 | n/a | exc = traceback.TracebackException(*exc_info, limit=5) |
---|
1007 | n/a | expected_stack = traceback.StackSummary.extract( |
---|
1008 | n/a | traceback.walk_tb(exc_info[2]), limit=5) |
---|
1009 | n/a | self.assertEqual(expected_stack, exc.stack) |
---|
1010 | n/a | |
---|
1011 | n/a | def test_lookup_lines(self): |
---|
1012 | n/a | linecache.clearcache() |
---|
1013 | n/a | e = Exception("uh oh") |
---|
1014 | n/a | c = test_code('/foo.py', 'method') |
---|
1015 | n/a | f = test_frame(c, None, None) |
---|
1016 | n/a | tb = test_tb(f, 6, None) |
---|
1017 | n/a | exc = traceback.TracebackException(Exception, e, tb, lookup_lines=False) |
---|
1018 | n/a | self.assertEqual({}, linecache.cache) |
---|
1019 | n/a | linecache.updatecache('/foo.py', globals()) |
---|
1020 | n/a | self.assertEqual(exc.stack[0].line, "import sys") |
---|
1021 | n/a | |
---|
1022 | n/a | def test_locals(self): |
---|
1023 | n/a | linecache.updatecache('/foo.py', globals()) |
---|
1024 | n/a | e = Exception("uh oh") |
---|
1025 | n/a | c = test_code('/foo.py', 'method') |
---|
1026 | n/a | f = test_frame(c, globals(), {'something': 1, 'other': 'string'}) |
---|
1027 | n/a | tb = test_tb(f, 6, None) |
---|
1028 | n/a | exc = traceback.TracebackException( |
---|
1029 | n/a | Exception, e, tb, capture_locals=True) |
---|
1030 | n/a | self.assertEqual( |
---|
1031 | n/a | exc.stack[0].locals, {'something': '1', 'other': "'string'"}) |
---|
1032 | n/a | |
---|
1033 | n/a | def test_no_locals(self): |
---|
1034 | n/a | linecache.updatecache('/foo.py', globals()) |
---|
1035 | n/a | e = Exception("uh oh") |
---|
1036 | n/a | c = test_code('/foo.py', 'method') |
---|
1037 | n/a | f = test_frame(c, globals(), {'something': 1}) |
---|
1038 | n/a | tb = test_tb(f, 6, None) |
---|
1039 | n/a | exc = traceback.TracebackException(Exception, e, tb) |
---|
1040 | n/a | self.assertEqual(exc.stack[0].locals, None) |
---|
1041 | n/a | |
---|
1042 | n/a | def test_traceback_header(self): |
---|
1043 | n/a | # do not print a traceback header if exc_traceback is None |
---|
1044 | n/a | # see issue #24695 |
---|
1045 | n/a | exc = traceback.TracebackException(Exception, Exception("haven"), None) |
---|
1046 | n/a | self.assertEqual(list(exc.format()), ["Exception: haven\n"]) |
---|
1047 | n/a | |
---|
1048 | n/a | |
---|
1049 | n/a | class MiscTest(unittest.TestCase): |
---|
1050 | n/a | |
---|
1051 | n/a | def test_all(self): |
---|
1052 | n/a | expected = set() |
---|
1053 | n/a | blacklist = {'print_list'} |
---|
1054 | n/a | for name in dir(traceback): |
---|
1055 | n/a | if name.startswith('_') or name in blacklist: |
---|
1056 | n/a | continue |
---|
1057 | n/a | module_object = getattr(traceback, name) |
---|
1058 | n/a | if getattr(module_object, '__module__', None) == 'traceback': |
---|
1059 | n/a | expected.add(name) |
---|
1060 | n/a | self.assertCountEqual(traceback.__all__, expected) |
---|
1061 | n/a | |
---|
1062 | n/a | |
---|
1063 | n/a | if __name__ == "__main__": |
---|
1064 | n/a | unittest.main() |
---|