_synctest.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. # -*- test-case-name: twisted.trial.test -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Things likely to be used by writers of unit tests.
  6. Maintainer: Jonathan Lange
  7. """
  8. import inspect
  9. import os
  10. import sys
  11. import tempfile
  12. import types
  13. import unittest as pyunit
  14. import warnings
  15. from dis import findlinestarts as _findlinestarts
  16. from typing import (
  17. Any,
  18. Callable,
  19. Coroutine,
  20. Generator,
  21. Iterable,
  22. List,
  23. NoReturn,
  24. Optional,
  25. Tuple,
  26. Type,
  27. TypeVar,
  28. Union,
  29. )
  30. # Python 2.7 and higher has skip support built-in
  31. from unittest import SkipTest
  32. from attrs import frozen
  33. from typing_extensions import ParamSpec
  34. from twisted.internet.defer import Deferred, ensureDeferred
  35. from twisted.python import failure, log, monkey
  36. from twisted.python.deprecate import (
  37. DEPRECATION_WARNING_FORMAT,
  38. getDeprecationWarningString,
  39. getVersionString,
  40. warnAboutFunction,
  41. )
  42. from twisted.python.reflect import fullyQualifiedName
  43. from twisted.python.util import runWithWarningsSuppressed
  44. from twisted.trial import itrial, util
  45. _P = ParamSpec("_P")
  46. T = TypeVar("T")
  47. class FailTest(AssertionError):
  48. """
  49. Raised to indicate the current test has failed to pass.
  50. """
  51. @frozen
  52. class Todo:
  53. """
  54. Internal object used to mark a L{TestCase} as 'todo'. Tests marked 'todo'
  55. are reported differently in Trial L{TestResult}s. If todo'd tests fail,
  56. they do not fail the suite and the errors are reported in a separate
  57. category. If todo'd tests succeed, Trial L{TestResult}s will report an
  58. unexpected success.
  59. @ivar reason: A string explaining why the test is marked 'todo'
  60. @ivar errors: An iterable of exception types that the test is expected to
  61. raise. If one of these errors is raised by the test, it will be
  62. trapped. Raising any other kind of error will fail the test. If
  63. L{None} then all errors will be trapped.
  64. """
  65. reason: str
  66. errors: Optional[Iterable[Type[BaseException]]] = None
  67. def __repr__(self) -> str:
  68. return f"<Todo reason={self.reason!r} errors={self.errors!r}>"
  69. def expected(self, failure):
  70. """
  71. @param failure: A L{twisted.python.failure.Failure}.
  72. @return: C{True} if C{failure} is expected, C{False} otherwise.
  73. """
  74. if self.errors is None:
  75. return True
  76. for error in self.errors:
  77. if failure.check(error):
  78. return True
  79. return False
  80. def makeTodo(
  81. value: Union[
  82. str, Tuple[Union[Type[BaseException], Iterable[Type[BaseException]]], str]
  83. ]
  84. ) -> Todo:
  85. """
  86. Return a L{Todo} object built from C{value}.
  87. If C{value} is a string, return a Todo that expects any exception with
  88. C{value} as a reason. If C{value} is a tuple, the second element is used
  89. as the reason and the first element as the excepted error(s).
  90. @param value: A string or a tuple of C{(errors, reason)}, where C{errors}
  91. is either a single exception class or an iterable of exception classes.
  92. @return: A L{Todo} object.
  93. """
  94. if isinstance(value, str):
  95. return Todo(reason=value)
  96. if isinstance(value, tuple):
  97. errors, reason = value
  98. if isinstance(errors, type):
  99. iterableErrors: Iterable[Type[BaseException]] = [errors]
  100. else:
  101. iterableErrors = errors
  102. return Todo(reason=reason, errors=iterableErrors)
  103. class _Warning:
  104. """
  105. A L{_Warning} instance represents one warning emitted through the Python
  106. warning system (L{warnings}). This is used to insulate callers of
  107. L{_collectWarnings} from changes to the Python warnings system which might
  108. otherwise require changes to the warning objects that function passes to
  109. the observer object it accepts.
  110. @ivar message: The string which was passed as the message parameter to
  111. L{warnings.warn}.
  112. @ivar category: The L{Warning} subclass which was passed as the category
  113. parameter to L{warnings.warn}.
  114. @ivar filename: The name of the file containing the definition of the code
  115. object which was C{stacklevel} frames above the call to
  116. L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel}
  117. parameter passed to L{warnings.warn}.
  118. @ivar lineno: The source line associated with the active instruction of the
  119. code object object which was C{stacklevel} frames above the call to
  120. L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel}
  121. parameter passed to L{warnings.warn}.
  122. """
  123. def __init__(self, message, category, filename, lineno):
  124. self.message = message
  125. self.category = category
  126. self.filename = filename
  127. self.lineno = lineno
  128. def _setWarningRegistryToNone(modules):
  129. """
  130. Disable the per-module cache for every module found in C{modules}, typically
  131. C{sys.modules}.
  132. @param modules: Dictionary of modules, typically sys.module dict
  133. """
  134. for v in list(modules.values()):
  135. if v is not None:
  136. try:
  137. v.__warningregistry__ = None
  138. except BaseException:
  139. # Don't specify a particular exception type to handle in case
  140. # some wacky object raises some wacky exception in response to
  141. # the setattr attempt.
  142. pass
  143. def _collectWarnings(observeWarning, f, *args, **kwargs):
  144. """
  145. Call C{f} with C{args} positional arguments and C{kwargs} keyword arguments
  146. and collect all warnings which are emitted as a result in a list.
  147. @param observeWarning: A callable which will be invoked with a L{_Warning}
  148. instance each time a warning is emitted.
  149. @return: The return value of C{f(*args, **kwargs)}.
  150. """
  151. def showWarning(message, category, filename, lineno, file=None, line=None):
  152. assert isinstance(message, Warning)
  153. observeWarning(_Warning(str(message), category, filename, lineno))
  154. # Disable the per-module cache for every module otherwise if the warning
  155. # which the caller is expecting us to collect was already emitted it won't
  156. # be re-emitted by the call to f which happens below.
  157. _setWarningRegistryToNone(sys.modules)
  158. origFilters = warnings.filters[:]
  159. origShow = warnings.showwarning
  160. warnings.simplefilter("always")
  161. try:
  162. warnings.showwarning = showWarning
  163. result = f(*args, **kwargs)
  164. finally:
  165. warnings.filters[:] = origFilters
  166. warnings.showwarning = origShow
  167. return result
  168. class UnsupportedTrialFeature(Exception):
  169. """A feature of twisted.trial was used that pyunit cannot support."""
  170. class PyUnitResultAdapter:
  171. """
  172. Wrap a C{TestResult} from the standard library's C{unittest} so that it
  173. supports the extended result types from Trial, and also supports
  174. L{twisted.python.failure.Failure}s being passed to L{addError} and
  175. L{addFailure}.
  176. """
  177. def __init__(self, original):
  178. """
  179. @param original: A C{TestResult} instance from C{unittest}.
  180. """
  181. self.original = original
  182. def _exc_info(self, err):
  183. return util.excInfoOrFailureToExcInfo(err)
  184. def startTest(self, method):
  185. self.original.startTest(method)
  186. def stopTest(self, method):
  187. self.original.stopTest(method)
  188. def addFailure(self, test, fail):
  189. self.original.addFailure(test, self._exc_info(fail))
  190. def addError(self, test, error):
  191. self.original.addError(test, self._exc_info(error))
  192. def _unsupported(self, test, feature, info):
  193. self.original.addFailure(
  194. test,
  195. (UnsupportedTrialFeature, UnsupportedTrialFeature(feature, info), None),
  196. )
  197. def addSkip(self, test, reason):
  198. """
  199. Report the skip as a failure.
  200. """
  201. self.original.addSkip(test, reason)
  202. def addUnexpectedSuccess(self, test, todo=None):
  203. """
  204. Report the unexpected success as a failure.
  205. """
  206. self._unsupported(test, "unexpected success", todo)
  207. def addExpectedFailure(self, test, error):
  208. """
  209. Report the expected failure (i.e. todo) as a failure.
  210. """
  211. self._unsupported(test, "expected failure", error)
  212. def addSuccess(self, test):
  213. self.original.addSuccess(test)
  214. def upDownError(self, method, error, warn, printStatus):
  215. pass
  216. class _AssertRaisesContext:
  217. """
  218. A helper for implementing C{assertRaises}. This is a context manager and a
  219. helper method to support the non-context manager version of
  220. C{assertRaises}.
  221. @ivar _testCase: See C{testCase} parameter of C{__init__}
  222. @ivar _expected: See C{expected} parameter of C{__init__}
  223. @ivar _returnValue: The value returned by the callable being tested (only
  224. when not being used as a context manager).
  225. @ivar _expectedName: A short string describing the expected exception
  226. (usually the name of the exception class).
  227. @ivar exception: The exception which was raised by the function being
  228. tested (if it raised one).
  229. """
  230. def __init__(self, testCase, expected):
  231. """
  232. @param testCase: The L{TestCase} instance which is used to raise a
  233. test-failing exception when that is necessary.
  234. @param expected: The exception type expected to be raised.
  235. """
  236. self._testCase = testCase
  237. self._expected = expected
  238. self._returnValue = None
  239. try:
  240. self._expectedName = self._expected.__name__
  241. except AttributeError:
  242. self._expectedName = str(self._expected)
  243. def _handle(self, obj):
  244. """
  245. Call the given object using this object as a context manager.
  246. @param obj: The object to call and which is expected to raise some
  247. exception.
  248. @type obj: L{object}
  249. @return: Whatever exception is raised by C{obj()}.
  250. @rtype: L{BaseException}
  251. """
  252. with self as context:
  253. self._returnValue = obj()
  254. return context.exception
  255. def __enter__(self):
  256. return self
  257. def __exit__(self, exceptionType, exceptionValue, traceback):
  258. """
  259. Check exit exception against expected exception.
  260. """
  261. # No exception raised.
  262. if exceptionType is None:
  263. self._testCase.fail(
  264. "{} not raised ({} returned)".format(
  265. self._expectedName, self._returnValue
  266. )
  267. )
  268. if not isinstance(exceptionValue, exceptionType):
  269. # Support some Python 2.6 ridiculousness. Exceptions raised using
  270. # the C API appear here as the arguments you might pass to the
  271. # exception class to create an exception instance. So... do that
  272. # to turn them into the instances.
  273. if isinstance(exceptionValue, tuple):
  274. exceptionValue = exceptionType(*exceptionValue)
  275. else:
  276. exceptionValue = exceptionType(exceptionValue)
  277. # Store exception so that it can be access from context.
  278. self.exception = exceptionValue
  279. # Wrong exception raised.
  280. if not issubclass(exceptionType, self._expected):
  281. reason = failure.Failure(exceptionValue, exceptionType, traceback)
  282. self._testCase.fail(
  283. "{} raised instead of {}:\n {}".format(
  284. fullyQualifiedName(exceptionType),
  285. self._expectedName,
  286. reason.getTraceback(),
  287. ),
  288. )
  289. # All good.
  290. return True
  291. class _Assertions(pyunit.TestCase):
  292. """
  293. Replaces many of the built-in TestCase assertions. In general, these
  294. assertions provide better error messages and are easier to use in
  295. callbacks.
  296. """
  297. def fail(self, msg: Optional[object] = None) -> NoReturn:
  298. """
  299. Absolutely fail the test. Do not pass go, do not collect $200.
  300. @param msg: the message that will be displayed as the reason for the
  301. failure
  302. """
  303. raise self.failureException(msg)
  304. def assertFalse(self, condition, msg=None):
  305. """
  306. Fail the test if C{condition} evaluates to True.
  307. @param condition: any object that defines __nonzero__
  308. """
  309. super().assertFalse(condition, msg)
  310. return condition
  311. assertNot = assertFalse
  312. failUnlessFalse = assertFalse
  313. failIf = assertFalse
  314. def assertTrue(self, condition, msg=None):
  315. """
  316. Fail the test if C{condition} evaluates to False.
  317. @param condition: any object that defines __nonzero__
  318. """
  319. super().assertTrue(condition, msg)
  320. return condition
  321. assert_ = assertTrue
  322. failUnlessTrue = assertTrue
  323. failUnless = assertTrue
  324. def assertRaises(self, exception, f=None, *args, **kwargs):
  325. """
  326. Fail the test unless calling the function C{f} with the given
  327. C{args} and C{kwargs} raises C{exception}. The failure will report
  328. the traceback and call stack of the unexpected exception.
  329. @param exception: exception type that is to be expected
  330. @param f: the function to call
  331. @return: If C{f} is L{None}, a context manager which will make an
  332. assertion about the exception raised from the suite it manages. If
  333. C{f} is not L{None}, the exception raised by C{f}.
  334. @raise self.failureException: Raised if the function call does
  335. not raise an exception or if it raises an exception of a
  336. different type.
  337. """
  338. context = _AssertRaisesContext(self, exception)
  339. if f is None:
  340. return context
  341. return context._handle(lambda: f(*args, **kwargs))
  342. # unittest.TestCase.assertRaises() is defined with 4 arguments
  343. # but we define it with 5 arguments. So we need to tell mypy
  344. # to ignore the following assignment to failUnlessRaises
  345. failUnlessRaises = assertRaises # type: ignore[assignment]
  346. def assertEqual(self, first, second, msg=None):
  347. """
  348. Fail the test if C{first} and C{second} are not equal.
  349. @param msg: A string describing the failure that's included in the
  350. exception.
  351. """
  352. super().assertEqual(first, second, msg)
  353. return first
  354. failUnlessEqual = assertEqual
  355. failUnlessEquals = assertEqual
  356. assertEquals = assertEqual
  357. def assertIs(self, first, second, msg=None):
  358. """
  359. Fail the test if C{first} is not C{second}. This is an
  360. obect-identity-equality test, not an object equality
  361. (i.e. C{__eq__}) test.
  362. @param msg: if msg is None, then the failure message will be
  363. '%r is not %r' % (first, second)
  364. """
  365. if first is not second:
  366. raise self.failureException(msg or f"{first!r} is not {second!r}")
  367. return first
  368. failUnlessIdentical = assertIs
  369. assertIdentical = assertIs
  370. def assertIsNot(self, first, second, msg=None):
  371. """
  372. Fail the test if C{first} is C{second}. This is an
  373. obect-identity-equality test, not an object equality
  374. (i.e. C{__eq__}) test.
  375. @param msg: if msg is None, then the failure message will be
  376. '%r is %r' % (first, second)
  377. """
  378. if first is second:
  379. raise self.failureException(msg or f"{first!r} is {second!r}")
  380. return first
  381. failIfIdentical = assertIsNot
  382. assertNotIdentical = assertIsNot
  383. def assertNotEqual(self, first, second, msg=None):
  384. """
  385. Fail the test if C{first} == C{second}.
  386. @param msg: if msg is None, then the failure message will be
  387. '%r == %r' % (first, second)
  388. """
  389. if not first != second:
  390. raise self.failureException(msg or f"{first!r} == {second!r}")
  391. return first
  392. assertNotEquals = assertNotEqual
  393. failIfEquals = assertNotEqual
  394. failIfEqual = assertNotEqual
  395. def assertIn(self, containee, container, msg=None):
  396. """
  397. Fail the test if C{containee} is not found in C{container}.
  398. @param containee: the value that should be in C{container}
  399. @param container: a sequence type, or in the case of a mapping type,
  400. will follow semantics of 'if key in dict.keys()'
  401. @param msg: if msg is None, then the failure message will be
  402. '%r not in %r' % (first, second)
  403. """
  404. if containee not in container:
  405. raise self.failureException(msg or f"{containee!r} not in {container!r}")
  406. return containee
  407. failUnlessIn = assertIn
  408. def assertNotIn(self, containee, container, msg=None):
  409. """
  410. Fail the test if C{containee} is found in C{container}.
  411. @param containee: the value that should not be in C{container}
  412. @param container: a sequence type, or in the case of a mapping type,
  413. will follow semantics of 'if key in dict.keys()'
  414. @param msg: if msg is None, then the failure message will be
  415. '%r in %r' % (first, second)
  416. """
  417. if containee in container:
  418. raise self.failureException(msg or f"{containee!r} in {container!r}")
  419. return containee
  420. failIfIn = assertNotIn
  421. def assertNotAlmostEqual(self, first, second, places=7, msg=None, delta=None):
  422. """
  423. Fail if the two objects are equal as determined by their
  424. difference rounded to the given number of decimal places
  425. (default 7) and comparing to zero.
  426. @note: decimal places (from zero) is usually not the same
  427. as significant digits (measured from the most
  428. significant digit).
  429. @note: included for compatibility with PyUnit test cases
  430. """
  431. if round(second - first, places) == 0:
  432. raise self.failureException(
  433. msg or f"{first!r} == {second!r} within {places!r} places"
  434. )
  435. return first
  436. assertNotAlmostEquals = assertNotAlmostEqual # type:ignore[assignment]
  437. failIfAlmostEqual = assertNotAlmostEqual # type:ignore[assignment]
  438. failIfAlmostEquals = assertNotAlmostEqual
  439. def assertAlmostEqual(self, first, second, places=7, msg=None, delta=None):
  440. """
  441. Fail if the two objects are unequal as determined by their
  442. difference rounded to the given number of decimal places
  443. (default 7) and comparing to zero.
  444. @note: decimal places (from zero) is usually not the same
  445. as significant digits (measured from the most
  446. significant digit).
  447. @note: included for compatibility with PyUnit test cases
  448. """
  449. if round(second - first, places) != 0:
  450. raise self.failureException(
  451. msg or f"{first!r} != {second!r} within {places!r} places"
  452. )
  453. return first
  454. assertAlmostEquals = assertAlmostEqual # type:ignore[assignment]
  455. failUnlessAlmostEqual = assertAlmostEqual # type:ignore[assignment]
  456. def assertApproximates(self, first, second, tolerance, msg=None):
  457. """
  458. Fail if C{first} - C{second} > C{tolerance}
  459. @param msg: if msg is None, then the failure message will be
  460. '%r ~== %r' % (first, second)
  461. """
  462. if abs(first - second) > tolerance:
  463. raise self.failureException(msg or f"{first} ~== {second}")
  464. return first
  465. failUnlessApproximates = assertApproximates
  466. def assertSubstring(self, substring, astring, msg=None):
  467. """
  468. Fail if C{substring} does not exist within C{astring}.
  469. """
  470. return self.failUnlessIn(substring, astring, msg)
  471. failUnlessSubstring = assertSubstring
  472. def assertNotSubstring(self, substring, astring, msg=None):
  473. """
  474. Fail if C{astring} contains C{substring}.
  475. """
  476. return self.failIfIn(substring, astring, msg)
  477. failIfSubstring = assertNotSubstring
  478. def assertWarns(self, category, message, filename, f, *args, **kwargs):
  479. """
  480. Fail if the given function doesn't generate the specified warning when
  481. called. It calls the function, checks the warning, and forwards the
  482. result of the function if everything is fine.
  483. @param category: the category of the warning to check.
  484. @param message: the output message of the warning to check.
  485. @param filename: the filename where the warning should come from.
  486. @param f: the function which is supposed to generate the warning.
  487. @type f: any callable.
  488. @param args: the arguments to C{f}.
  489. @param kwargs: the keywords arguments to C{f}.
  490. @return: the result of the original function C{f}.
  491. """
  492. warningsShown = []
  493. result = _collectWarnings(warningsShown.append, f, *args, **kwargs)
  494. if not warningsShown:
  495. self.fail("No warnings emitted")
  496. first = warningsShown[0]
  497. for other in warningsShown[1:]:
  498. if (other.message, other.category) != (first.message, first.category):
  499. self.fail("Can't handle different warnings")
  500. self.assertEqual(first.message, message)
  501. self.assertIdentical(first.category, category)
  502. # Use starts with because of .pyc/.pyo issues.
  503. self.assertTrue(
  504. filename.startswith(first.filename),
  505. f"Warning in {first.filename!r}, expected {filename!r}",
  506. )
  507. # It would be nice to be able to check the line number as well, but
  508. # different configurations actually end up reporting different line
  509. # numbers (generally the variation is only 1 line, but that's enough
  510. # to fail the test erroneously...).
  511. # self.assertEqual(lineno, xxx)
  512. return result
  513. failUnlessWarns = assertWarns
  514. def assertIsInstance(self, instance, classOrTuple, message=None):
  515. """
  516. Fail if C{instance} is not an instance of the given class or of
  517. one of the given classes.
  518. @param instance: the object to test the type (first argument of the
  519. C{isinstance} call).
  520. @type instance: any.
  521. @param classOrTuple: the class or classes to test against (second
  522. argument of the C{isinstance} call).
  523. @type classOrTuple: class, type, or tuple.
  524. @param message: Custom text to include in the exception text if the
  525. assertion fails.
  526. """
  527. if not isinstance(instance, classOrTuple):
  528. if message is None:
  529. suffix = ""
  530. else:
  531. suffix = ": " + message
  532. self.fail(f"{instance!r} is not an instance of {classOrTuple}{suffix}")
  533. failUnlessIsInstance = assertIsInstance
  534. def assertNotIsInstance(self, instance, classOrTuple):
  535. """
  536. Fail if C{instance} is an instance of the given class or of one of the
  537. given classes.
  538. @param instance: the object to test the type (first argument of the
  539. C{isinstance} call).
  540. @type instance: any.
  541. @param classOrTuple: the class or classes to test against (second
  542. argument of the C{isinstance} call).
  543. @type classOrTuple: class, type, or tuple.
  544. """
  545. if isinstance(instance, classOrTuple):
  546. self.fail(f"{instance!r} is an instance of {classOrTuple}")
  547. failIfIsInstance = assertNotIsInstance
  548. def successResultOf(
  549. self,
  550. deferred: Union[
  551. Coroutine[Deferred[T], Any, T],
  552. Generator[Deferred[T], Any, T],
  553. Deferred[T],
  554. ],
  555. ) -> T:
  556. """
  557. Return the current success result of C{deferred} or raise
  558. C{self.failureException}.
  559. @param deferred: A L{Deferred<twisted.internet.defer.Deferred>} or
  560. I{coroutine} which has a success result.
  561. For a L{Deferred<twisted.internet.defer.Deferred>} this means
  562. L{Deferred.callback<twisted.internet.defer.Deferred.callback>} or
  563. L{Deferred.errback<twisted.internet.defer.Deferred.errback>} has
  564. been called on it and it has reached the end of its callback chain
  565. and the last callback or errback returned a
  566. non-L{failure.Failure}.
  567. For a I{coroutine} this means all awaited values have a success
  568. result.
  569. @raise SynchronousTestCase.failureException: If the
  570. L{Deferred<twisted.internet.defer.Deferred>} has no result or has a
  571. failure result.
  572. @return: The result of C{deferred}.
  573. """
  574. deferred = ensureDeferred(deferred)
  575. results: List[Union[T, failure.Failure]] = []
  576. deferred.addBoth(results.append)
  577. if not results:
  578. self.fail(
  579. "Success result expected on {!r}, found no result instead".format(
  580. deferred
  581. )
  582. )
  583. result = results[0]
  584. if isinstance(result, failure.Failure):
  585. self.fail(
  586. "Success result expected on {!r}, "
  587. "found failure result instead:\n{}".format(
  588. deferred, result.getTraceback()
  589. )
  590. )
  591. return result
  592. def failureResultOf(self, deferred, *expectedExceptionTypes):
  593. """
  594. Return the current failure result of C{deferred} or raise
  595. C{self.failureException}.
  596. @param deferred: A L{Deferred<twisted.internet.defer.Deferred>} which
  597. has a failure result. This means
  598. L{Deferred.callback<twisted.internet.defer.Deferred.callback>} or
  599. L{Deferred.errback<twisted.internet.defer.Deferred.errback>} has
  600. been called on it and it has reached the end of its callback chain
  601. and the last callback or errback raised an exception or returned a
  602. L{failure.Failure}.
  603. @type deferred: L{Deferred<twisted.internet.defer.Deferred>}
  604. @param expectedExceptionTypes: Exception types to expect - if
  605. provided, and the exception wrapped by the failure result is
  606. not one of the types provided, then this test will fail.
  607. @raise SynchronousTestCase.failureException: If the
  608. L{Deferred<twisted.internet.defer.Deferred>} has no result, has a
  609. success result, or has an unexpected failure result.
  610. @return: The failure result of C{deferred}.
  611. @rtype: L{failure.Failure}
  612. """
  613. deferred = ensureDeferred(deferred)
  614. result = []
  615. deferred.addBoth(result.append)
  616. if not result:
  617. self.fail(
  618. "Failure result expected on {!r}, found no result instead".format(
  619. deferred
  620. )
  621. )
  622. result = result[0]
  623. if not isinstance(result, failure.Failure):
  624. self.fail(
  625. "Failure result expected on {!r}, "
  626. "found success result ({!r}) instead".format(deferred, result)
  627. )
  628. if expectedExceptionTypes and not result.check(*expectedExceptionTypes):
  629. expectedString = " or ".join(
  630. [".".join((t.__module__, t.__name__)) for t in expectedExceptionTypes]
  631. )
  632. self.fail(
  633. "Failure of type ({}) expected on {!r}, "
  634. "found type {!r} instead: {}".format(
  635. expectedString, deferred, result.type, result.getTraceback()
  636. )
  637. )
  638. return result
  639. def assertNoResult(self, deferred):
  640. """
  641. Assert that C{deferred} does not have a result at this point.
  642. If the assertion succeeds, then the result of C{deferred} is left
  643. unchanged. Otherwise, any L{failure.Failure} result is swallowed.
  644. @param deferred: A L{Deferred<twisted.internet.defer.Deferred>} without
  645. a result. This means that neither
  646. L{Deferred.callback<twisted.internet.defer.Deferred.callback>} nor
  647. L{Deferred.errback<twisted.internet.defer.Deferred.errback>} has
  648. been called, or that the
  649. L{Deferred<twisted.internet.defer.Deferred>} is waiting on another
  650. L{Deferred<twisted.internet.defer.Deferred>} for a result.
  651. @type deferred: L{Deferred<twisted.internet.defer.Deferred>}
  652. @raise SynchronousTestCase.failureException: If the
  653. L{Deferred<twisted.internet.defer.Deferred>} has a result.
  654. """
  655. deferred = ensureDeferred(deferred)
  656. result = []
  657. def cb(res):
  658. result.append(res)
  659. return res
  660. deferred.addBoth(cb)
  661. if result:
  662. # If there is already a failure, the self.fail below will
  663. # report it, so swallow it in the deferred
  664. deferred.addErrback(lambda _: None)
  665. self.fail(
  666. "No result expected on {!r}, found {!r} instead".format(
  667. deferred, result[0]
  668. )
  669. )
  670. class _LogObserver:
  671. """
  672. Observes the Twisted logs and catches any errors.
  673. @ivar _errors: A C{list} of L{Failure} instances which were received as
  674. error events from the Twisted logging system.
  675. @ivar _added: A C{int} giving the number of times C{_add} has been called
  676. less the number of times C{_remove} has been called; used to only add
  677. this observer to the Twisted logging since once, regardless of the
  678. number of calls to the add method.
  679. @ivar _ignored: A C{list} of exception types which will not be recorded.
  680. """
  681. def __init__(self):
  682. self._errors = []
  683. self._added = 0
  684. self._ignored = []
  685. def _add(self):
  686. if self._added == 0:
  687. log.addObserver(self.gotEvent)
  688. self._added += 1
  689. def _remove(self):
  690. self._added -= 1
  691. if self._added == 0:
  692. log.removeObserver(self.gotEvent)
  693. def _ignoreErrors(self, *errorTypes):
  694. """
  695. Do not store any errors with any of the given types.
  696. """
  697. self._ignored.extend(errorTypes)
  698. def _clearIgnores(self):
  699. """
  700. Stop ignoring any errors we might currently be ignoring.
  701. """
  702. self._ignored = []
  703. def flushErrors(self, *errorTypes):
  704. """
  705. Flush errors from the list of caught errors. If no arguments are
  706. specified, remove all errors. If arguments are specified, only remove
  707. errors of those types from the stored list.
  708. """
  709. if errorTypes:
  710. flushed = []
  711. remainder = []
  712. for f in self._errors:
  713. if f.check(*errorTypes):
  714. flushed.append(f)
  715. else:
  716. remainder.append(f)
  717. self._errors = remainder
  718. else:
  719. flushed = self._errors
  720. self._errors = []
  721. return flushed
  722. def getErrors(self):
  723. """
  724. Return a list of errors caught by this observer.
  725. """
  726. return self._errors
  727. def gotEvent(self, event):
  728. """
  729. The actual observer method. Called whenever a message is logged.
  730. @param event: A dictionary containing the log message. Actual
  731. structure undocumented (see source for L{twisted.python.log}).
  732. """
  733. if event.get("isError", False) and "failure" in event:
  734. f = event["failure"]
  735. if len(self._ignored) == 0 or not f.check(*self._ignored):
  736. self._errors.append(f)
  737. _logObserver = _LogObserver()
  738. class SynchronousTestCase(_Assertions):
  739. """
  740. A unit test. The atom of the unit testing universe.
  741. This class extends C{unittest.TestCase} from the standard library. A number
  742. of convenient testing helpers are added, including logging and warning
  743. integration, monkey-patching support, and more.
  744. To write a unit test, subclass C{SynchronousTestCase} and define a method
  745. (say, 'test_foo') on the subclass. To run the test, instantiate your
  746. subclass with the name of the method, and call L{run} on the instance,
  747. passing a L{TestResult} object.
  748. The C{trial} script will automatically find any C{SynchronousTestCase}
  749. subclasses defined in modules beginning with 'test_' and construct test
  750. cases for all methods beginning with 'test'.
  751. If an error is logged during the test run, the test will fail with an
  752. error. See L{log.err}.
  753. @ivar failureException: An exception class, defaulting to C{FailTest}. If
  754. the test method raises this exception, it will be reported as a failure,
  755. rather than an exception. All of the assertion methods raise this if the
  756. assertion fails.
  757. @ivar skip: L{None} or a string explaining why this test is to be
  758. skipped. If defined, the test will not be run. Instead, it will be
  759. reported to the result object as 'skipped' (if the C{TestResult} supports
  760. skipping).
  761. @ivar todo: L{None}, a string or a tuple of C{(errors, reason)} where
  762. C{errors} is either an exception class or an iterable of exception
  763. classes, and C{reason} is a string. See L{Todo} or L{makeTodo} for more
  764. information.
  765. @ivar suppress: L{None} or a list of tuples of C{(args, kwargs)} to be
  766. passed to C{warnings.filterwarnings}. Use these to suppress warnings
  767. raised in a test. Useful for testing deprecated code. See also
  768. L{util.suppress}.
  769. """
  770. failureException = FailTest
  771. def __init__(self, methodName="runTest"):
  772. super().__init__(methodName)
  773. self._passed = False
  774. self._cleanups = []
  775. self._testMethodName = methodName
  776. testMethod = getattr(self, methodName)
  777. self._parents = [testMethod, self, sys.modules.get(self.__class__.__module__)]
  778. def __eq__(self, other: object) -> bool:
  779. """
  780. Override the comparison defined by the base TestCase which considers
  781. instances of the same class with the same _testMethodName to be
  782. equal. Since trial puts TestCase instances into a set, that
  783. definition of comparison makes it impossible to run the same test
  784. method twice. Most likely, trial should stop using a set to hold
  785. tests, but until it does, this is necessary on Python 2.6. -exarkun
  786. """
  787. if isinstance(other, SynchronousTestCase):
  788. return self is other
  789. else:
  790. return NotImplemented
  791. def __hash__(self):
  792. return hash((self.__class__, self._testMethodName))
  793. def shortDescription(self):
  794. desc = super().shortDescription()
  795. if desc is None:
  796. return self._testMethodName
  797. return desc
  798. def getSkip(self) -> Tuple[bool, Optional[str]]:
  799. """
  800. Return the skip reason set on this test, if any is set. Checks on the
  801. instance first, then the class, then the module, then packages. As
  802. soon as it finds something with a C{skip} attribute, returns that in
  803. a tuple (L{True}, L{str}).
  804. If the C{skip} attribute does not exist, look for C{__unittest_skip__}
  805. and C{__unittest_skip_why__} attributes which are set by the standard
  806. library L{unittest.skip} function.
  807. Returns (L{False}, L{None}) if it cannot find anything.
  808. See L{TestCase} docstring for more details.
  809. """
  810. skipReason = util.acquireAttribute(self._parents, "skip", None)
  811. doSkip = skipReason is not None
  812. if skipReason is None:
  813. doSkip = getattr(self, "__unittest_skip__", False)
  814. if doSkip:
  815. skipReason = getattr(self, "__unittest_skip_why__", "")
  816. return (doSkip, skipReason)
  817. def getTodo(self):
  818. """
  819. Return a L{Todo} object if the test is marked todo. Checks on the
  820. instance first, then the class, then the module, then packages. As
  821. soon as it finds something with a C{todo} attribute, returns that.
  822. Returns L{None} if it cannot find anything. See L{TestCase} docstring
  823. for more details.
  824. """
  825. todo = util.acquireAttribute(self._parents, "todo", None)
  826. if todo is None:
  827. return None
  828. return makeTodo(todo)
  829. def runTest(self):
  830. """
  831. If no C{methodName} argument is passed to the constructor, L{run} will
  832. treat this method as the thing with the actual test inside.
  833. """
  834. def run(self, result):
  835. """
  836. Run the test case, storing the results in C{result}.
  837. First runs C{setUp} on self, then runs the test method (defined in the
  838. constructor), then runs C{tearDown}. As with the standard library
  839. L{unittest.TestCase}, the return value of these methods is disregarded.
  840. In particular, returning a L{Deferred<twisted.internet.defer.Deferred>}
  841. has no special additional consequences.
  842. @param result: A L{TestResult} object.
  843. """
  844. log.msg("--> %s <--" % (self.id()))
  845. new_result = itrial.IReporter(result, None)
  846. if new_result is None:
  847. result = PyUnitResultAdapter(result)
  848. else:
  849. result = new_result
  850. result.startTest(self)
  851. (doSkip, skipReason) = self.getSkip()
  852. if doSkip: # don't run test methods that are marked as .skip
  853. result.addSkip(self, skipReason)
  854. result.stopTest(self)
  855. return
  856. self._passed = False
  857. self._warnings = []
  858. self._installObserver()
  859. # All the code inside _runFixturesAndTest will be run such that warnings
  860. # emitted by it will be collected and retrievable by flushWarnings.
  861. _collectWarnings(self._warnings.append, self._runFixturesAndTest, result)
  862. # Any collected warnings which the test method didn't flush get
  863. # re-emitted so they'll be logged or show up on stdout or whatever.
  864. for w in self.flushWarnings():
  865. try:
  866. warnings.warn_explicit(**w)
  867. except BaseException:
  868. result.addError(self, failure.Failure())
  869. result.stopTest(self)
  870. # f should be a positional only argument but that is a breaking change
  871. # see https://github.com/twisted/twisted/issues/11967
  872. def addCleanup( # type: ignore[override]
  873. self, f: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs
  874. ) -> None:
  875. """
  876. Add the given function to a list of functions to be called after the
  877. test has run, but before C{tearDown}.
  878. Functions will be run in reverse order of being added. This helps
  879. ensure that tear down complements set up.
  880. As with all aspects of L{SynchronousTestCase}, Deferreds are not
  881. supported in cleanup functions.
  882. """
  883. self._cleanups.append((f, args, kwargs))
  884. def patch(self, obj, attribute, value):
  885. """
  886. Monkey patch an object for the duration of the test.
  887. The monkey patch will be reverted at the end of the test using the
  888. L{addCleanup} mechanism.
  889. The L{monkey.MonkeyPatcher} is returned so that users can restore and
  890. re-apply the monkey patch within their tests.
  891. @param obj: The object to monkey patch.
  892. @param attribute: The name of the attribute to change.
  893. @param value: The value to set the attribute to.
  894. @return: A L{monkey.MonkeyPatcher} object.
  895. """
  896. monkeyPatch = monkey.MonkeyPatcher((obj, attribute, value))
  897. monkeyPatch.patch()
  898. self.addCleanup(monkeyPatch.restore)
  899. return monkeyPatch
  900. def flushLoggedErrors(self, *errorTypes):
  901. """
  902. Remove stored errors received from the log.
  903. C{TestCase} stores each error logged during the run of the test and
  904. reports them as errors during the cleanup phase (after C{tearDown}).
  905. @param errorTypes: If unspecified, flush all errors. Otherwise, only
  906. flush errors that match the given types.
  907. @return: A list of failures that have been removed.
  908. """
  909. return self._observer.flushErrors(*errorTypes)
  910. def flushWarnings(self, offendingFunctions=None):
  911. """
  912. Remove stored warnings from the list of captured warnings and return
  913. them.
  914. @param offendingFunctions: If L{None}, all warnings issued during the
  915. currently running test will be flushed. Otherwise, only warnings
  916. which I{point} to a function included in this list will be flushed.
  917. All warnings include a filename and source line number; if these
  918. parts of a warning point to a source line which is part of a
  919. function, then the warning I{points} to that function.
  920. @type offendingFunctions: L{None} or L{list} of functions or methods.
  921. @raise ValueError: If C{offendingFunctions} is not L{None} and includes
  922. an object which is not a L{types.FunctionType} or
  923. L{types.MethodType} instance.
  924. @return: A C{list}, each element of which is a C{dict} giving
  925. information about one warning which was flushed by this call. The
  926. keys of each C{dict} are:
  927. - C{'message'}: The string which was passed as the I{message}
  928. parameter to L{warnings.warn}.
  929. - C{'category'}: The warning subclass which was passed as the
  930. I{category} parameter to L{warnings.warn}.
  931. - C{'filename'}: The name of the file containing the definition
  932. of the code object which was C{stacklevel} frames above the
  933. call to L{warnings.warn}, where C{stacklevel} is the value of
  934. the C{stacklevel} parameter passed to L{warnings.warn}.
  935. - C{'lineno'}: The source line associated with the active
  936. instruction of the code object object which was C{stacklevel}
  937. frames above the call to L{warnings.warn}, where
  938. C{stacklevel} is the value of the C{stacklevel} parameter
  939. passed to L{warnings.warn}.
  940. """
  941. if offendingFunctions is None:
  942. toFlush = self._warnings[:]
  943. self._warnings[:] = []
  944. else:
  945. toFlush = []
  946. for aWarning in self._warnings:
  947. for aFunction in offendingFunctions:
  948. if not isinstance(
  949. aFunction, (types.FunctionType, types.MethodType)
  950. ):
  951. raise ValueError(f"{aFunction!r} is not a function or method")
  952. # inspect.getabsfile(aFunction) sometimes returns a
  953. # filename which disagrees with the filename the warning
  954. # system generates. This seems to be because a
  955. # function's code object doesn't deal with source files
  956. # being renamed. inspect.getabsfile(module) seems
  957. # better (or at least agrees with the warning system
  958. # more often), and does some normalization for us which
  959. # is desirable. inspect.getmodule() is attractive, but
  960. # somewhat broken in Python < 2.6. See Python bug 4845.
  961. aModule = sys.modules[aFunction.__module__]
  962. filename = inspect.getabsfile(aModule)
  963. if filename != os.path.normcase(aWarning.filename):
  964. continue
  965. # In Python 3.13 line numbers returned by findlinestarts
  966. # can be None for bytecode that does not map to source
  967. # lines.
  968. lineNumbers = [
  969. lineNumber
  970. for _, lineNumber in _findlinestarts(aFunction.__code__)
  971. if lineNumber is not None
  972. ]
  973. if not (min(lineNumbers) <= aWarning.lineno <= max(lineNumbers)):
  974. continue
  975. # The warning points to this function, flush it and move on
  976. # to the next warning.
  977. toFlush.append(aWarning)
  978. break
  979. # Remove everything which is being flushed.
  980. list(map(self._warnings.remove, toFlush))
  981. return [
  982. {
  983. "message": w.message,
  984. "category": w.category,
  985. "filename": w.filename,
  986. "lineno": w.lineno,
  987. }
  988. for w in toFlush
  989. ]
  990. def getDeprecatedModuleAttribute(self, moduleName, name, version, message=None):
  991. """
  992. Retrieve a module attribute which should have been deprecated,
  993. and assert that we saw the appropriate deprecation warning.
  994. @type moduleName: C{str}
  995. @param moduleName: Fully-qualified Python name of the module containing
  996. the deprecated attribute; if called from the same module as the
  997. attributes are being deprecated in, using the C{__name__} global can
  998. be helpful
  999. @type name: C{str}
  1000. @param name: Attribute name which we expect to be deprecated
  1001. @param version: The first L{version<twisted.python.versions.Version>} that
  1002. the module attribute was deprecated.
  1003. @type message: C{str}
  1004. @param message: (optional) The expected deprecation message for the module attribute
  1005. @return: The given attribute from the named module
  1006. @raise FailTest: if no warnings were emitted on getattr, or if the
  1007. L{DeprecationWarning} emitted did not produce the canonical
  1008. please-use-something-else message that is standard for Twisted
  1009. deprecations according to the given version and replacement.
  1010. @since: Twisted 21.2.0
  1011. """
  1012. fqpn = moduleName + "." + name
  1013. module = sys.modules[moduleName]
  1014. attr = getattr(module, name)
  1015. warningsShown = self.flushWarnings([self.getDeprecatedModuleAttribute])
  1016. if len(warningsShown) == 0:
  1017. self.fail(f"{fqpn} is not deprecated.")
  1018. observedWarning = warningsShown[0]["message"]
  1019. expectedWarning = DEPRECATION_WARNING_FORMAT % {
  1020. "fqpn": fqpn,
  1021. "version": getVersionString(version),
  1022. }
  1023. if message is not None:
  1024. expectedWarning = expectedWarning + ": " + message
  1025. self.assert_(
  1026. observedWarning.startswith(expectedWarning),
  1027. f"Expected {observedWarning!r} to start with {expectedWarning!r}",
  1028. )
  1029. return attr
  1030. def callDeprecated(self, version, f, *args, **kwargs):
  1031. """
  1032. Call a function that should have been deprecated at a specific version
  1033. and in favor of a specific alternative, and assert that it was thusly
  1034. deprecated.
  1035. @param version: A 2-sequence of (since, replacement), where C{since} is
  1036. a the first L{version<incremental.Version>} that C{f}
  1037. should have been deprecated since, and C{replacement} is a suggested
  1038. replacement for the deprecated functionality, as described by
  1039. L{twisted.python.deprecate.deprecated}. If there is no suggested
  1040. replacement, this parameter may also be simply a
  1041. L{version<incremental.Version>} by itself.
  1042. @param f: The deprecated function to call.
  1043. @param args: The arguments to pass to C{f}.
  1044. @param kwargs: The keyword arguments to pass to C{f}.
  1045. @return: Whatever C{f} returns.
  1046. @raise Exception: Whatever C{f} raises. If any exception is
  1047. raised by C{f}, though, no assertions will be made about emitted
  1048. deprecations.
  1049. @raise FailTest: if no warnings were emitted by C{f}, or if the
  1050. L{DeprecationWarning} emitted did not produce the canonical
  1051. please-use-something-else message that is standard for Twisted
  1052. deprecations according to the given version and replacement.
  1053. """
  1054. result = f(*args, **kwargs)
  1055. warningsShown = self.flushWarnings([self.callDeprecated])
  1056. try:
  1057. info = list(version)
  1058. except TypeError:
  1059. since = version
  1060. replacement = None
  1061. else:
  1062. [since, replacement] = info
  1063. if len(warningsShown) == 0:
  1064. self.fail(f"{f!r} is not deprecated.")
  1065. observedWarning = warningsShown[0]["message"]
  1066. expectedWarning = getDeprecationWarningString(f, since, replacement=replacement)
  1067. self.assertEqual(expectedWarning, observedWarning)
  1068. return result
  1069. def mktemp(self):
  1070. """
  1071. Create a new path name which can be used for a new file or directory.
  1072. The result is a relative path that is guaranteed to be unique within the
  1073. current working directory. The parent of the path will exist, but the
  1074. path will not.
  1075. For a temporary directory call os.mkdir on the path. For a temporary
  1076. file just create the file (e.g. by opening the path for writing and then
  1077. closing it).
  1078. @return: The newly created path
  1079. @rtype: C{str}
  1080. """
  1081. MAX_FILENAME = 32 # some platforms limit lengths of filenames
  1082. base = os.path.join(
  1083. self.__class__.__module__[:MAX_FILENAME],
  1084. self.__class__.__name__[:MAX_FILENAME],
  1085. self._testMethodName[:MAX_FILENAME],
  1086. )
  1087. if not os.path.exists(base):
  1088. os.makedirs(base)
  1089. # With 3.11 or older mkdtemp returns a relative path.
  1090. # With newer it is absolute.
  1091. # Here we make sure we always handle a relative path.
  1092. # See https://github.com/python/cpython/issues/51574
  1093. dirname = os.path.relpath(tempfile.mkdtemp("", "", base))
  1094. return os.path.join(dirname, "temp")
  1095. def _getSuppress(self):
  1096. """
  1097. Returns any warning suppressions set for this test. Checks on the
  1098. instance first, then the class, then the module, then packages. As
  1099. soon as it finds something with a C{suppress} attribute, returns that.
  1100. Returns any empty list (i.e. suppress no warnings) if it cannot find
  1101. anything. See L{TestCase} docstring for more details.
  1102. """
  1103. return util.acquireAttribute(self._parents, "suppress", [])
  1104. def _getSkipReason(self, method, skip):
  1105. """
  1106. Return the reason to use for skipping a test method.
  1107. @param method: The method which produced the skip.
  1108. @param skip: A L{unittest.SkipTest} instance raised by C{method}.
  1109. """
  1110. if len(skip.args) > 0:
  1111. return skip.args[0]
  1112. warnAboutFunction(
  1113. method,
  1114. "Do not raise unittest.SkipTest with no arguments! Give a reason "
  1115. "for skipping tests!",
  1116. )
  1117. return skip
  1118. def _run(self, suppress, todo, method, result):
  1119. """
  1120. Run a single method, either a test method or fixture.
  1121. @param suppress: Any warnings to suppress, as defined by the C{suppress}
  1122. attribute on this method, test case, or the module it is defined in.
  1123. @param todo: Any expected failure or failures, as defined by the C{todo}
  1124. attribute on this method, test case, or the module it is defined in.
  1125. @param method: The method to run.
  1126. @param result: The TestResult instance to which to report results.
  1127. @return: C{True} if the method fails and no further method/fixture calls
  1128. should be made, C{False} otherwise.
  1129. """
  1130. if inspect.isgeneratorfunction(method):
  1131. exc = TypeError(
  1132. "{!r} is a generator function and therefore will never run".format(
  1133. method
  1134. )
  1135. )
  1136. result.addError(self, failure.Failure(exc))
  1137. return True
  1138. try:
  1139. runWithWarningsSuppressed(suppress, method)
  1140. except SkipTest as e:
  1141. result.addSkip(self, self._getSkipReason(method, e))
  1142. except BaseException:
  1143. reason = failure.Failure()
  1144. if todo is None or not todo.expected(reason):
  1145. if reason.check(self.failureException):
  1146. addResult = result.addFailure
  1147. else:
  1148. addResult = result.addError
  1149. addResult(self, reason)
  1150. else:
  1151. result.addExpectedFailure(self, reason, todo)
  1152. else:
  1153. return False
  1154. return True
  1155. def _runFixturesAndTest(self, result):
  1156. """
  1157. Run C{setUp}, a test method, test cleanups, and C{tearDown}.
  1158. @param result: The TestResult instance to which to report results.
  1159. """
  1160. suppress = self._getSuppress()
  1161. try:
  1162. if self._run(suppress, None, self.setUp, result):
  1163. return
  1164. todo = self.getTodo()
  1165. method = getattr(self, self._testMethodName)
  1166. failed = self._run(suppress, todo, method, result)
  1167. finally:
  1168. self._runCleanups(result)
  1169. if todo and not failed:
  1170. result.addUnexpectedSuccess(self, todo)
  1171. if self._run(suppress, None, self.tearDown, result):
  1172. failed = True
  1173. for error in self._observer.getErrors():
  1174. result.addError(self, error)
  1175. failed = True
  1176. self._observer.flushErrors()
  1177. self._removeObserver()
  1178. if not (failed or todo):
  1179. result.addSuccess(self)
  1180. def _runCleanups(self, result):
  1181. """
  1182. Synchronously run any cleanups which have been added.
  1183. """
  1184. while len(self._cleanups) > 0:
  1185. f, args, kwargs = self._cleanups.pop()
  1186. try:
  1187. f(*args, **kwargs)
  1188. except BaseException:
  1189. f = failure.Failure()
  1190. result.addError(self, f)
  1191. def _installObserver(self):
  1192. self._observer = _logObserver
  1193. self._observer._add()
  1194. def _removeObserver(self):
  1195. self._observer._remove()