You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reporter.py 40KB

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