test_traceback.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. """Test cases for traceback module"""
  2. from StringIO import StringIO
  3. import sys
  4. import unittest
  5. from imp import reload
  6. from test.test_support import (run_unittest, is_jython, Error, cpython_only,
  7. captured_output)
  8. import traceback
  9. class TracebackCases(unittest.TestCase):
  10. # For now, a very minimal set of tests. I want to be sure that
  11. # formatting of SyntaxErrors works based on changes for 2.1.
  12. def get_exception_format(self, func, exc):
  13. try:
  14. func()
  15. except exc, value:
  16. return traceback.format_exception_only(exc, value)
  17. else:
  18. raise ValueError, "call did not raise exception"
  19. def syntax_error_with_caret(self):
  20. compile("def fact(x):\n\treturn x!\n", "?", "exec")
  21. def syntax_error_with_caret_2(self):
  22. compile("1 +\n", "?", "exec")
  23. def syntax_error_without_caret(self):
  24. # XXX why doesn't compile raise the same traceback?
  25. import test.badsyntax_nocaret
  26. def syntax_error_bad_indentation(self):
  27. compile("def spam():\n print 1\n print 2", "?", "exec")
  28. def syntax_error_bad_indentation2(self):
  29. compile(" print(2)", "?", "exec")
  30. def test_caret(self):
  31. err = self.get_exception_format(self.syntax_error_with_caret,
  32. SyntaxError)
  33. self.assertTrue(len(err) == 4)
  34. self.assertTrue(err[1].strip() == "return x!")
  35. self.assertIn("^", err[2]) # third line has caret
  36. self.assertTrue(err[1].find("!") == err[2].find("^")) # in the right place
  37. err = self.get_exception_format(self.syntax_error_with_caret_2,
  38. SyntaxError)
  39. self.assertIn("^", err[2]) # third line has caret
  40. self.assertTrue(err[2].count('\n') == 1) # and no additional newline
  41. self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place
  42. def test_nocaret(self):
  43. if is_jython:
  44. # jython adds a caret in this case (why shouldn't it?)
  45. return
  46. err = self.get_exception_format(self.syntax_error_without_caret,
  47. SyntaxError)
  48. self.assertTrue(len(err) == 3)
  49. self.assertTrue(err[1].strip() == "[x for x in x] = x")
  50. def test_bad_indentation(self):
  51. err = self.get_exception_format(self.syntax_error_bad_indentation,
  52. IndentationError)
  53. self.assertTrue(len(err) == 4)
  54. self.assertTrue(err[1].strip() == "print 2")
  55. self.assertIn("^", err[2])
  56. self.assertTrue(err[1].find("2") == err[2].find("^"))
  57. def test_bug737473(self):
  58. import os, tempfile, time
  59. savedpath = sys.path[:]
  60. testdir = tempfile.mkdtemp()
  61. try:
  62. sys.path.insert(0, testdir)
  63. testfile = os.path.join(testdir, 'test_bug737473.py')
  64. print >> open(testfile, 'w'), """
  65. def test():
  66. raise ValueError"""
  67. if 'test_bug737473' in sys.modules:
  68. del sys.modules['test_bug737473']
  69. import test_bug737473
  70. try:
  71. test_bug737473.test()
  72. except ValueError:
  73. # this loads source code to linecache
  74. traceback.extract_tb(sys.exc_traceback)
  75. # If this test runs too quickly, test_bug737473.py's mtime
  76. # attribute will remain unchanged even if the file is rewritten.
  77. # Consequently, the file would not reload. So, added a sleep()
  78. # delay to assure that a new, distinct timestamp is written.
  79. # Since WinME with FAT32 has multisecond resolution, more than
  80. # three seconds are needed for this test to pass reliably :-(
  81. time.sleep(4)
  82. print >> open(testfile, 'w'), """
  83. def test():
  84. raise NotImplementedError"""
  85. reload(test_bug737473)
  86. try:
  87. test_bug737473.test()
  88. except NotImplementedError:
  89. src = traceback.extract_tb(sys.exc_traceback)[-1][-1]
  90. self.assertEqual(src, 'raise NotImplementedError')
  91. finally:
  92. sys.path[:] = savedpath
  93. for f in os.listdir(testdir):
  94. os.unlink(os.path.join(testdir, f))
  95. os.rmdir(testdir)
  96. err = self.get_exception_format(self.syntax_error_bad_indentation2,
  97. IndentationError)
  98. self.assertEqual(len(err), 4)
  99. self.assertEqual(err[1].strip(), "print(2)")
  100. self.assertIn("^", err[2])
  101. self.assertEqual(err[1].find("p"), err[2].find("^"))
  102. def test_base_exception(self):
  103. # Test that exceptions derived from BaseException are formatted right
  104. e = KeyboardInterrupt()
  105. lst = traceback.format_exception_only(e.__class__, e)
  106. self.assertEqual(lst, ['KeyboardInterrupt\n'])
  107. # String exceptions are deprecated, but legal. The quirky form with
  108. # separate "type" and "value" tends to break things, because
  109. # not isinstance(value, type)
  110. # and a string cannot be the first argument to issubclass.
  111. #
  112. # Note that sys.last_type and sys.last_value do not get set if an
  113. # exception is caught, so we sort of cheat and just emulate them.
  114. #
  115. # test_string_exception1 is equivalent to
  116. #
  117. # >>> raise "String Exception"
  118. #
  119. # test_string_exception2 is equivalent to
  120. #
  121. # >>> raise "String Exception", "String Value"
  122. #
  123. def test_string_exception1(self):
  124. str_type = "String Exception"
  125. err = traceback.format_exception_only(str_type, None)
  126. self.assertEqual(len(err), 1)
  127. self.assertEqual(err[0], str_type + '\n')
  128. def test_string_exception2(self):
  129. str_type = "String Exception"
  130. str_value = "String Value"
  131. err = traceback.format_exception_only(str_type, str_value)
  132. self.assertEqual(len(err), 1)
  133. self.assertEqual(err[0], str_type + ': ' + str_value + '\n')
  134. def test_format_exception_only_bad__str__(self):
  135. class X(Exception):
  136. def __str__(self):
  137. 1 // 0
  138. err = traceback.format_exception_only(X, X())
  139. self.assertEqual(len(err), 1)
  140. str_value = '<unprintable %s object>' % X.__name__
  141. self.assertEqual(err[0], X.__name__ + ': ' + str_value + '\n')
  142. def test_without_exception(self):
  143. err = traceback.format_exception_only(None, None)
  144. self.assertEqual(err, ['None\n'])
  145. def test_unicode(self):
  146. err = AssertionError('\xff')
  147. lines = traceback.format_exception_only(type(err), err)
  148. self.assertEqual(lines, ['AssertionError: \xff\n'])
  149. err = AssertionError(u'\xe9')
  150. lines = traceback.format_exception_only(type(err), err)
  151. self.assertEqual(lines, ['AssertionError: \\xe9\n'])
  152. class TracebackFormatTests(unittest.TestCase):
  153. @cpython_only
  154. def test_traceback_format(self):
  155. from _testcapi import traceback_print
  156. try:
  157. raise KeyError('blah')
  158. except KeyError:
  159. type_, value, tb = sys.exc_info()
  160. traceback_fmt = 'Traceback (most recent call last):\n' + \
  161. ''.join(traceback.format_tb(tb))
  162. file_ = StringIO()
  163. traceback_print(tb, file_)
  164. python_fmt = file_.getvalue()
  165. else:
  166. raise Error("unable to create test traceback string")
  167. # Make sure that Python and the traceback module format the same thing
  168. self.assertEqual(traceback_fmt, python_fmt)
  169. # Make sure that the traceback is properly indented.
  170. tb_lines = python_fmt.splitlines()
  171. self.assertEqual(len(tb_lines), 3)
  172. banner, location, source_line = tb_lines
  173. self.assertTrue(banner.startswith('Traceback'))
  174. self.assertTrue(location.startswith(' File'))
  175. self.assertTrue(source_line.startswith(' raise'))
  176. def test_print_stack(self):
  177. def prn():
  178. traceback.print_stack()
  179. with captured_output("stderr") as stderr:
  180. prn()
  181. lineno = prn.__code__.co_firstlineno
  182. file = prn.__code__.co_filename
  183. self.assertEqual(stderr.getvalue().splitlines()[-4:], [
  184. ' File "%s", line %d, in test_print_stack' % (file, lineno+3),
  185. ' prn()',
  186. ' File "%s", line %d, in prn' % (file, lineno+1),
  187. ' traceback.print_stack()',
  188. ])
  189. def test_format_stack(self):
  190. def fmt():
  191. return traceback.format_stack()
  192. result = fmt()
  193. lineno = fmt.__code__.co_firstlineno
  194. file = fmt.__code__.co_filename
  195. self.assertEqual(result[-2:], [
  196. ' File "%s", line %d, in test_format_stack\n'
  197. ' result = fmt()\n' % (file, lineno+2),
  198. ' File "%s", line %d, in fmt\n'
  199. ' return traceback.format_stack()\n' % (file, lineno+1),
  200. ])
  201. class MiscTracebackCases(unittest.TestCase):
  202. #
  203. # Check non-printing functions in traceback module
  204. #
  205. def test_extract_stack(self):
  206. def extract():
  207. return traceback.extract_stack()
  208. result = extract()
  209. lineno = extract.__code__.co_firstlineno
  210. file = extract.__code__.co_filename
  211. self.assertEqual(result[-2:], [
  212. (file, lineno+2, 'test_extract_stack', 'result = extract()'),
  213. (file, lineno+1, 'extract', 'return traceback.extract_stack()'),
  214. ])
  215. def test_main():
  216. run_unittest(TracebackCases, TracebackFormatTests, MiscTracebackCases)
  217. if __name__ == "__main__":
  218. test_main()