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.

_synctest.py 52KB

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