PageRenderTime 133ms CodeModel.GetById 25ms RepoModel.GetById 2ms app.codeStats 0ms

/edk2/AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_traceback.py

https://gitlab.com/envieidoc/Clover
Python | 204 lines | 184 code | 15 blank | 5 comment | 5 complexity | df6cb42c1adf19163347402792c539a1 MD5 | raw file
  1. """Test cases for traceback module"""
  2. from _testcapi import traceback_print
  3. from StringIO import StringIO
  4. import sys
  5. import unittest
  6. from imp import reload
  7. from test.test_support import run_unittest, is_jython, Error
  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 test_caret(self):
  29. err = self.get_exception_format(self.syntax_error_with_caret,
  30. SyntaxError)
  31. self.assertTrue(len(err) == 4)
  32. self.assertTrue(err[1].strip() == "return x!")
  33. self.assertIn("^", err[2]) # third line has caret
  34. self.assertTrue(err[1].find("!") == err[2].find("^")) # in the right place
  35. err = self.get_exception_format(self.syntax_error_with_caret_2,
  36. SyntaxError)
  37. self.assertIn("^", err[2]) # third line has caret
  38. self.assertTrue(err[2].count('\n') == 1) # and no additional newline
  39. self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place
  40. def test_nocaret(self):
  41. if is_jython:
  42. # jython adds a caret in this case (why shouldn't it?)
  43. return
  44. err = self.get_exception_format(self.syntax_error_without_caret,
  45. SyntaxError)
  46. self.assertTrue(len(err) == 3)
  47. self.assertTrue(err[1].strip() == "[x for x in x] = x")
  48. def test_bad_indentation(self):
  49. err = self.get_exception_format(self.syntax_error_bad_indentation,
  50. IndentationError)
  51. self.assertTrue(len(err) == 4)
  52. self.assertTrue(err[1].strip() == "print 2")
  53. self.assertIn("^", err[2])
  54. self.assertTrue(err[1].find("2") == err[2].find("^"))
  55. def test_bug737473(self):
  56. import os, tempfile, time
  57. savedpath = sys.path[:]
  58. testdir = tempfile.mkdtemp()
  59. try:
  60. sys.path.insert(0, testdir)
  61. testfile = os.path.join(testdir, 'test_bug737473.py')
  62. print >> open(testfile, 'w'), """
  63. def test():
  64. raise ValueError"""
  65. if 'test_bug737473' in sys.modules:
  66. del sys.modules['test_bug737473']
  67. import test_bug737473
  68. try:
  69. test_bug737473.test()
  70. except ValueError:
  71. # this loads source code to linecache
  72. traceback.extract_tb(sys.exc_traceback)
  73. # If this test runs too quickly, test_bug737473.py's mtime
  74. # attribute will remain unchanged even if the file is rewritten.
  75. # Consequently, the file would not reload. So, added a sleep()
  76. # delay to assure that a new, distinct timestamp is written.
  77. # Since WinME with FAT32 has multisecond resolution, more than
  78. # three seconds are needed for this test to pass reliably :-(
  79. time.sleep(4)
  80. print >> open(testfile, 'w'), """
  81. def test():
  82. raise NotImplementedError"""
  83. reload(test_bug737473)
  84. try:
  85. test_bug737473.test()
  86. except NotImplementedError:
  87. src = traceback.extract_tb(sys.exc_traceback)[-1][-1]
  88. self.assertEqual(src, 'raise NotImplementedError')
  89. finally:
  90. sys.path[:] = savedpath
  91. for f in os.listdir(testdir):
  92. os.unlink(os.path.join(testdir, f))
  93. os.rmdir(testdir)
  94. def test_base_exception(self):
  95. # Test that exceptions derived from BaseException are formatted right
  96. e = KeyboardInterrupt()
  97. lst = traceback.format_exception_only(e.__class__, e)
  98. self.assertEqual(lst, ['KeyboardInterrupt\n'])
  99. # String exceptions are deprecated, but legal. The quirky form with
  100. # separate "type" and "value" tends to break things, because
  101. # not isinstance(value, type)
  102. # and a string cannot be the first argument to issubclass.
  103. #
  104. # Note that sys.last_type and sys.last_value do not get set if an
  105. # exception is caught, so we sort of cheat and just emulate them.
  106. #
  107. # test_string_exception1 is equivalent to
  108. #
  109. # >>> raise "String Exception"
  110. #
  111. # test_string_exception2 is equivalent to
  112. #
  113. # >>> raise "String Exception", "String Value"
  114. #
  115. def test_string_exception1(self):
  116. str_type = "String Exception"
  117. err = traceback.format_exception_only(str_type, None)
  118. self.assertEqual(len(err), 1)
  119. self.assertEqual(err[0], str_type + '\n')
  120. def test_string_exception2(self):
  121. str_type = "String Exception"
  122. str_value = "String Value"
  123. err = traceback.format_exception_only(str_type, str_value)
  124. self.assertEqual(len(err), 1)
  125. self.assertEqual(err[0], str_type + ': ' + str_value + '\n')
  126. def test_format_exception_only_bad__str__(self):
  127. class X(Exception):
  128. def __str__(self):
  129. 1 // 0
  130. err = traceback.format_exception_only(X, X())
  131. self.assertEqual(len(err), 1)
  132. str_value = '<unprintable %s object>' % X.__name__
  133. self.assertEqual(err[0], X.__name__ + ': ' + str_value + '\n')
  134. def test_without_exception(self):
  135. err = traceback.format_exception_only(None, None)
  136. self.assertEqual(err, ['None\n'])
  137. def test_unicode(self):
  138. err = AssertionError('\xff')
  139. lines = traceback.format_exception_only(type(err), err)
  140. self.assertEqual(lines, ['AssertionError: \xff\n'])
  141. err = AssertionError(u'\xe9')
  142. lines = traceback.format_exception_only(type(err), err)
  143. self.assertEqual(lines, ['AssertionError: \\xe9\n'])
  144. class TracebackFormatTests(unittest.TestCase):
  145. def test_traceback_format(self):
  146. try:
  147. raise KeyError('blah')
  148. except KeyError:
  149. type_, value, tb = sys.exc_info()
  150. traceback_fmt = 'Traceback (most recent call last):\n' + \
  151. ''.join(traceback.format_tb(tb))
  152. file_ = StringIO()
  153. traceback_print(tb, file_)
  154. python_fmt = file_.getvalue()
  155. else:
  156. raise Error("unable to create test traceback string")
  157. # Make sure that Python and the traceback module format the same thing
  158. self.assertEqual(traceback_fmt, python_fmt)
  159. # Make sure that the traceback is properly indented.
  160. tb_lines = python_fmt.splitlines()
  161. self.assertEqual(len(tb_lines), 3)
  162. banner, location, source_line = tb_lines
  163. self.assertTrue(banner.startswith('Traceback'))
  164. self.assertTrue(location.startswith(' File'))
  165. self.assertTrue(source_line.startswith(' raise'))
  166. def test_main():
  167. run_unittest(TracebackCases, TracebackFormatTests)
  168. if __name__ == "__main__":
  169. test_main()