ยปCore Development>Code coverage>Lib/test/test_traceback.py

Python code coverage for Lib/test/test_traceback.py

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