test_failure.py 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Test cases for the L{twisted.python.failure} module.
  5. """
  6. from __future__ import division, absolute_import
  7. import re
  8. import sys
  9. import traceback
  10. import pdb
  11. import linecache
  12. from twisted.python.compat import NativeStringIO, _PY3, _shouldEnableNewStyle
  13. from twisted.python import reflect
  14. from twisted.python import failure
  15. from twisted.trial.unittest import SynchronousTestCase
  16. try:
  17. from twisted.test import raiser
  18. except ImportError:
  19. raiser = None
  20. def getDivisionFailure(*args, **kwargs):
  21. """
  22. Make a C{Failure} of a divide-by-zero error.
  23. @param args: Any C{*args} are passed to Failure's constructor.
  24. @param kwargs: Any C{**kwargs} are passed to Failure's constructor.
  25. """
  26. try:
  27. 1/0
  28. except:
  29. f = failure.Failure(*args, **kwargs)
  30. return f
  31. class FailureTests(SynchronousTestCase):
  32. """
  33. Tests for L{failure.Failure}.
  34. """
  35. def test_failAndTrap(self):
  36. """
  37. Trapping a L{Failure}.
  38. """
  39. try:
  40. raise NotImplementedError('test')
  41. except:
  42. f = failure.Failure()
  43. error = f.trap(SystemExit, RuntimeError)
  44. self.assertEqual(error, RuntimeError)
  45. self.assertEqual(f.type, NotImplementedError)
  46. def test_trapRaisesCurrentFailure(self):
  47. """
  48. If the wrapped C{Exception} is not a subclass of one of the
  49. expected types, L{failure.Failure.trap} raises the current
  50. L{failure.Failure} ie C{self}.
  51. """
  52. exception = ValueError()
  53. try:
  54. raise exception
  55. except:
  56. f = failure.Failure()
  57. untrapped = self.assertRaises(failure.Failure, f.trap, OverflowError)
  58. self.assertIs(f, untrapped)
  59. if _shouldEnableNewStyle:
  60. test_trapRaisesCurrentFailure.skip = (
  61. "In Python 3, or with new-style classes enabled on Python 2, "
  62. "Failure.trap raises the wrapped Exception "
  63. "instead of the original Failure instance.")
  64. def test_trapRaisesWrappedException(self):
  65. """
  66. If the wrapped C{Exception} is not a subclass of one of the
  67. expected types, L{failure.Failure.trap} raises the wrapped
  68. C{Exception}.
  69. """
  70. exception = ValueError()
  71. try:
  72. raise exception
  73. except:
  74. f = failure.Failure()
  75. untrapped = self.assertRaises(ValueError, f.trap, OverflowError)
  76. self.assertIs(exception, untrapped)
  77. if not _shouldEnableNewStyle:
  78. test_trapRaisesWrappedException.skip = (
  79. "In Python2 with old-style classes, Failure.trap raises the "
  80. "current Failure instance instead of the wrapped Exception.")
  81. def test_failureValueFromFailure(self):
  82. """
  83. A L{failure.Failure} constructed from another
  84. L{failure.Failure} instance, has its C{value} property set to
  85. the value of that L{failure.Failure} instance.
  86. """
  87. exception = ValueError()
  88. f1 = failure.Failure(exception)
  89. f2 = failure.Failure(f1)
  90. self.assertIs(f2.value, exception)
  91. def test_failureValueFromFoundFailure(self):
  92. """
  93. A L{failure.Failure} constructed without a C{exc_value}
  94. argument, will search for an "original" C{Failure}, and if
  95. found, its value will be used as the value for the new
  96. C{Failure}.
  97. """
  98. exception = ValueError()
  99. f1 = failure.Failure(exception)
  100. try:
  101. f1.trap(OverflowError)
  102. except:
  103. f2 = failure.Failure()
  104. self.assertIs(f2.value, exception)
  105. def assertStartsWith(self, s, prefix):
  106. """
  107. Assert that C{s} starts with a particular C{prefix}.
  108. @param s: The input string.
  109. @type s: C{str}
  110. @param prefix: The string that C{s} should start with.
  111. @type prefix: C{str}
  112. """
  113. self.assertTrue(s.startswith(prefix),
  114. '%r is not the start of %r' % (prefix, s))
  115. def assertEndsWith(self, s, suffix):
  116. """
  117. Assert that C{s} end with a particular C{suffix}.
  118. @param s: The input string.
  119. @type s: C{str}
  120. @param suffix: The string that C{s} should end with.
  121. @type suffix: C{str}
  122. """
  123. self.assertTrue(s.endswith(suffix),
  124. '%r is not the end of %r' % (suffix, s))
  125. def assertTracebackFormat(self, tb, prefix, suffix):
  126. """
  127. Assert that the C{tb} traceback contains a particular C{prefix} and
  128. C{suffix}.
  129. @param tb: The traceback string.
  130. @type tb: C{str}
  131. @param prefix: The string that C{tb} should start with.
  132. @type prefix: C{str}
  133. @param suffix: The string that C{tb} should end with.
  134. @type suffix: C{str}
  135. """
  136. self.assertStartsWith(tb, prefix)
  137. self.assertEndsWith(tb, suffix)
  138. def assertDetailedTraceback(self, captureVars=False, cleanFailure=False):
  139. """
  140. Assert that L{printDetailedTraceback} produces and prints a detailed
  141. traceback.
  142. The detailed traceback consists of a header::
  143. *--- Failure #20 ---
  144. The body contains the stacktrace::
  145. /twisted/trial/_synctest.py:1180: _run(...)
  146. /twisted/python/util.py:1076: runWithWarningsSuppressed(...)
  147. --- <exception caught here> ---
  148. /twisted/test/test_failure.py:39: getDivisionFailure(...)
  149. If C{captureVars} is enabled the body also includes a list of
  150. globals and locals::
  151. [ Locals ]
  152. exampleLocalVar : 'xyz'
  153. ...
  154. ( Globals )
  155. ...
  156. Or when C{captureVars} is disabled::
  157. [Capture of Locals and Globals disabled (use captureVars=True)]
  158. When C{cleanFailure} is enabled references to other objects are removed
  159. and replaced with strings.
  160. And finally the footer with the L{Failure}'s value::
  161. exceptions.ZeroDivisionError: float division
  162. *--- End of Failure #20 ---
  163. @param captureVars: Enables L{Failure.captureVars}.
  164. @type captureVars: C{bool}
  165. @param cleanFailure: Enables L{Failure.cleanFailure}.
  166. @type cleanFailure: C{bool}
  167. """
  168. if captureVars:
  169. exampleLocalVar = 'xyz'
  170. # Silence the linter as this variable is checked via
  171. # the traceback.
  172. exampleLocalVar
  173. f = getDivisionFailure(captureVars=captureVars)
  174. out = NativeStringIO()
  175. if cleanFailure:
  176. f.cleanFailure()
  177. f.printDetailedTraceback(out)
  178. tb = out.getvalue()
  179. start = "*--- Failure #%d%s---\n" % (f.count,
  180. (f.pickled and ' (pickled) ') or ' ')
  181. end = "%s: %s\n*--- End of Failure #%s ---\n" % (reflect.qual(f.type),
  182. reflect.safe_str(f.value), f.count)
  183. self.assertTracebackFormat(tb, start, end)
  184. # Variables are printed on lines with 2 leading spaces.
  185. linesWithVars = [line for line in tb.splitlines()
  186. if line.startswith(' ')]
  187. if captureVars:
  188. self.assertNotEqual([], linesWithVars)
  189. if cleanFailure:
  190. line = ' exampleLocalVar : "\'xyz\'"'
  191. else:
  192. line = " exampleLocalVar : 'xyz'"
  193. self.assertIn(line, linesWithVars)
  194. else:
  195. self.assertEqual([], linesWithVars)
  196. self.assertIn(' [Capture of Locals and Globals disabled (use '
  197. 'captureVars=True)]\n', tb)
  198. def assertBriefTraceback(self, captureVars=False):
  199. """
  200. Assert that L{printBriefTraceback} produces and prints a brief
  201. traceback.
  202. The brief traceback consists of a header::
  203. Traceback: <type 'exceptions.ZeroDivisionError'>: float division
  204. The body with the stacktrace::
  205. /twisted/trial/_synctest.py:1180:_run
  206. /twisted/python/util.py:1076:runWithWarningsSuppressed
  207. And the footer::
  208. --- <exception caught here> ---
  209. /twisted/test/test_failure.py:39:getDivisionFailure
  210. @param captureVars: Enables L{Failure.captureVars}.
  211. @type captureVars: C{bool}
  212. """
  213. if captureVars:
  214. exampleLocalVar = 'abcde'
  215. # Silence the linter as this variable is checked via
  216. # the traceback.
  217. exampleLocalVar
  218. f = getDivisionFailure()
  219. out = NativeStringIO()
  220. f.printBriefTraceback(out)
  221. tb = out.getvalue()
  222. stack = ''
  223. for method, filename, lineno, localVars, globalVars in f.frames:
  224. stack += '%s:%s:%s\n' % (filename, lineno, method)
  225. zde = repr(ZeroDivisionError)
  226. self.assertTracebackFormat(tb,
  227. "Traceback: %s: " % (zde,),
  228. "%s\n%s" % (failure.EXCEPTION_CAUGHT_HERE, stack))
  229. if captureVars:
  230. self.assertIsNone(re.search('exampleLocalVar.*abcde', tb))
  231. def assertDefaultTraceback(self, captureVars=False):
  232. """
  233. Assert that L{printTraceback} produces and prints a default traceback.
  234. The default traceback consists of a header::
  235. Traceback (most recent call last):
  236. The body with traceback::
  237. File "/twisted/trial/_synctest.py", line 1180, in _run
  238. runWithWarningsSuppressed(suppress, method)
  239. And the footer::
  240. --- <exception caught here> ---
  241. File "twisted/test/test_failure.py", line 39, in getDivisionFailure
  242. 1/0
  243. exceptions.ZeroDivisionError: float division
  244. @param captureVars: Enables L{Failure.captureVars}.
  245. @type captureVars: C{bool}
  246. """
  247. if captureVars:
  248. exampleLocalVar = 'xyzzy'
  249. # Silence the linter as this variable is checked via
  250. # the traceback.
  251. exampleLocalVar
  252. f = getDivisionFailure(captureVars=captureVars)
  253. out = NativeStringIO()
  254. f.printTraceback(out)
  255. tb = out.getvalue()
  256. stack = ''
  257. for method, filename, lineno, localVars, globalVars in f.frames:
  258. stack += ' File "%s", line %s, in %s\n' % (filename, lineno,
  259. method)
  260. stack += ' %s\n' % (linecache.getline(
  261. filename, lineno).strip(),)
  262. self.assertTracebackFormat(tb,
  263. "Traceback (most recent call last):",
  264. "%s\n%s%s: %s\n" % (failure.EXCEPTION_CAUGHT_HERE, stack,
  265. reflect.qual(f.type), reflect.safe_str(f.value)))
  266. if captureVars:
  267. self.assertIsNone(re.search('exampleLocalVar.*xyzzy', tb))
  268. def test_printDetailedTraceback(self):
  269. """
  270. L{printDetailedTraceback} returns a detailed traceback including the
  271. L{Failure}'s count.
  272. """
  273. self.assertDetailedTraceback()
  274. def test_printBriefTraceback(self):
  275. """
  276. L{printBriefTraceback} returns a brief traceback.
  277. """
  278. self.assertBriefTraceback()
  279. def test_printTraceback(self):
  280. """
  281. L{printTraceback} returns a traceback.
  282. """
  283. self.assertDefaultTraceback()
  284. def test_printDetailedTracebackCapturedVars(self):
  285. """
  286. L{printDetailedTraceback} captures the locals and globals for its
  287. stack frames and adds them to the traceback, when called on a
  288. L{Failure} constructed with C{captureVars=True}.
  289. """
  290. self.assertDetailedTraceback(captureVars=True)
  291. def test_printBriefTracebackCapturedVars(self):
  292. """
  293. L{printBriefTraceback} returns a brief traceback when called on a
  294. L{Failure} constructed with C{captureVars=True}.
  295. Local variables on the stack can not be seen in the resulting
  296. traceback.
  297. """
  298. self.assertBriefTraceback(captureVars=True)
  299. def test_printTracebackCapturedVars(self):
  300. """
  301. L{printTraceback} returns a traceback when called on a L{Failure}
  302. constructed with C{captureVars=True}.
  303. Local variables on the stack can not be seen in the resulting
  304. traceback.
  305. """
  306. self.assertDefaultTraceback(captureVars=True)
  307. def test_printDetailedTracebackCapturedVarsCleaned(self):
  308. """
  309. C{printDetailedTraceback} includes information about local variables on
  310. the stack after C{cleanFailure} has been called.
  311. """
  312. self.assertDetailedTraceback(captureVars=True, cleanFailure=True)
  313. def test_invalidFormatFramesDetail(self):
  314. """
  315. L{failure.format_frames} raises a L{ValueError} if the supplied
  316. C{detail} level is unknown.
  317. """
  318. self.assertRaises(ValueError, failure.format_frames, None, None,
  319. detail='noisia')
  320. def test_ExplictPass(self):
  321. e = RuntimeError()
  322. f = failure.Failure(e)
  323. f.trap(RuntimeError)
  324. self.assertEqual(f.value, e)
  325. def _getInnermostFrameLine(self, f):
  326. try:
  327. f.raiseException()
  328. except ZeroDivisionError:
  329. tb = traceback.extract_tb(sys.exc_info()[2])
  330. return tb[-1][-1]
  331. else:
  332. raise Exception(
  333. "f.raiseException() didn't raise ZeroDivisionError!?")
  334. def test_RaiseExceptionWithTB(self):
  335. f = getDivisionFailure()
  336. innerline = self._getInnermostFrameLine(f)
  337. self.assertEqual(innerline, '1/0')
  338. def test_stringExceptionConstruction(self):
  339. """
  340. Constructing a C{Failure} with a string as its exception value raises
  341. a C{TypeError}, as this is no longer supported as of Python 2.6.
  342. """
  343. exc = self.assertRaises(TypeError, failure.Failure, "ono!")
  344. self.assertIn("Strings are not supported by Failure", str(exc))
  345. def test_ConstructionFails(self):
  346. """
  347. Creating a Failure with no arguments causes it to try to discover the
  348. current interpreter exception state. If no such state exists, creating
  349. the Failure should raise a synchronous exception.
  350. """
  351. if sys.version_info < (3, 0):
  352. sys.exc_clear()
  353. self.assertRaises(failure.NoCurrentExceptionError, failure.Failure)
  354. def test_getTracebackObject(self):
  355. """
  356. If the C{Failure} has not been cleaned, then C{getTracebackObject}
  357. returns the traceback object that captured in its constructor.
  358. """
  359. f = getDivisionFailure()
  360. self.assertEqual(f.getTracebackObject(), f.tb)
  361. def test_getTracebackObjectFromCaptureVars(self):
  362. """
  363. C{captureVars=True} has no effect on the result of
  364. C{getTracebackObject}.
  365. """
  366. try:
  367. 1/0
  368. except ZeroDivisionError:
  369. noVarsFailure = failure.Failure()
  370. varsFailure = failure.Failure(captureVars=True)
  371. self.assertEqual(noVarsFailure.getTracebackObject(), varsFailure.tb)
  372. def test_getTracebackObjectFromClean(self):
  373. """
  374. If the Failure has been cleaned, then C{getTracebackObject} returns an
  375. object that looks the same to L{traceback.extract_tb}.
  376. """
  377. f = getDivisionFailure()
  378. expected = traceback.extract_tb(f.getTracebackObject())
  379. f.cleanFailure()
  380. observed = traceback.extract_tb(f.getTracebackObject())
  381. self.assertIsNotNone(expected)
  382. self.assertEqual(expected, observed)
  383. def test_getTracebackObjectFromCaptureVarsAndClean(self):
  384. """
  385. If the Failure was created with captureVars, then C{getTracebackObject}
  386. returns an object that looks the same to L{traceback.extract_tb}.
  387. """
  388. f = getDivisionFailure(captureVars=True)
  389. expected = traceback.extract_tb(f.getTracebackObject())
  390. f.cleanFailure()
  391. observed = traceback.extract_tb(f.getTracebackObject())
  392. self.assertEqual(expected, observed)
  393. def test_getTracebackObjectWithoutTraceback(self):
  394. """
  395. L{failure.Failure}s need not be constructed with traceback objects. If
  396. a C{Failure} has no traceback information at all, C{getTracebackObject}
  397. just returns None.
  398. None is a good value, because traceback.extract_tb(None) -> [].
  399. """
  400. f = failure.Failure(Exception("some error"))
  401. self.assertIsNone(f.getTracebackObject())
  402. def test_tracebackFromExceptionInPython3(self):
  403. """
  404. If a L{failure.Failure} is constructed with an exception but no
  405. traceback in Python 3, the traceback will be extracted from the
  406. exception's C{__traceback__} attribute.
  407. """
  408. try:
  409. 1/0
  410. except:
  411. klass, exception, tb = sys.exc_info()
  412. f = failure.Failure(exception)
  413. self.assertIs(f.tb, tb)
  414. def test_cleanFailureRemovesTracebackInPython3(self):
  415. """
  416. L{failure.Failure.cleanFailure} sets the C{__traceback__} attribute of
  417. the exception to L{None} in Python 3.
  418. """
  419. f = getDivisionFailure()
  420. self.assertIsNotNone(f.tb)
  421. self.assertIs(f.value.__traceback__, f.tb)
  422. f.cleanFailure()
  423. self.assertIsNone(f.value.__traceback__)
  424. if getattr(BaseException, "__traceback__", None) is None:
  425. test_tracebackFromExceptionInPython3.skip = "Python 3 only."
  426. test_cleanFailureRemovesTracebackInPython3.skip = "Python 3 only."
  427. def test_repr(self):
  428. """
  429. The C{repr} of a L{failure.Failure} shows the type and string
  430. representation of the underlying exception.
  431. """
  432. f = getDivisionFailure()
  433. typeName = reflect.fullyQualifiedName(ZeroDivisionError)
  434. self.assertEqual(
  435. repr(f),
  436. '<twisted.python.failure.Failure '
  437. '%s: division by zero>' % (typeName,))
  438. class BrokenStr(Exception):
  439. """
  440. An exception class the instances of which cannot be presented as strings via
  441. C{str}.
  442. """
  443. def __str__(self):
  444. # Could raise something else, but there's no point as yet.
  445. raise self
  446. class BrokenExceptionMetaclass(type):
  447. """
  448. A metaclass for an exception type which cannot be presented as a string via
  449. C{str}.
  450. """
  451. def __str__(self):
  452. raise ValueError("You cannot make a string out of me.")
  453. class BrokenExceptionType(Exception, object):
  454. """
  455. The aforementioned exception type which cnanot be presented as a string via
  456. C{str}.
  457. """
  458. __metaclass__ = BrokenExceptionMetaclass
  459. class GetTracebackTests(SynchronousTestCase):
  460. """
  461. Tests for L{Failure.getTraceback}.
  462. """
  463. def _brokenValueTest(self, detail):
  464. """
  465. Construct a L{Failure} with an exception that raises an exception from
  466. its C{__str__} method and then call C{getTraceback} with the specified
  467. detail and verify that it returns a string.
  468. """
  469. x = BrokenStr()
  470. f = failure.Failure(x)
  471. traceback = f.getTraceback(detail=detail)
  472. self.assertIsInstance(traceback, str)
  473. def test_brokenValueBriefDetail(self):
  474. """
  475. A L{Failure} might wrap an exception with a C{__str__} method which
  476. raises an exception. In this case, calling C{getTraceback} on the
  477. failure with the C{"brief"} detail does not raise an exception.
  478. """
  479. self._brokenValueTest("brief")
  480. def test_brokenValueDefaultDetail(self):
  481. """
  482. Like test_brokenValueBriefDetail, but for the C{"default"} detail case.
  483. """
  484. self._brokenValueTest("default")
  485. def test_brokenValueVerboseDetail(self):
  486. """
  487. Like test_brokenValueBriefDetail, but for the C{"default"} detail case.
  488. """
  489. self._brokenValueTest("verbose")
  490. def _brokenTypeTest(self, detail):
  491. """
  492. Construct a L{Failure} with an exception type that raises an exception
  493. from its C{__str__} method and then call C{getTraceback} with the
  494. specified detail and verify that it returns a string.
  495. """
  496. f = failure.Failure(BrokenExceptionType())
  497. traceback = f.getTraceback(detail=detail)
  498. self.assertIsInstance(traceback, str)
  499. def test_brokenTypeBriefDetail(self):
  500. """
  501. A L{Failure} might wrap an exception the type object of which has a
  502. C{__str__} method which raises an exception. In this case, calling
  503. C{getTraceback} on the failure with the C{"brief"} detail does not raise
  504. an exception.
  505. """
  506. self._brokenTypeTest("brief")
  507. def test_brokenTypeDefaultDetail(self):
  508. """
  509. Like test_brokenTypeBriefDetail, but for the C{"default"} detail case.
  510. """
  511. self._brokenTypeTest("default")
  512. def test_brokenTypeVerboseDetail(self):
  513. """
  514. Like test_brokenTypeBriefDetail, but for the C{"verbose"} detail case.
  515. """
  516. self._brokenTypeTest("verbose")
  517. class FindFailureTests(SynchronousTestCase):
  518. """
  519. Tests for functionality related to L{Failure._findFailure}.
  520. """
  521. def test_findNoFailureInExceptionHandler(self):
  522. """
  523. Within an exception handler, _findFailure should return
  524. L{None} in case no Failure is associated with the current
  525. exception.
  526. """
  527. try:
  528. 1/0
  529. except:
  530. self.assertIsNone(failure.Failure._findFailure())
  531. else:
  532. self.fail("No exception raised from 1/0!?")
  533. def test_findNoFailure(self):
  534. """
  535. Outside of an exception handler, _findFailure should return None.
  536. """
  537. if sys.version_info < (3, 0):
  538. sys.exc_clear()
  539. self.assertIsNone(sys.exc_info()[-1]) #environment sanity check
  540. self.assertIsNone(failure.Failure._findFailure())
  541. def test_findFailure(self):
  542. """
  543. Within an exception handler, it should be possible to find the
  544. original Failure that caused the current exception (if it was
  545. caused by raiseException).
  546. """
  547. f = getDivisionFailure()
  548. f.cleanFailure()
  549. try:
  550. f.raiseException()
  551. except:
  552. self.assertEqual(failure.Failure._findFailure(), f)
  553. else:
  554. self.fail("No exception raised from raiseException!?")
  555. def test_failureConstructionFindsOriginalFailure(self):
  556. """
  557. When a Failure is constructed in the context of an exception
  558. handler that is handling an exception raised by
  559. raiseException, the new Failure should be chained to that
  560. original Failure.
  561. """
  562. f = getDivisionFailure()
  563. f.cleanFailure()
  564. try:
  565. f.raiseException()
  566. except:
  567. newF = failure.Failure()
  568. self.assertEqual(f.getTraceback(), newF.getTraceback())
  569. else:
  570. self.fail("No exception raised from raiseException!?")
  571. def test_failureConstructionWithMungedStackSucceeds(self):
  572. """
  573. Pyrex and Cython are known to insert fake stack frames so as to give
  574. more Python-like tracebacks. These stack frames with empty code objects
  575. should not break extraction of the exception.
  576. """
  577. try:
  578. raiser.raiseException()
  579. except raiser.RaiserException:
  580. f = failure.Failure()
  581. self.assertTrue(f.check(raiser.RaiserException))
  582. else:
  583. self.fail("No exception raised from extension?!")
  584. if raiser is None:
  585. skipMsg = "raiser extension not available"
  586. test_failureConstructionWithMungedStackSucceeds.skip = skipMsg
  587. # On Python 3.5, extract_tb returns "FrameSummary" objects, which are almost
  588. # like the old tuples. This being different does not affect the actual tests
  589. # as we are testing that the input works, and that extract_tb returns something
  590. # reasonable.
  591. if sys.version_info < (3, 5):
  592. _tb = lambda fn, lineno, name, text: (fn, lineno, name, text)
  593. else:
  594. from traceback import FrameSummary
  595. _tb = lambda fn, lineno, name, text: FrameSummary(fn, lineno, name)
  596. class FormattableTracebackTests(SynchronousTestCase):
  597. """
  598. Whitebox tests that show that L{failure._Traceback} constructs objects that
  599. can be used by L{traceback.extract_tb}.
  600. If the objects can be used by L{traceback.extract_tb}, then they can be
  601. formatted using L{traceback.format_tb} and friends.
  602. """
  603. def test_singleFrame(self):
  604. """
  605. A C{_Traceback} object constructed with a single frame should be able
  606. to be passed to L{traceback.extract_tb}, and we should get a singleton
  607. list containing a (filename, lineno, methodname, line) tuple.
  608. """
  609. tb = failure._Traceback([['method', 'filename.py', 123, {}, {}]])
  610. # Note that we don't need to test that extract_tb correctly extracts
  611. # the line's contents. In this case, since filename.py doesn't exist,
  612. # it will just use None.
  613. self.assertEqual(traceback.extract_tb(tb),
  614. [_tb('filename.py', 123, 'method', None)])
  615. def test_manyFrames(self):
  616. """
  617. A C{_Traceback} object constructed with multiple frames should be able
  618. to be passed to L{traceback.extract_tb}, and we should get a list
  619. containing a tuple for each frame.
  620. """
  621. tb = failure._Traceback([
  622. ['method1', 'filename.py', 123, {}, {}],
  623. ['method2', 'filename.py', 235, {}, {}]])
  624. self.assertEqual(traceback.extract_tb(tb),
  625. [_tb('filename.py', 123, 'method1', None),
  626. _tb('filename.py', 235, 'method2', None)])
  627. class FrameAttributesTests(SynchronousTestCase):
  628. """
  629. _Frame objects should possess some basic attributes that qualify them as
  630. fake python Frame objects.
  631. """
  632. def test_fakeFrameAttributes(self):
  633. """
  634. L{_Frame} instances have the C{f_globals} and C{f_locals} attributes
  635. bound to C{dict} instance. They also have the C{f_code} attribute
  636. bound to something like a code object.
  637. """
  638. frame = failure._Frame("dummyname", "dummyfilename")
  639. self.assertIsInstance(frame.f_globals, dict)
  640. self.assertIsInstance(frame.f_locals, dict)
  641. self.assertIsInstance(frame.f_code, failure._Code)
  642. class DebugModeTests(SynchronousTestCase):
  643. """
  644. Failure's debug mode should allow jumping into the debugger.
  645. """
  646. def setUp(self):
  647. """
  648. Override pdb.post_mortem so we can make sure it's called.
  649. """
  650. # Make sure any changes we make are reversed:
  651. post_mortem = pdb.post_mortem
  652. if _shouldEnableNewStyle:
  653. origInit = failure.Failure.__init__
  654. else:
  655. origInit = failure.Failure.__dict__['__init__']
  656. def restore():
  657. pdb.post_mortem = post_mortem
  658. if _shouldEnableNewStyle:
  659. failure.Failure.__init__ = origInit
  660. else:
  661. failure.Failure.__dict__['__init__'] = origInit
  662. self.addCleanup(restore)
  663. self.result = []
  664. pdb.post_mortem = self.result.append
  665. failure.startDebugMode()
  666. def test_regularFailure(self):
  667. """
  668. If startDebugMode() is called, calling Failure() will first call
  669. pdb.post_mortem with the traceback.
  670. """
  671. try:
  672. 1/0
  673. except:
  674. typ, exc, tb = sys.exc_info()
  675. f = failure.Failure()
  676. self.assertEqual(self.result, [tb])
  677. self.assertFalse(f.captureVars)
  678. def test_captureVars(self):
  679. """
  680. If startDebugMode() is called, passing captureVars to Failure() will
  681. not blow up.
  682. """
  683. try:
  684. 1/0
  685. except:
  686. typ, exc, tb = sys.exc_info()
  687. f = failure.Failure(captureVars=True)
  688. self.assertEqual(self.result, [tb])
  689. self.assertTrue(f.captureVars)
  690. class ExtendedGeneratorTests(SynchronousTestCase):
  691. """
  692. Tests C{failure.Failure} support for generator features added in Python 2.5
  693. """
  694. def _throwIntoGenerator(self, f, g):
  695. try:
  696. f.throwExceptionIntoGenerator(g)
  697. except StopIteration:
  698. pass
  699. else:
  700. self.fail("throwExceptionIntoGenerator should have raised "
  701. "StopIteration")
  702. def test_throwExceptionIntoGenerator(self):
  703. """
  704. It should be possible to throw the exception that a Failure
  705. represents into a generator.
  706. """
  707. stuff = []
  708. def generator():
  709. try:
  710. yield
  711. except:
  712. stuff.append(sys.exc_info())
  713. else:
  714. self.fail("Yield should have yielded exception.")
  715. g = generator()
  716. f = getDivisionFailure()
  717. next(g)
  718. self._throwIntoGenerator(f, g)
  719. self.assertEqual(stuff[0][0], ZeroDivisionError)
  720. self.assertIsInstance(stuff[0][1], ZeroDivisionError)
  721. self.assertEqual(traceback.extract_tb(stuff[0][2])[-1][-1], "1/0")
  722. def test_findFailureInGenerator(self):
  723. """
  724. Within an exception handler, it should be possible to find the
  725. original Failure that caused the current exception (if it was
  726. caused by throwExceptionIntoGenerator).
  727. """
  728. f = getDivisionFailure()
  729. f.cleanFailure()
  730. foundFailures = []
  731. def generator():
  732. try:
  733. yield
  734. except:
  735. foundFailures.append(failure.Failure._findFailure())
  736. else:
  737. self.fail("No exception sent to generator")
  738. g = generator()
  739. next(g)
  740. self._throwIntoGenerator(f, g)
  741. self.assertEqual(foundFailures, [f])
  742. def test_failureConstructionFindsOriginalFailure(self):
  743. """
  744. When a Failure is constructed in the context of an exception
  745. handler that is handling an exception raised by
  746. throwExceptionIntoGenerator, the new Failure should be chained to that
  747. original Failure.
  748. """
  749. f = getDivisionFailure()
  750. f.cleanFailure()
  751. newFailures = []
  752. def generator():
  753. try:
  754. yield
  755. except:
  756. newFailures.append(failure.Failure())
  757. else:
  758. self.fail("No exception sent to generator")
  759. g = generator()
  760. next(g)
  761. self._throwIntoGenerator(f, g)
  762. self.assertEqual(len(newFailures), 1)
  763. self.assertEqual(newFailures[0].getTraceback(), f.getTraceback())
  764. if _PY3:
  765. # FIXME: https://twistedmatrix.com/trac/ticket/5949
  766. test_findFailureInGenerator.skip = (
  767. "Python 3 support to be fixed in #5949")
  768. test_failureConstructionFindsOriginalFailure.skip = (
  769. "Python 3 support to be fixed in #5949")
  770. def test_ambiguousFailureInGenerator(self):
  771. """
  772. When a generator reraises a different exception,
  773. L{Failure._findFailure} inside the generator should find the reraised
  774. exception rather than original one.
  775. """
  776. def generator():
  777. try:
  778. try:
  779. yield
  780. except:
  781. [][1]
  782. except:
  783. self.assertIsInstance(failure.Failure().value, IndexError)
  784. g = generator()
  785. next(g)
  786. f = getDivisionFailure()
  787. self._throwIntoGenerator(f, g)
  788. def test_ambiguousFailureFromGenerator(self):
  789. """
  790. When a generator reraises a different exception,
  791. L{Failure._findFailure} above the generator should find the reraised
  792. exception rather than original one.
  793. """
  794. def generator():
  795. try:
  796. yield
  797. except:
  798. [][1]
  799. g = generator()
  800. next(g)
  801. f = getDivisionFailure()
  802. try:
  803. self._throwIntoGenerator(f, g)
  804. except:
  805. self.assertIsInstance(failure.Failure().value, IndexError)