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 49KB

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