Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_failure.py 34KB

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