reporter.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. # -*- test-case-name: twisted.trial.test.test_reporter -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. #
  5. # Maintainer: Jonathan Lange
  6. """
  7. Defines classes that handle the results of tests.
  8. """
  9. from __future__ import division, absolute_import
  10. import sys
  11. import os
  12. import time
  13. import warnings
  14. import unittest as pyunit
  15. from collections import OrderedDict
  16. from zope.interface import implementer
  17. from twisted.python import reflect, log
  18. from twisted.python.components import proxyForInterface
  19. from twisted.python.failure import Failure
  20. from twisted.python.util import untilConcludes
  21. from twisted.python.compat import _PY3, items
  22. from twisted.trial import itrial, util
  23. from twisted.trial.unittest import makeTodo
  24. try:
  25. from subunit import TestProtocolClient
  26. except ImportError:
  27. TestProtocolClient = None
  28. class BrokenTestCaseWarning(Warning):
  29. """
  30. Emitted as a warning when an exception occurs in one of setUp or tearDown.
  31. """
  32. class SafeStream(object):
  33. """
  34. Wraps a stream object so that all C{write} calls are wrapped in
  35. L{untilConcludes<twisted.python.util.untilConcludes>}.
  36. """
  37. def __init__(self, original):
  38. self.original = original
  39. def __getattr__(self, name):
  40. return getattr(self.original, name)
  41. def write(self, *a, **kw):
  42. return untilConcludes(self.original.write, *a, **kw)
  43. @implementer(itrial.IReporter)
  44. class TestResult(pyunit.TestResult, object):
  45. """
  46. Accumulates the results of several L{twisted.trial.unittest.TestCase}s.
  47. @ivar successes: count the number of successes achieved by the test run.
  48. @type successes: C{int}
  49. """
  50. # Used when no todo provided to addExpectedFailure or addUnexpectedSuccess.
  51. _DEFAULT_TODO = 'Test expected to fail'
  52. def __init__(self):
  53. super(TestResult, self).__init__()
  54. self.skips = []
  55. self.expectedFailures = []
  56. self.unexpectedSuccesses = []
  57. self.successes = 0
  58. self._timings = []
  59. def __repr__(self):
  60. return ('<%s run=%d errors=%d failures=%d todos=%d dones=%d skips=%d>'
  61. % (reflect.qual(self.__class__), self.testsRun,
  62. len(self.errors), len(self.failures),
  63. len(self.expectedFailures), len(self.skips),
  64. len(self.unexpectedSuccesses)))
  65. def _getTime(self):
  66. return time.time()
  67. def _getFailure(self, error):
  68. """
  69. Convert a C{sys.exc_info()}-style tuple to a L{Failure}, if necessary.
  70. """
  71. if isinstance(error, tuple):
  72. return Failure(error[1], error[0], error[2])
  73. return error
  74. def startTest(self, test):
  75. """
  76. This must be called before the given test is commenced.
  77. @type test: L{pyunit.TestCase}
  78. """
  79. super(TestResult, self).startTest(test)
  80. self._testStarted = self._getTime()
  81. def stopTest(self, test):
  82. """
  83. This must be called after the given test is completed.
  84. @type test: L{pyunit.TestCase}
  85. """
  86. super(TestResult, self).stopTest(test)
  87. self._lastTime = self._getTime() - self._testStarted
  88. def addFailure(self, test, fail):
  89. """
  90. Report a failed assertion for the given test.
  91. @type test: L{pyunit.TestCase}
  92. @type fail: L{Failure} or L{tuple}
  93. """
  94. self.failures.append((test, self._getFailure(fail)))
  95. def addError(self, test, error):
  96. """
  97. Report an error that occurred while running the given test.
  98. @type test: L{pyunit.TestCase}
  99. @type error: L{Failure} or L{tuple}
  100. """
  101. self.errors.append((test, self._getFailure(error)))
  102. def addSkip(self, test, reason):
  103. """
  104. Report that the given test was skipped.
  105. In Trial, tests can be 'skipped'. Tests are skipped mostly because
  106. there is some platform or configuration issue that prevents them from
  107. being run correctly.
  108. @type test: L{pyunit.TestCase}
  109. @type reason: L{str}
  110. """
  111. self.skips.append((test, reason))
  112. def addUnexpectedSuccess(self, test, todo=None):
  113. """
  114. Report that the given test succeeded against expectations.
  115. In Trial, tests can be marked 'todo'. That is, they are expected to
  116. fail. When a test that is expected to fail instead succeeds, it should
  117. call this method to report the unexpected success.
  118. @type test: L{pyunit.TestCase}
  119. @type todo: L{unittest.Todo}, or L{None}, in which case a default todo
  120. message is provided.
  121. """
  122. if todo is None:
  123. todo = makeTodo(self._DEFAULT_TODO)
  124. self.unexpectedSuccesses.append((test, todo))
  125. def addExpectedFailure(self, test, error, todo=None):
  126. """
  127. Report that the given test failed, and was expected to do so.
  128. In Trial, tests can be marked 'todo'. That is, they are expected to
  129. fail.
  130. @type test: L{pyunit.TestCase}
  131. @type error: L{Failure}
  132. @type todo: L{unittest.Todo}, or L{None}, in which case a default todo
  133. message is provided.
  134. """
  135. if todo is None:
  136. todo = makeTodo(self._DEFAULT_TODO)
  137. self.expectedFailures.append((test, error, todo))
  138. def addSuccess(self, test):
  139. """
  140. Report that the given test succeeded.
  141. @type test: L{pyunit.TestCase}
  142. """
  143. self.successes += 1
  144. def wasSuccessful(self):
  145. """
  146. Report whether or not this test suite was successful or not.
  147. The behaviour of this method changed in L{pyunit} in Python 3.4 to
  148. fail if there are any errors, failures, or unexpected successes.
  149. Previous to 3.4, it was only if there were errors or failures. This
  150. method implements the old behaviour for backwards compatibility reasons,
  151. checking just for errors and failures.
  152. @rtype: L{bool}
  153. """
  154. return len(self.failures) == len(self.errors) == 0
  155. def done(self):
  156. """
  157. The test suite has finished running.
  158. """
  159. @implementer(itrial.IReporter)
  160. class TestResultDecorator(proxyForInterface(itrial.IReporter,
  161. "_originalReporter")):
  162. """
  163. Base class for TestResult decorators.
  164. @ivar _originalReporter: The wrapped instance of reporter.
  165. @type _originalReporter: A provider of L{itrial.IReporter}
  166. """
  167. @implementer(itrial.IReporter)
  168. class UncleanWarningsReporterWrapper(TestResultDecorator):
  169. """
  170. A wrapper for a reporter that converts L{util.DirtyReactorAggregateError}s
  171. to warnings.
  172. """
  173. def addError(self, test, error):
  174. """
  175. If the error is a L{util.DirtyReactorAggregateError}, instead of
  176. reporting it as a normal error, throw a warning.
  177. """
  178. if (isinstance(error, Failure)
  179. and error.check(util.DirtyReactorAggregateError)):
  180. warnings.warn(error.getErrorMessage())
  181. else:
  182. self._originalReporter.addError(test, error)
  183. @implementer(itrial.IReporter)
  184. class _ExitWrapper(TestResultDecorator):
  185. """
  186. A wrapper for a reporter that causes the reporter to stop after
  187. unsuccessful tests.
  188. """
  189. def addError(self, *args, **kwargs):
  190. self.shouldStop = True
  191. return self._originalReporter.addError(*args, **kwargs)
  192. def addFailure(self, *args, **kwargs):
  193. self.shouldStop = True
  194. return self._originalReporter.addFailure(*args, **kwargs)
  195. class _AdaptedReporter(TestResultDecorator):
  196. """
  197. TestResult decorator that makes sure that addError only gets tests that
  198. have been adapted with a particular test adapter.
  199. """
  200. def __init__(self, original, testAdapter):
  201. """
  202. Construct an L{_AdaptedReporter}.
  203. @param original: An {itrial.IReporter}.
  204. @param testAdapter: A callable that returns an L{itrial.ITestCase}.
  205. """
  206. TestResultDecorator.__init__(self, original)
  207. self.testAdapter = testAdapter
  208. def addError(self, test, error):
  209. """
  210. See L{itrial.IReporter}.
  211. """
  212. test = self.testAdapter(test)
  213. return self._originalReporter.addError(test, error)
  214. def addExpectedFailure(self, test, failure, todo=None):
  215. """
  216. See L{itrial.IReporter}.
  217. @type test: A L{pyunit.TestCase}.
  218. @type failure: A L{failure.Failure} or L{exceptions.AssertionError}
  219. @type todo: A L{unittest.Todo} or None
  220. When C{todo} is L{None} a generic C{unittest.Todo} is built.
  221. L{pyunit.TestCase}'s C{run()} calls this with 3 positional arguments
  222. (without C{todo}).
  223. """
  224. return self._originalReporter.addExpectedFailure(
  225. self.testAdapter(test), failure, todo)
  226. def addFailure(self, test, failure):
  227. """
  228. See L{itrial.IReporter}.
  229. """
  230. test = self.testAdapter(test)
  231. return self._originalReporter.addFailure(test, failure)
  232. def addSkip(self, test, skip):
  233. """
  234. See L{itrial.IReporter}.
  235. """
  236. test = self.testAdapter(test)
  237. return self._originalReporter.addSkip(test, skip)
  238. def addUnexpectedSuccess(self, test, todo=None):
  239. """
  240. See L{itrial.IReporter}.
  241. @type test: A L{pyunit.TestCase}.
  242. @type todo: A L{unittest.Todo} or None
  243. When C{todo} is L{None} a generic C{unittest.Todo} is built.
  244. L{pyunit.TestCase}'s C{run()} calls this with 2 positional arguments
  245. (without C{todo}).
  246. """
  247. test = self.testAdapter(test)
  248. return self._originalReporter.addUnexpectedSuccess(test, todo)
  249. def startTest(self, test):
  250. """
  251. See L{itrial.IReporter}.
  252. """
  253. return self._originalReporter.startTest(self.testAdapter(test))
  254. def stopTest(self, test):
  255. """
  256. See L{itrial.IReporter}.
  257. """
  258. return self._originalReporter.stopTest(self.testAdapter(test))
  259. @implementer(itrial.IReporter)
  260. class Reporter(TestResult):
  261. """
  262. A basic L{TestResult} with support for writing to a stream.
  263. @ivar _startTime: The time when the first test was started. It defaults to
  264. L{None}, which means that no test was actually launched.
  265. @type _startTime: C{float} or L{None}
  266. @ivar _warningCache: A C{set} of tuples of warning message (file, line,
  267. text, category) which have already been written to the output stream
  268. during the currently executing test. This is used to avoid writing
  269. duplicates of the same warning to the output stream.
  270. @type _warningCache: C{set}
  271. @ivar _publisher: The log publisher which will be observed for warning
  272. events.
  273. @type _publisher: L{twisted.python.log.LogPublisher}
  274. """
  275. _separator = '-' * 79
  276. _doubleSeparator = '=' * 79
  277. def __init__(self, stream=sys.stdout, tbformat='default', realtime=False,
  278. publisher=None):
  279. super(Reporter, self).__init__()
  280. self._stream = SafeStream(stream)
  281. self.tbformat = tbformat
  282. self.realtime = realtime
  283. self._startTime = None
  284. self._warningCache = set()
  285. # Start observing log events so as to be able to report warnings.
  286. self._publisher = publisher
  287. if publisher is not None:
  288. publisher.addObserver(self._observeWarnings)
  289. def _observeWarnings(self, event):
  290. """
  291. Observe warning events and write them to C{self._stream}.
  292. This method is a log observer which will be registered with
  293. C{self._publisher.addObserver}.
  294. @param event: A C{dict} from the logging system. If it has a
  295. C{'warning'} key, a logged warning will be extracted from it and
  296. possibly written to C{self.stream}.
  297. """
  298. if 'warning' in event:
  299. key = (event['filename'], event['lineno'],
  300. event['category'].split('.')[-1],
  301. str(event['warning']))
  302. if key not in self._warningCache:
  303. self._warningCache.add(key)
  304. self._stream.write('%s:%s: %s: %s\n' % key)
  305. def startTest(self, test):
  306. """
  307. Called when a test begins to run. Records the time when it was first
  308. called and resets the warning cache.
  309. @param test: L{ITestCase}
  310. """
  311. super(Reporter, self).startTest(test)
  312. if self._startTime is None:
  313. self._startTime = self._getTime()
  314. self._warningCache = set()
  315. def addFailure(self, test, fail):
  316. """
  317. Called when a test fails. If C{realtime} is set, then it prints the
  318. error to the stream.
  319. @param test: L{ITestCase} that failed.
  320. @param fail: L{failure.Failure} containing the error.
  321. """
  322. super(Reporter, self).addFailure(test, fail)
  323. if self.realtime:
  324. fail = self.failures[-1][1] # guarantee it's a Failure
  325. self._write(self._formatFailureTraceback(fail))
  326. def addError(self, test, error):
  327. """
  328. Called when a test raises an error. If C{realtime} is set, then it
  329. prints the error to the stream.
  330. @param test: L{ITestCase} that raised the error.
  331. @param error: L{failure.Failure} containing the error.
  332. """
  333. error = self._getFailure(error)
  334. super(Reporter, self).addError(test, error)
  335. if self.realtime:
  336. error = self.errors[-1][1] # guarantee it's a Failure
  337. self._write(self._formatFailureTraceback(error))
  338. def _write(self, format, *args):
  339. """
  340. Safely write to the reporter's stream.
  341. @param format: A format string to write.
  342. @param *args: The arguments for the format string.
  343. """
  344. s = str(format)
  345. assert isinstance(s, type(''))
  346. if args:
  347. self._stream.write(s % args)
  348. else:
  349. self._stream.write(s)
  350. untilConcludes(self._stream.flush)
  351. def _writeln(self, format, *args):
  352. """
  353. Safely write a line to the reporter's stream. Newline is appended to
  354. the format string.
  355. @param format: A format string to write.
  356. @param *args: The arguments for the format string.
  357. """
  358. self._write(format, *args)
  359. self._write('\n')
  360. def upDownError(self, method, error, warn, printStatus):
  361. super(Reporter, self).upDownError(method, error, warn, printStatus)
  362. if warn:
  363. tbStr = self._formatFailureTraceback(error)
  364. log.msg(tbStr)
  365. msg = ("caught exception in %s, your TestCase is broken\n\n%s"
  366. % (method, tbStr))
  367. warnings.warn(msg, BrokenTestCaseWarning, stacklevel=2)
  368. def cleanupErrors(self, errs):
  369. super(Reporter, self).cleanupErrors(errs)
  370. warnings.warn("%s\n%s" % ("REACTOR UNCLEAN! traceback(s) follow: ",
  371. self._formatFailureTraceback(errs)),
  372. BrokenTestCaseWarning)
  373. def _trimFrames(self, frames):
  374. """
  375. Trim frames to remove internal paths.
  376. When a C{SynchronousTestCase} method fails synchronously, the stack
  377. looks like this:
  378. - [0]: C{SynchronousTestCase._run}
  379. - [1]: C{util.runWithWarningsSuppressed}
  380. - [2:-2]: code in the test method which failed
  381. - [-1]: C{_synctest.fail}
  382. When a C{TestCase} method fails synchronously, the stack looks like
  383. this:
  384. - [0]: C{defer.maybeDeferred}
  385. - [1]: C{utils.runWithWarningsSuppressed}
  386. - [2]: C{utils.runWithWarningsSuppressed}
  387. - [3:-2]: code in the test method which failed
  388. - [-1]: C{_synctest.fail}
  389. When a method fails inside a C{Deferred} (i.e., when the test method
  390. returns a C{Deferred}, and that C{Deferred}'s errback fires), the stack
  391. captured inside the resulting C{Failure} looks like this:
  392. - [0]: C{defer.Deferred._runCallbacks}
  393. - [1:-2]: code in the testmethod which failed
  394. - [-1]: C{_synctest.fail}
  395. As a result, we want to trim either [maybeDeferred, runWWS, runWWS] or
  396. [Deferred._runCallbacks] or [SynchronousTestCase._run, runWWS] from the
  397. front, and trim the [unittest.fail] from the end.
  398. There is also another case, when the test method is badly defined and
  399. contains extra arguments.
  400. If it doesn't recognize one of these cases, it just returns the
  401. original frames.
  402. @param frames: The C{list} of frames from the test failure.
  403. @return: The C{list} of frames to display.
  404. """
  405. newFrames = list(frames)
  406. if len(frames) < 2:
  407. return newFrames
  408. firstMethod = newFrames[0][0]
  409. firstFile = os.path.splitext(os.path.basename(newFrames[0][1]))[0]
  410. secondMethod = newFrames[1][0]
  411. secondFile = os.path.splitext(os.path.basename(newFrames[1][1]))[0]
  412. syncCase = (("_run", "_synctest"),
  413. ("runWithWarningsSuppressed", "util"))
  414. asyncCase = (("maybeDeferred", "defer"),
  415. ("runWithWarningsSuppressed", "utils"))
  416. twoFrames = ((firstMethod, firstFile), (secondMethod, secondFile))
  417. if _PY3:
  418. # On PY3, we have an extra frame which is reraising the exception
  419. for frame in newFrames:
  420. frameFile = os.path.splitext(os.path.basename(frame[1]))[0]
  421. if frameFile == "compat" and frame[0] == "reraise":
  422. # If it's in the compat module and is reraise, BLAM IT
  423. newFrames.pop(newFrames.index(frame))
  424. if twoFrames == syncCase:
  425. newFrames = newFrames[2:]
  426. elif twoFrames == asyncCase:
  427. newFrames = newFrames[3:]
  428. elif (firstMethod, firstFile) == ("_runCallbacks", "defer"):
  429. newFrames = newFrames[1:]
  430. if not newFrames:
  431. # The method fails before getting called, probably an argument
  432. # problem
  433. return newFrames
  434. last = newFrames[-1]
  435. if (last[0].startswith('fail')
  436. and os.path.splitext(os.path.basename(last[1]))[0] == '_synctest'):
  437. newFrames = newFrames[:-1]
  438. return newFrames
  439. def _formatFailureTraceback(self, fail):
  440. if isinstance(fail, str):
  441. return fail.rstrip() + '\n'
  442. fail.frames, frames = self._trimFrames(fail.frames), fail.frames
  443. result = fail.getTraceback(detail=self.tbformat,
  444. elideFrameworkCode=True)
  445. fail.frames = frames
  446. return result
  447. def _groupResults(self, results, formatter):
  448. """
  449. Group tests together based on their results.
  450. @param results: An iterable of tuples of two or more elements. The
  451. first element of each tuple is a test case. The remaining
  452. elements describe the outcome of that test case.
  453. @param formatter: A callable which turns a test case result into a
  454. string. The elements after the first of the tuples in
  455. C{results} will be passed as positional arguments to
  456. C{formatter}.
  457. @return: A C{list} of two-tuples. The first element of each tuple
  458. is a unique string describing one result from at least one of
  459. the test cases in C{results}. The second element is a list of
  460. the test cases which had that result.
  461. """
  462. groups = OrderedDict()
  463. for content in results:
  464. case = content[0]
  465. outcome = content[1:]
  466. key = formatter(*outcome)
  467. groups.setdefault(key, []).append(case)
  468. return items(groups)
  469. def _printResults(self, flavor, errors, formatter):
  470. """
  471. Print a group of errors to the stream.
  472. @param flavor: A string indicating the kind of error (e.g. 'TODO').
  473. @param errors: A list of errors, often L{failure.Failure}s, but
  474. sometimes 'todo' errors.
  475. @param formatter: A callable that knows how to format the errors.
  476. """
  477. for reason, cases in self._groupResults(errors, formatter):
  478. self._writeln(self._doubleSeparator)
  479. self._writeln(flavor)
  480. self._write(reason)
  481. self._writeln('')
  482. for case in cases:
  483. self._writeln(case.id())
  484. def _printExpectedFailure(self, error, todo):
  485. return 'Reason: %r\n%s' % (todo.reason,
  486. self._formatFailureTraceback(error))
  487. def _printUnexpectedSuccess(self, todo):
  488. ret = 'Reason: %r\n' % (todo.reason,)
  489. if todo.errors:
  490. ret += 'Expected errors: %s\n' % (', '.join(todo.errors),)
  491. return ret
  492. def _printErrors(self):
  493. """
  494. Print all of the non-success results to the stream in full.
  495. """
  496. self._write('\n')
  497. self._printResults('[SKIPPED]', self.skips, lambda x: '%s\n' % x)
  498. self._printResults('[TODO]', self.expectedFailures,
  499. self._printExpectedFailure)
  500. self._printResults('[FAIL]', self.failures,
  501. self._formatFailureTraceback)
  502. self._printResults('[ERROR]', self.errors,
  503. self._formatFailureTraceback)
  504. self._printResults('[SUCCESS!?!]', self.unexpectedSuccesses,
  505. self._printUnexpectedSuccess)
  506. def _getSummary(self):
  507. """
  508. Return a formatted count of tests status results.
  509. """
  510. summaries = []
  511. for stat in ("skips", "expectedFailures", "failures", "errors",
  512. "unexpectedSuccesses"):
  513. num = len(getattr(self, stat))
  514. if num:
  515. summaries.append('%s=%d' % (stat, num))
  516. if self.successes:
  517. summaries.append('successes=%d' % (self.successes,))
  518. summary = (summaries and ' (' + ', '.join(summaries) + ')') or ''
  519. return summary
  520. def _printSummary(self):
  521. """
  522. Print a line summarising the test results to the stream.
  523. """
  524. summary = self._getSummary()
  525. if self.wasSuccessful():
  526. status = "PASSED"
  527. else:
  528. status = "FAILED"
  529. self._write("%s%s\n", status, summary)
  530. def done(self):
  531. """
  532. Summarize the result of the test run.
  533. The summary includes a report of all of the errors, todos, skips and
  534. so forth that occurred during the run. It also includes the number of
  535. tests that were run and how long it took to run them (not including
  536. load time).
  537. Expects that C{_printErrors}, C{_writeln}, C{_write}, C{_printSummary}
  538. and C{_separator} are all implemented.
  539. """
  540. if self._publisher is not None:
  541. self._publisher.removeObserver(self._observeWarnings)
  542. self._printErrors()
  543. self._writeln(self._separator)
  544. if self._startTime is not None:
  545. self._writeln('Ran %d tests in %.3fs', self.testsRun,
  546. time.time() - self._startTime)
  547. self._write('\n')
  548. self._printSummary()
  549. class MinimalReporter(Reporter):
  550. """
  551. A minimalist reporter that prints only a summary of the test result, in
  552. the form of (timeTaken, #tests, #tests, #errors, #failures, #skips).
  553. """
  554. def _printErrors(self):
  555. """
  556. Don't print a detailed summary of errors. We only care about the
  557. counts.
  558. """
  559. def _printSummary(self):
  560. """
  561. Print out a one-line summary of the form:
  562. '%(runtime) %(number_of_tests) %(number_of_tests) %(num_errors)
  563. %(num_failures) %(num_skips)'
  564. """
  565. numTests = self.testsRun
  566. if self._startTime is not None:
  567. timing = self._getTime() - self._startTime
  568. else:
  569. timing = 0
  570. t = (timing, numTests, numTests,
  571. len(self.errors), len(self.failures), len(self.skips))
  572. self._writeln(' '.join(map(str, t)))
  573. class TextReporter(Reporter):
  574. """
  575. Simple reporter that prints a single character for each test as it runs,
  576. along with the standard Trial summary text.
  577. """
  578. def addSuccess(self, test):
  579. super(TextReporter, self).addSuccess(test)
  580. self._write('.')
  581. def addError(self, *args):
  582. super(TextReporter, self).addError(*args)
  583. self._write('E')
  584. def addFailure(self, *args):
  585. super(TextReporter, self).addFailure(*args)
  586. self._write('F')
  587. def addSkip(self, *args):
  588. super(TextReporter, self).addSkip(*args)
  589. self._write('S')
  590. def addExpectedFailure(self, *args):
  591. super(TextReporter, self).addExpectedFailure(*args)
  592. self._write('T')
  593. def addUnexpectedSuccess(self, *args):
  594. super(TextReporter, self).addUnexpectedSuccess(*args)
  595. self._write('!')
  596. class VerboseTextReporter(Reporter):
  597. """
  598. A verbose reporter that prints the name of each test as it is running.
  599. Each line is printed with the name of the test, followed by the result of
  600. that test.
  601. """
  602. # This is actually the bwverbose option
  603. def startTest(self, tm):
  604. self._write('%s ... ', tm.id())
  605. super(VerboseTextReporter, self).startTest(tm)
  606. def addSuccess(self, test):
  607. super(VerboseTextReporter, self).addSuccess(test)
  608. self._write('[OK]')
  609. def addError(self, *args):
  610. super(VerboseTextReporter, self).addError(*args)
  611. self._write('[ERROR]')
  612. def addFailure(self, *args):
  613. super(VerboseTextReporter, self).addFailure(*args)
  614. self._write('[FAILURE]')
  615. def addSkip(self, *args):
  616. super(VerboseTextReporter, self).addSkip(*args)
  617. self._write('[SKIPPED]')
  618. def addExpectedFailure(self, *args):
  619. super(VerboseTextReporter, self).addExpectedFailure(*args)
  620. self._write('[TODO]')
  621. def addUnexpectedSuccess(self, *args):
  622. super(VerboseTextReporter, self).addUnexpectedSuccess(*args)
  623. self._write('[SUCCESS!?!]')
  624. def stopTest(self, test):
  625. super(VerboseTextReporter, self).stopTest(test)
  626. self._write('\n')
  627. class TimingTextReporter(VerboseTextReporter):
  628. """
  629. Prints out each test as it is running, followed by the time taken for each
  630. test to run.
  631. """
  632. def stopTest(self, method):
  633. """
  634. Mark the test as stopped, and write the time it took to run the test
  635. to the stream.
  636. """
  637. super(TimingTextReporter, self).stopTest(method)
  638. self._write("(%.03f secs)\n" % self._lastTime)
  639. class _AnsiColorizer(object):
  640. """
  641. A colorizer is an object that loosely wraps around a stream, allowing
  642. callers to write text to the stream in a particular color.
  643. Colorizer classes must implement C{supported()} and C{write(text, color)}.
  644. """
  645. _colors = dict(black=30, red=31, green=32, yellow=33,
  646. blue=34, magenta=35, cyan=36, white=37)
  647. def __init__(self, stream):
  648. self.stream = stream
  649. def supported(cls, stream=sys.stdout):
  650. """
  651. A class method that returns True if the current platform supports
  652. coloring terminal output using this method. Returns False otherwise.
  653. """
  654. if not stream.isatty():
  655. return False # auto color only on TTYs
  656. try:
  657. import curses
  658. except ImportError:
  659. return False
  660. else:
  661. try:
  662. try:
  663. return curses.tigetnum("colors") > 2
  664. except curses.error:
  665. curses.setupterm()
  666. return curses.tigetnum("colors") > 2
  667. except:
  668. # guess false in case of error
  669. return False
  670. supported = classmethod(supported)
  671. def write(self, text, color):
  672. """
  673. Write the given text to the stream in the given color.
  674. @param text: Text to be written to the stream.
  675. @param color: A string label for a color. e.g. 'red', 'white'.
  676. """
  677. color = self._colors[color]
  678. self.stream.write('\x1b[%s;1m%s\x1b[0m' % (color, text))
  679. class _Win32Colorizer(object):
  680. """
  681. See _AnsiColorizer docstring.
  682. """
  683. def __init__(self, stream):
  684. from win32console import GetStdHandle, STD_OUTPUT_HANDLE, \
  685. FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
  686. FOREGROUND_INTENSITY
  687. red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
  688. FOREGROUND_BLUE, FOREGROUND_INTENSITY)
  689. self.stream = stream
  690. self.screenBuffer = GetStdHandle(STD_OUTPUT_HANDLE)
  691. self._colors = {
  692. 'normal': red | green | blue,
  693. 'red': red | bold,
  694. 'green': green | bold,
  695. 'blue': blue | bold,
  696. 'yellow': red | green | bold,
  697. 'magenta': red | blue | bold,
  698. 'cyan': green | blue | bold,
  699. 'white': red | green | blue | bold
  700. }
  701. def supported(cls, stream=sys.stdout):
  702. try:
  703. import win32console
  704. screenBuffer = win32console.GetStdHandle(
  705. win32console.STD_OUTPUT_HANDLE)
  706. except ImportError:
  707. return False
  708. import pywintypes
  709. try:
  710. screenBuffer.SetConsoleTextAttribute(
  711. win32console.FOREGROUND_RED |
  712. win32console.FOREGROUND_GREEN |
  713. win32console.FOREGROUND_BLUE)
  714. except pywintypes.error:
  715. return False
  716. else:
  717. return True
  718. supported = classmethod(supported)
  719. def write(self, text, color):
  720. color = self._colors[color]
  721. self.screenBuffer.SetConsoleTextAttribute(color)
  722. self.stream.write(text)
  723. self.screenBuffer.SetConsoleTextAttribute(self._colors['normal'])
  724. class _NullColorizer(object):
  725. """
  726. See _AnsiColorizer docstring.
  727. """
  728. def __init__(self, stream):
  729. self.stream = stream
  730. def supported(cls, stream=sys.stdout):
  731. return True
  732. supported = classmethod(supported)
  733. def write(self, text, color):
  734. self.stream.write(text)
  735. @implementer(itrial.IReporter)
  736. class SubunitReporter(object):
  737. """
  738. Reports test output via Subunit.
  739. @ivar _subunit: The subunit protocol client that we are wrapping.
  740. @ivar _successful: An internal variable, used to track whether we have
  741. received only successful results.
  742. @since: 10.0
  743. """
  744. def __init__(self, stream=sys.stdout, tbformat='default',
  745. realtime=False, publisher=None):
  746. """
  747. Construct a L{SubunitReporter}.
  748. @param stream: A file-like object representing the stream to print
  749. output to. Defaults to stdout.
  750. @param tbformat: The format for tracebacks. Ignored, since subunit
  751. always uses Python's standard format.
  752. @param realtime: Whether or not to print exceptions in the middle
  753. of the test results. Ignored, since subunit always does this.
  754. @param publisher: The log publisher which will be preserved for
  755. reporting events. Ignored, as it's not relevant to subunit.
  756. """
  757. if TestProtocolClient is None:
  758. raise Exception("Subunit not available")
  759. self._subunit = TestProtocolClient(stream)
  760. self._successful = True
  761. def done(self):
  762. """
  763. Record that the entire test suite run is finished.
  764. We do nothing, since a summary clause is irrelevant to the subunit
  765. protocol.
  766. """
  767. pass
  768. def shouldStop(self):
  769. """
  770. Whether or not the test runner should stop running tests.
  771. """
  772. return self._subunit.shouldStop
  773. shouldStop = property(shouldStop)
  774. def stop(self):
  775. """
  776. Signal that the test runner should stop running tests.
  777. """
  778. return self._subunit.stop()
  779. def wasSuccessful(self):
  780. """
  781. Has the test run been successful so far?
  782. @return: C{True} if we have received no reports of errors or failures,
  783. C{False} otherwise.
  784. """
  785. # Subunit has a bug in its implementation of wasSuccessful, see
  786. # https://bugs.edge.launchpad.net/subunit/+bug/491090, so we can't
  787. # simply forward it on.
  788. return self._successful
  789. def startTest(self, test):
  790. """
  791. Record that C{test} has started.
  792. """
  793. return self._subunit.startTest(test)
  794. def stopTest(self, test):
  795. """
  796. Record that C{test} has completed.
  797. """
  798. return self._subunit.stopTest(test)
  799. def addSuccess(self, test):
  800. """
  801. Record that C{test} was successful.
  802. """
  803. return self._subunit.addSuccess(test)
  804. def addSkip(self, test, reason):
  805. """
  806. Record that C{test} was skipped for C{reason}.
  807. Some versions of subunit don't have support for addSkip. In those
  808. cases, the skip is reported as a success.
  809. @param test: A unittest-compatible C{TestCase}.
  810. @param reason: The reason for it being skipped. The C{str()} of this
  811. object will be included in the subunit output stream.
  812. """
  813. addSkip = getattr(self._subunit, 'addSkip', None)
  814. if addSkip is None:
  815. self.addSuccess(test)
  816. else:
  817. self._subunit.addSkip(test, reason)
  818. def addError(self, test, err):
  819. """
  820. Record that C{test} failed with an unexpected error C{err}.
  821. Also marks the run as being unsuccessful, causing
  822. L{SubunitReporter.wasSuccessful} to return C{False}.
  823. """
  824. self._successful = False
  825. return self._subunit.addError(
  826. test, util.excInfoOrFailureToExcInfo(err))
  827. def addFailure(self, test, err):
  828. """
  829. Record that C{test} failed an assertion with the error C{err}.
  830. Also marks the run as being unsuccessful, causing
  831. L{SubunitReporter.wasSuccessful} to return C{False}.
  832. """
  833. self._successful = False
  834. return self._subunit.addFailure(
  835. test, util.excInfoOrFailureToExcInfo(err))
  836. def addExpectedFailure(self, test, failure, todo):
  837. """
  838. Record an expected failure from a test.
  839. Some versions of subunit do not implement this. For those versions, we
  840. record a success.
  841. """
  842. failure = util.excInfoOrFailureToExcInfo(failure)
  843. addExpectedFailure = getattr(self._subunit, 'addExpectedFailure', None)
  844. if addExpectedFailure is None:
  845. self.addSuccess(test)
  846. else:
  847. addExpectedFailure(test, failure)
  848. def addUnexpectedSuccess(self, test, todo=None):
  849. """
  850. Record an unexpected success.
  851. Since subunit has no way of expressing this concept, we record a
  852. success on the subunit stream.
  853. """
  854. # Not represented in pyunit/subunit.
  855. self.addSuccess(test)
  856. class TreeReporter(Reporter):
  857. """
  858. Print out the tests in the form a tree.
  859. Tests are indented according to which class and module they belong.
  860. Results are printed in ANSI color.
  861. """
  862. currentLine = ''
  863. indent = ' '
  864. columns = 79
  865. FAILURE = 'red'
  866. ERROR = 'red'
  867. TODO = 'blue'
  868. SKIP = 'blue'
  869. TODONE = 'red'
  870. SUCCESS = 'green'
  871. def __init__(self, stream=sys.stdout, *args, **kwargs):
  872. super(TreeReporter, self).__init__(stream, *args, **kwargs)
  873. self._lastTest = []
  874. for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
  875. if colorizer.supported(stream):
  876. self._colorizer = colorizer(stream)
  877. break
  878. def getDescription(self, test):
  879. """
  880. Return the name of the method which 'test' represents. This is
  881. what gets displayed in the leaves of the tree.
  882. e.g. getDescription(TestCase('test_foo')) ==> test_foo
  883. """
  884. return test.id().split('.')[-1]
  885. def addSuccess(self, test):
  886. super(TreeReporter, self).addSuccess(test)
  887. self.endLine('[OK]', self.SUCCESS)
  888. def addError(self, *args):
  889. super(TreeReporter, self).addError(*args)
  890. self.endLine('[ERROR]', self.ERROR)
  891. def addFailure(self, *args):
  892. super(TreeReporter, self).addFailure(*args)
  893. self.endLine('[FAIL]', self.FAILURE)
  894. def addSkip(self, *args):
  895. super(TreeReporter, self).addSkip(*args)
  896. self.endLine('[SKIPPED]', self.SKIP)
  897. def addExpectedFailure(self, *args):
  898. super(TreeReporter, self).addExpectedFailure(*args)
  899. self.endLine('[TODO]', self.TODO)
  900. def addUnexpectedSuccess(self, *args):
  901. super(TreeReporter, self).addUnexpectedSuccess(*args)
  902. self.endLine('[SUCCESS!?!]', self.TODONE)
  903. def _write(self, format, *args):
  904. if args:
  905. format = format % args
  906. self.currentLine = format
  907. super(TreeReporter, self)._write(self.currentLine)
  908. def _getPreludeSegments(self, testID):
  909. """
  910. Return a list of all non-leaf segments to display in the tree.
  911. Normally this is the module and class name.
  912. """
  913. segments = testID.split('.')[:-1]
  914. if len(segments) == 0:
  915. return segments
  916. segments = [
  917. seg for seg in ('.'.join(segments[:-1]), segments[-1])
  918. if len(seg) > 0]
  919. return segments
  920. def _testPrelude(self, testID):
  921. """
  922. Write the name of the test to the stream, indenting it appropriately.
  923. If the test is the first test in a new 'branch' of the tree, also
  924. write all of the parents in that branch.
  925. """
  926. segments = self._getPreludeSegments(testID)
  927. indentLevel = 0
  928. for seg in segments:
  929. if indentLevel < len(self._lastTest):
  930. if seg != self._lastTest[indentLevel]:
  931. self._write('%s%s\n' % (self.indent * indentLevel, seg))
  932. else:
  933. self._write('%s%s\n' % (self.indent * indentLevel, seg))
  934. indentLevel += 1
  935. self._lastTest = segments
  936. def cleanupErrors(self, errs):
  937. self._colorizer.write(' cleanup errors', self.ERROR)
  938. self.endLine('[ERROR]', self.ERROR)
  939. super(TreeReporter, self).cleanupErrors(errs)
  940. def upDownError(self, method, error, warn, printStatus):
  941. self._colorizer.write(" %s" % method, self.ERROR)
  942. if printStatus:
  943. self.endLine('[ERROR]', self.ERROR)
  944. super(TreeReporter, self).upDownError(method, error, warn, printStatus)
  945. def startTest(self, test):
  946. """
  947. Called when C{test} starts. Writes the tests name to the stream using
  948. a tree format.
  949. """
  950. self._testPrelude(test.id())
  951. self._write('%s%s ... ' % (self.indent * (len(self._lastTest)),
  952. self.getDescription(test)))
  953. super(TreeReporter, self).startTest(test)
  954. def endLine(self, message, color):
  955. """
  956. Print 'message' in the given color.
  957. @param message: A string message, usually '[OK]' or something similar.
  958. @param color: A string color, 'red', 'green' and so forth.
  959. """
  960. spaces = ' ' * (self.columns - len(self.currentLine) - len(message))
  961. super(TreeReporter, self)._write(spaces)
  962. self._colorizer.write(message, color)
  963. super(TreeReporter, self)._write("\n")
  964. def _printSummary(self):
  965. """
  966. Print a line summarising the test results to the stream, and color the
  967. status result.
  968. """
  969. summary = self._getSummary()
  970. if self.wasSuccessful():
  971. status = "PASSED"
  972. color = self.SUCCESS
  973. else:
  974. status = "FAILED"
  975. color = self.FAILURE
  976. self._colorizer.write(status, color)
  977. self._write("%s\n", summary)