blob: e78fea2e5b43f59cb75e28642f231a86eea9aafb [file] [log] [blame]
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +00001"""Test cases for traceback module"""
2
Brett Cannon8dc43032008-04-28 04:50:06 +00003from _testcapi import traceback_print
Brett Cannon141534e2008-04-28 03:23:50 +00004from StringIO import StringIO
5import sys
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +00006import unittest
Brett Cannon141534e2008-04-28 03:23:50 +00007from test.test_support import run_unittest, is_jython, Error
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +00008
9import traceback
10
Brett Cannon141534e2008-04-28 03:23:50 +000011
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000012class 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.
15
16 def get_exception_format(self, func, exc):
17 try:
18 func()
19 except exc, value:
20 return traceback.format_exception_only(exc, value)
21 else:
22 raise ValueError, "call did not raise exception"
Tim Peters7e01e282001-04-08 07:44:07 +000023
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000024 def syntax_error_with_caret(self):
25 compile("def fact(x):\n\treturn x!\n", "?", "exec")
26
Georg Brandl4da2fa52009-06-04 18:59:58 +000027 def syntax_error_with_caret_2(self):
28 compile("1 +\n", "?", "exec")
29
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000030 def syntax_error_without_caret(self):
31 # XXX why doesn't compile raise the same traceback?
Barry Warsaw408b6d32002-07-30 23:27:12 +000032 import test.badsyntax_nocaret
Tim Peters480725d2006-04-03 02:46:44 +000033
Georg Brandl51dbc4c2006-03-31 15:59:13 +000034 def syntax_error_bad_indentation(self):
35 compile("def spam():\n print 1\n print 2", "?", "exec")
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000036
37 def test_caret(self):
38 err = self.get_exception_format(self.syntax_error_with_caret,
39 SyntaxError)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000040 self.assertTrue(len(err) == 4)
41 self.assertTrue(err[1].strip() == "return x!")
Ezio Melottiaa980582010-01-23 23:04:36 +000042 self.assertIn("^", err[2]) # third line has caret
Benjamin Peterson5c8da862009-06-30 22:57:08 +000043 self.assertTrue(err[1].find("!") == err[2].find("^")) # in the right place
Tim Peters7e01e282001-04-08 07:44:07 +000044
Georg Brandl4da2fa52009-06-04 18:59:58 +000045 err = self.get_exception_format(self.syntax_error_with_caret_2,
46 SyntaxError)
Ezio Melottiaa980582010-01-23 23:04:36 +000047 self.assertIn("^", err[2]) # third line has caret
Benjamin Peterson5c8da862009-06-30 22:57:08 +000048 self.assertTrue(err[2].count('\n') == 1) # and no additional newline
49 self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place
Georg Brandl4da2fa52009-06-04 18:59:58 +000050
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000051 def test_nocaret(self):
Finn Bock57f0f342002-11-06 11:45:15 +000052 if is_jython:
53 # jython adds a caret in this case (why shouldn't it?)
54 return
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000055 err = self.get_exception_format(self.syntax_error_without_caret,
56 SyntaxError)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000057 self.assertTrue(len(err) == 3)
58 self.assertTrue(err[1].strip() == "[x for x in x] = x")
Jeremy Hylton09ccc3a2001-03-21 20:33:04 +000059
Georg Brandl51dbc4c2006-03-31 15:59:13 +000060 def test_bad_indentation(self):
61 err = self.get_exception_format(self.syntax_error_bad_indentation,
62 IndentationError)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000063 self.assertTrue(len(err) == 4)
64 self.assertTrue(err[1].strip() == "print 2")
Ezio Melottiaa980582010-01-23 23:04:36 +000065 self.assertIn("^", err[2])
Benjamin Peterson5c8da862009-06-30 22:57:08 +000066 self.assertTrue(err[1].find("2") == err[2].find("^"))
Georg Brandl51dbc4c2006-03-31 15:59:13 +000067
Hye-Shik Chang182ac852004-10-26 09:16:42 +000068 def test_bug737473(self):
Tim Petersf1af9c02004-10-27 02:33:15 +000069 import sys, os, tempfile, time
70
Hye-Shik Chang182ac852004-10-26 09:16:42 +000071 savedpath = sys.path[:]
72 testdir = tempfile.mkdtemp()
73 try:
74 sys.path.insert(0, testdir)
75 testfile = os.path.join(testdir, 'test_bug737473.py')
Raymond Hettingerf7010be2004-11-01 22:27:14 +000076 print >> open(testfile, 'w'), """
Hye-Shik Chang182ac852004-10-26 09:16:42 +000077def test():
78 raise ValueError"""
79
Hye-Shik Chang182ac852004-10-26 09:16:42 +000080 if 'test_bug737473' in sys.modules:
81 del sys.modules['test_bug737473']
82 import test_bug737473
83
84 try:
85 test_bug737473.test()
86 except ValueError:
Tim Peters10d59f32004-10-27 02:43:25 +000087 # this loads source code to linecache
Hye-Shik Chang182ac852004-10-26 09:16:42 +000088 traceback.extract_tb(sys.exc_traceback)
89
Raymond Hettingerf7010be2004-11-01 22:27:14 +000090 # 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 :-(
96 time.sleep(4)
Hye-Shik Chang4a8d8512004-11-01 08:26:09 +000097
Raymond Hettingerf7010be2004-11-01 22:27:14 +000098 print >> open(testfile, 'w'), """
Hye-Shik Chang182ac852004-10-26 09:16:42 +000099def test():
100 raise NotImplementedError"""
101 reload(test_bug737473)
102 try:
103 test_bug737473.test()
104 except NotImplementedError:
105 src = traceback.extract_tb(sys.exc_traceback)[-1][-1]
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000106 self.assertEqual(src, 'raise NotImplementedError')
Hye-Shik Chang182ac852004-10-26 09:16:42 +0000107 finally:
108 sys.path[:] = savedpath
109 for f in os.listdir(testdir):
110 os.unlink(os.path.join(testdir, f))
111 os.rmdir(testdir)
Fred Drake2e2be372001-09-20 21:33:42 +0000112
Guido van Rossum8f6cbe12006-05-02 17:36:09 +0000113 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'])
118
Georg Brandlc13c34c2006-07-24 14:09:56 +0000119 # String exceptions are deprecated, but legal. The quirky form with
Tim Peters0bbfd832006-07-24 21:02:15 +0000120 # separate "type" and "value" tends to break things, because
Georg Brandlc13c34c2006-07-24 14:09:56 +0000121 # not isinstance(value, type)
122 # and a string cannot be the first argument to issubclass.
123 #
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.
126 #
127 # test_string_exception1 is equivalent to
128 #
129 # >>> raise "String Exception"
130 #
131 # test_string_exception2 is equivalent to
132 #
133 # >>> raise "String Exception", "String Value"
134 #
135 def test_string_exception1(self):
136 str_type = "String Exception"
137 err = traceback.format_exception_only(str_type, None)
Neal Norwitzff4b63b2006-08-04 04:50:21 +0000138 self.assertEqual(len(err), 1)
139 self.assertEqual(err[0], str_type + '\n')
Georg Brandlc13c34c2006-07-24 14:09:56 +0000140
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)
Neal Norwitzff4b63b2006-08-04 04:50:21 +0000145 self.assertEqual(len(err), 1)
146 self.assertEqual(err[0], str_type + ': ' + str_value + '\n')
147
148 def test_format_exception_only_bad__str__(self):
149 class X(Exception):
150 def __str__(self):
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000151 1/0
Neal Norwitzff4b63b2006-08-04 04:50:21 +0000152 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')
Tim Peters0bbfd832006-07-24 21:02:15 +0000156
Georg Brandlc7986ce2006-09-24 12:50:24 +0000157 def test_without_exception(self):
158 err = traceback.format_exception_only(None, None)
159 self.assertEqual(err, ['None\n'])
160
Georg Brandlc13c34c2006-07-24 14:09:56 +0000161
Brett Cannon141534e2008-04-28 03:23:50 +0000162class TracebackFormatTests(unittest.TestCase):
163
Georg Brandldc4a7712009-04-05 14:24:52 +0000164 def test_traceback_format(self):
165 try:
166 raise KeyError('blah')
167 except KeyError:
168 type_, value, tb = sys.exc_info()
169 traceback_fmt = 'Traceback (most recent call last):\n' + \
170 ''.join(traceback.format_tb(tb))
171 file_ = StringIO()
172 traceback_print(tb, file_)
173 python_fmt = file_.getvalue()
174 else:
175 raise Error("unable to create test traceback string")
176
177 # Make sure that Python and the traceback module format the same thing
178 self.assertEquals(traceback_fmt, python_fmt)
179
Brett Cannon141534e2008-04-28 03:23:50 +0000180 # Make sure that the traceback is properly indented.
Georg Brandldc4a7712009-04-05 14:24:52 +0000181 tb_lines = python_fmt.splitlines()
Brett Cannon141534e2008-04-28 03:23:50 +0000182 self.assertEquals(len(tb_lines), 3)
183 banner, location, source_line = tb_lines
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000184 self.assertTrue(banner.startswith('Traceback'))
185 self.assertTrue(location.startswith(' File'))
186 self.assertTrue(source_line.startswith(' raise'))
Brett Cannon141534e2008-04-28 03:23:50 +0000187
188
Fred Drake2e2be372001-09-20 21:33:42 +0000189def test_main():
Brett Cannon141534e2008-04-28 03:23:50 +0000190 run_unittest(TracebackCases, TracebackFormatTests)
Fred Drake2e2be372001-09-20 21:33:42 +0000191
192
193if __name__ == "__main__":
194 test_main()