1 """Test cases for traceback module"""
3 from _testcapi
import traceback_print
4 from StringIO
import StringIO
7 from test
.test_support
import run_unittest
, is_jython
, Error
12 class TracebackCases(unittest
.TestCase
):
13 # For now, a very minimal set of tests. I want to be sure that
14 # formatting of SyntaxErrors works based on changes for 2.1.
16 def get_exception_format(self
, func
, exc
):
20 return traceback
.format_exception_only(exc
, value
)
22 raise ValueError, "call did not raise exception"
24 def syntax_error_with_caret(self
):
25 compile("def fact(x):\n\treturn x!\n", "?", "exec")
27 def syntax_error_with_caret_2(self
):
28 compile("1 +\n", "?", "exec")
30 def syntax_error_without_caret(self
):
31 # XXX why doesn't compile raise the same traceback?
32 import test
.badsyntax_nocaret
34 def syntax_error_bad_indentation(self
):
35 compile("def spam():\n print 1\n print 2", "?", "exec")
38 err
= self
.get_exception_format(self
.syntax_error_with_caret
,
40 self
.assertTrue(len(err
) == 4)
41 self
.assertTrue(err
[1].strip() == "return x!")
42 self
.assertTrue("^" in err
[2]) # third line has caret
43 self
.assertTrue(err
[1].find("!") == err
[2].find("^")) # in the right place
45 err
= self
.get_exception_format(self
.syntax_error_with_caret_2
,
47 self
.assertTrue("^" in err
[2]) # third line has caret
48 self
.assertTrue(err
[2].count('\n') == 1) # and no additional newline
49 self
.assertTrue(err
[1].find("+") == err
[2].find("^")) # in the right place
51 def test_nocaret(self
):
53 # jython adds a caret in this case (why shouldn't it?)
55 err
= self
.get_exception_format(self
.syntax_error_without_caret
,
57 self
.assertTrue(len(err
) == 3)
58 self
.assertTrue(err
[1].strip() == "[x for x in x] = x")
60 def test_bad_indentation(self
):
61 err
= self
.get_exception_format(self
.syntax_error_bad_indentation
,
63 self
.assertTrue(len(err
) == 4)
64 self
.assertTrue(err
[1].strip() == "print 2")
65 self
.assertTrue("^" in err
[2])
66 self
.assertTrue(err
[1].find("2") == err
[2].find("^"))
68 def test_bug737473(self
):
69 import sys
, os
, tempfile
, time
71 savedpath
= sys
.path
[:]
72 testdir
= tempfile
.mkdtemp()
74 sys
.path
.insert(0, testdir
)
75 testfile
= os
.path
.join(testdir
, 'test_bug737473.py')
76 print >> open(testfile
, 'w'), """
80 if 'test_bug737473' in sys
.modules
:
81 del sys
.modules
['test_bug737473']
87 # this loads source code to linecache
88 traceback
.extract_tb(sys
.exc_traceback
)
90 # If this test runs too quickly, test_bug737473.py's mtime
91 # attribute will remain unchanged even if the file is rewritten.
92 # Consequently, the file would not reload. So, added a sleep()
93 # delay to assure that a new, distinct timestamp is written.
94 # Since WinME with FAT32 has multisecond resolution, more than
95 # three seconds are needed for this test to pass reliably :-(
98 print >> open(testfile
, 'w'), """
100 raise NotImplementedError"""
101 reload(test_bug737473
)
103 test_bug737473
.test()
104 except NotImplementedError:
105 src
= traceback
.extract_tb(sys
.exc_traceback
)[-1][-1]
106 self
.assertEqual(src
, 'raise NotImplementedError')
108 sys
.path
[:] = savedpath
109 for f
in os
.listdir(testdir
):
110 os
.unlink(os
.path
.join(testdir
, f
))
113 def test_base_exception(self
):
114 # Test that exceptions derived from BaseException are formatted right
115 e
= KeyboardInterrupt()
116 lst
= traceback
.format_exception_only(e
.__class
__, e
)
117 self
.assertEqual(lst
, ['KeyboardInterrupt\n'])
119 # String exceptions are deprecated, but legal. The quirky form with
120 # separate "type" and "value" tends to break things, because
121 # not isinstance(value, type)
122 # and a string cannot be the first argument to issubclass.
124 # Note that sys.last_type and sys.last_value do not get set if an
125 # exception is caught, so we sort of cheat and just emulate them.
127 # test_string_exception1 is equivalent to
129 # >>> raise "String Exception"
131 # test_string_exception2 is equivalent to
133 # >>> raise "String Exception", "String Value"
135 def test_string_exception1(self
):
136 str_type
= "String Exception"
137 err
= traceback
.format_exception_only(str_type
, None)
138 self
.assertEqual(len(err
), 1)
139 self
.assertEqual(err
[0], str_type
+ '\n')
141 def test_string_exception2(self
):
142 str_type
= "String Exception"
143 str_value
= "String Value"
144 err
= traceback
.format_exception_only(str_type
, str_value
)
145 self
.assertEqual(len(err
), 1)
146 self
.assertEqual(err
[0], str_type
+ ': ' + str_value
+ '\n')
148 def test_format_exception_only_bad__str__(self
):
152 err
= traceback
.format_exception_only(X
, X())
153 self
.assertEqual(len(err
), 1)
154 str_value
= '<unprintable %s object>' % X
.__name
__
155 self
.assertEqual(err
[0], X
.__name
__ + ': ' + str_value
+ '\n')
157 def test_without_exception(self
):
158 err
= traceback
.format_exception_only(None, None)
159 self
.assertEqual(err
, ['None\n'])
162 class TracebackFormatTests(unittest
.TestCase
):
164 def test_traceback_format(self
):
166 raise KeyError('blah')
168 type_
, value
, tb
= sys
.exc_info()
169 traceback_fmt
= 'Traceback (most recent call last):\n' + \
170 ''.join(traceback
.format_tb(tb
))
172 traceback_print(tb
, file_
)
173 python_fmt
= file_
.getvalue()
175 raise Error("unable to create test traceback string")
177 # Make sure that Python and the traceback module format the same thing
178 self
.assertEquals(traceback_fmt
, python_fmt
)
180 # Make sure that the traceback is properly indented.
181 tb_lines
= python_fmt
.splitlines()
182 self
.assertEquals(len(tb_lines
), 3)
183 banner
, location
, source_line
= tb_lines
184 self
.assertTrue(banner
.startswith('Traceback'))
185 self
.assertTrue(location
.startswith(' File'))
186 self
.assertTrue(source_line
.startswith(' raise'))
190 run_unittest(TracebackCases
, TracebackFormatTests
)
193 if __name__
== "__main__":