_synctest.py 49 KB

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