test_reporter.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. #
  4. # Maintainer: Jonathan Lange
  5. """
  6. Tests for L{twisted.trial.reporter}.
  7. """
  8. from __future__ import absolute_import, division
  9. import errno
  10. import os
  11. import re
  12. import sys
  13. from inspect import getmro
  14. from unittest import expectedFailure
  15. from unittest import TestCase as StdlibTestCase
  16. from twisted.python import log, reflect
  17. from twisted.python.failure import Failure
  18. from twisted.python.reflect import qual
  19. from twisted.trial import itrial, unittest, runner, reporter, util
  20. from twisted.trial.reporter import _ExitWrapper, UncleanWarningsReporterWrapper
  21. from twisted.trial.test import erroneous
  22. from twisted.trial.unittest import makeTodo, SkipTest, Todo
  23. from twisted.trial.test import sample
  24. from twisted.python.compat import NativeStringIO, _PY3
  25. if _PY3:
  26. from io import BytesIO
  27. else:
  28. # On Python 2, we want regular old StringIO, because otherwise subunit
  29. # complains
  30. from StringIO import StringIO as BytesIO
  31. class BrokenStream(object):
  32. """
  33. Stream-ish object that raises a signal interrupt error. We use this to make
  34. sure that Trial still manages to write what it needs to write.
  35. """
  36. written = False
  37. flushed = False
  38. def __init__(self, fObj):
  39. self.fObj = fObj
  40. def write(self, s):
  41. if self.written:
  42. return self.fObj.write(s)
  43. self.written = True
  44. raise IOError(errno.EINTR, "Interrupted write")
  45. def flush(self):
  46. if self.flushed:
  47. return self.fObj.flush()
  48. self.flushed = True
  49. raise IOError(errno.EINTR, "Interrupted flush")
  50. class StringTest(unittest.SynchronousTestCase):
  51. def stringComparison(self, expect, output):
  52. output = list(filter(None, output))
  53. self.assertTrue(len(expect) <= len(output),
  54. "Must have more observed than expected"
  55. "lines %d < %d" % (len(output), len(expect)))
  56. REGEX_PATTERN_TYPE = type(re.compile(''))
  57. for line_number, (exp, out) in enumerate(zip(expect, output)):
  58. if exp is None:
  59. continue
  60. elif isinstance(exp, str):
  61. self.assertSubstring(exp, out, "Line %d: %r not in %r"
  62. % (line_number, exp, out))
  63. elif isinstance(exp, REGEX_PATTERN_TYPE):
  64. self.assertTrue(exp.match(out),
  65. "Line %d: %r did not match string %r"
  66. % (line_number, exp.pattern, out))
  67. else:
  68. raise TypeError("don't know what to do with object %r"
  69. % (exp,))
  70. class TestResultTests(unittest.SynchronousTestCase):
  71. def setUp(self):
  72. self.result = reporter.TestResult()
  73. def test_pyunitAddError(self):
  74. # pyunit passes an exc_info tuple directly to addError
  75. try:
  76. raise RuntimeError('foo')
  77. except RuntimeError as e:
  78. excValue = e
  79. self.result.addError(self, sys.exc_info())
  80. failure = self.result.errors[0][1]
  81. self.assertEqual(excValue, failure.value)
  82. self.assertEqual(RuntimeError, failure.type)
  83. def test_pyunitAddFailure(self):
  84. # pyunit passes an exc_info tuple directly to addFailure
  85. try:
  86. raise self.failureException('foo')
  87. except self.failureException as e:
  88. excValue = e
  89. self.result.addFailure(self, sys.exc_info())
  90. failure = self.result.failures[0][1]
  91. self.assertEqual(excValue, failure.value)
  92. self.assertEqual(self.failureException, failure.type)
  93. class ReporterRealtimeTests(TestResultTests):
  94. def setUp(self):
  95. output = NativeStringIO()
  96. self.result = reporter.Reporter(output, realtime=True)
  97. class ErrorReportingTests(StringTest):
  98. doubleSeparator = re.compile(r'^=+$')
  99. def setUp(self):
  100. self.loader = runner.TestLoader()
  101. self.output = NativeStringIO()
  102. self.result = reporter.Reporter(self.output)
  103. def getOutput(self, suite):
  104. result = self.getResult(suite)
  105. result.done()
  106. return self.output.getvalue()
  107. def getResult(self, suite):
  108. suite.run(self.result)
  109. return self.result
  110. def test_formatErroredMethod(self):
  111. """
  112. A test method which runs and has an error recorded against it is
  113. reported in the output stream with the I{ERROR} tag along with a
  114. summary of what error was reported and the ID of the test.
  115. """
  116. cls = erroneous.SynchronousTestFailureInSetUp
  117. suite = self.loader.loadClass(cls)
  118. output = self.getOutput(suite).splitlines()
  119. match = [
  120. self.doubleSeparator,
  121. '[ERROR]',
  122. 'Traceback (most recent call last):',
  123. re.compile(r'^\s+File .*erroneous\.py., line \d+, in setUp$'),
  124. re.compile(r'^\s+raise FoolishError.'
  125. r'.I am a broken setUp method..$'),
  126. ('twisted.trial.test.erroneous.FoolishError: '
  127. 'I am a broken setUp method'),
  128. '%s.%s.test_noop' % (cls.__module__, cls.__name__)]
  129. self.stringComparison(match, output)
  130. def test_formatFailedMethod(self):
  131. """
  132. A test method which runs and has a failure recorded against it is
  133. reported in the output stream with the I{FAIL} tag along with a summary
  134. of what failure was reported and the ID of the test.
  135. """
  136. suite = self.loader.loadByName(
  137. "twisted.trial.test.erroneous.TestRegularFail.test_fail")
  138. output = self.getOutput(suite).splitlines()
  139. match = [
  140. self.doubleSeparator,
  141. '[FAIL]',
  142. 'Traceback (most recent call last):',
  143. re.compile(r'^\s+File .*erroneous\.py., line \d+, in test_fail$'),
  144. re.compile(r'^\s+self\.fail\("I fail"\)$'),
  145. 'twisted.trial.unittest.FailTest: I fail',
  146. 'twisted.trial.test.erroneous.TestRegularFail.test_fail',
  147. ]
  148. self.stringComparison(match, output)
  149. def test_doctestError(self):
  150. """
  151. A problem encountered while running a doctest is reported in the output
  152. stream with a I{FAIL} or I{ERROR} tag along with a summary of what
  153. problem was encountered and the ID of the test.
  154. """
  155. from twisted.trial.test import erroneous
  156. suite = unittest.decorate(
  157. self.loader.loadDoctests(erroneous), itrial.ITestCase)
  158. output = self.getOutput(suite)
  159. path = 'twisted.trial.test.erroneous.unexpectedException'
  160. for substring in ['1/0', 'ZeroDivisionError',
  161. 'Exception raised:', path]:
  162. self.assertSubstring(substring, output)
  163. self.assertTrue(re.search('Fail(ed|ure in) example:', output),
  164. "Couldn't match 'Failure in example: ' "
  165. "or 'Failed example: '")
  166. expect = [self.doubleSeparator,
  167. re.compile(r'\[(ERROR|FAIL)\]')]
  168. self.stringComparison(expect, output.splitlines())
  169. def test_hiddenException(self):
  170. """
  171. Check that errors in C{DelayedCall}s get reported, even if the
  172. test already has a failure.
  173. Only really necessary for testing the deprecated style of tests that
  174. use iterate() directly. See
  175. L{erroneous.DelayedCall.testHiddenException} for more details.
  176. """
  177. from twisted.internet import reactor
  178. if reflect.qual(reactor).startswith("twisted.internet.asyncioreactor"):
  179. raise self.skipTest(
  180. ("This test does not work on the asyncio reactor, as the "
  181. "traceback comes from inside asyncio, not Twisted."))
  182. test = erroneous.DelayedCall('testHiddenException')
  183. output = self.getOutput(test).splitlines()
  184. errorQual = qual(RuntimeError)
  185. match = [
  186. self.doubleSeparator,
  187. '[FAIL]',
  188. 'Traceback (most recent call last):',
  189. re.compile(r'^\s+File .*erroneous\.py., line \d+, in '
  190. 'testHiddenException$'),
  191. re.compile(r'^\s+self\.fail\("Deliberate failure to mask the '
  192. 'hidden exception"\)$'),
  193. 'twisted.trial.unittest.FailTest: '
  194. 'Deliberate failure to mask the hidden exception',
  195. 'twisted.trial.test.erroneous.DelayedCall.testHiddenException',
  196. self.doubleSeparator,
  197. '[ERROR]',
  198. 'Traceback (most recent call last):',
  199. re.compile(r'^\s+File .* in runUntilCurrent'),
  200. re.compile(r'^\s+.*'),
  201. re.compile('^\s+File .*erroneous\.py", line \d+, in go'),
  202. re.compile('^\s+raise RuntimeError\(self.hiddenExceptionMsg\)'),
  203. errorQual + ': something blew up',
  204. 'twisted.trial.test.erroneous.DelayedCall.testHiddenException']
  205. self.stringComparison(match, output)
  206. class UncleanWarningWrapperErrorReportingTests(ErrorReportingTests):
  207. """
  208. Tests that the L{UncleanWarningsReporterWrapper} can sufficiently proxy
  209. IReporter failure and error reporting methods to a L{reporter.Reporter}.
  210. """
  211. def setUp(self):
  212. self.loader = runner.TestLoader()
  213. self.output = NativeStringIO()
  214. self.result = UncleanWarningsReporterWrapper(
  215. reporter.Reporter(self.output))
  216. class TracebackHandlingTests(unittest.SynchronousTestCase):
  217. def getErrorFrames(self, test):
  218. """
  219. Run the given C{test}, make sure it fails and return the trimmed
  220. frames.
  221. @param test: The test case to run.
  222. @return: The C{list} of frames trimmed.
  223. """
  224. stream = NativeStringIO()
  225. result = reporter.Reporter(stream)
  226. test.run(result)
  227. bads = result.failures + result.errors
  228. self.assertEqual(len(bads), 1)
  229. self.assertEqual(bads[0][0], test)
  230. return result._trimFrames(bads[0][1].frames)
  231. def checkFrames(self, observedFrames, expectedFrames):
  232. for observed, expected in zip(observedFrames, expectedFrames):
  233. self.assertEqual(observed[0], expected[0])
  234. observedSegs = os.path.splitext(observed[1])[0].split(os.sep)
  235. expectedSegs = expected[1].split('/')
  236. self.assertEqual(observedSegs[-len(expectedSegs):],
  237. expectedSegs)
  238. self.assertEqual(len(observedFrames), len(expectedFrames))
  239. def test_basic(self):
  240. test = erroneous.TestRegularFail('test_fail')
  241. frames = self.getErrorFrames(test)
  242. self.checkFrames(frames,
  243. [('test_fail', 'twisted/trial/test/erroneous')])
  244. def test_subroutine(self):
  245. test = erroneous.TestRegularFail('test_subfail')
  246. frames = self.getErrorFrames(test)
  247. self.checkFrames(frames,
  248. [('test_subfail', 'twisted/trial/test/erroneous'),
  249. ('subroutine', 'twisted/trial/test/erroneous')])
  250. def test_deferred(self):
  251. """
  252. C{_trimFrames} removes traces of C{_runCallbacks} when getting an error
  253. in a callback returned by a C{TestCase} based test.
  254. """
  255. test = erroneous.TestAsynchronousFail('test_fail')
  256. frames = self.getErrorFrames(test)
  257. self.checkFrames(frames,
  258. [('_later', 'twisted/trial/test/erroneous')])
  259. def test_noFrames(self):
  260. result = reporter.Reporter(None)
  261. self.assertEqual([], result._trimFrames([]))
  262. def test_oneFrame(self):
  263. result = reporter.Reporter(None)
  264. self.assertEqual(['fake frame'], result._trimFrames(['fake frame']))
  265. def test_exception(self):
  266. """
  267. C{_trimFrames} removes traces of C{runWithWarningsSuppressed} from
  268. C{utils} when a synchronous exception happens in a C{TestCase}
  269. based test.
  270. """
  271. test = erroneous.TestAsynchronousFail('test_exception')
  272. frames = self.getErrorFrames(test)
  273. self.checkFrames(frames,
  274. [('test_exception', 'twisted/trial/test/erroneous')])
  275. class FormatFailuresTests(StringTest):
  276. def setUp(self):
  277. try:
  278. raise RuntimeError('foo')
  279. except RuntimeError:
  280. self.f = Failure()
  281. self.f.frames = [
  282. ['foo', 'foo/bar.py', 5, [('x', 5)], [('y', 'orange')]],
  283. ['qux', 'foo/bar.py', 10, [('a', 'two')], [('b', 'MCMXCIX')]]
  284. ]
  285. self.stream = NativeStringIO()
  286. self.result = reporter.Reporter(self.stream)
  287. def test_formatDefault(self):
  288. tb = self.result._formatFailureTraceback(self.f)
  289. self.stringComparison([
  290. 'Traceback (most recent call last):',
  291. ' File "foo/bar.py", line 5, in foo',
  292. re.compile(r'^\s*$'),
  293. ' File "foo/bar.py", line 10, in qux',
  294. re.compile(r'^\s*$'),
  295. 'RuntimeError: foo'], tb.splitlines())
  296. def test_formatString(self):
  297. tb = '''
  298. File "twisted/trial/unittest.py", line 256, in failUnlessSubstring
  299. return self.failUnlessIn(substring, astring, msg)
  300. exceptions.TypeError: iterable argument required
  301. '''
  302. expected = '''
  303. File "twisted/trial/unittest.py", line 256, in failUnlessSubstring
  304. return self.failUnlessIn(substring, astring, msg)
  305. exceptions.TypeError: iterable argument required
  306. '''
  307. formatted = self.result._formatFailureTraceback(tb)
  308. self.assertEqual(expected, formatted)
  309. def test_mutation(self):
  310. frames = self.f.frames[:]
  311. # The call shouldn't mutate the frames.
  312. self.result._formatFailureTraceback(self.f)
  313. self.assertEqual(self.f.frames, frames)
  314. class PyunitNamesTests(unittest.SynchronousTestCase):
  315. def setUp(self):
  316. self.stream = NativeStringIO()
  317. self.test = sample.PyunitTest('test_foo')
  318. def test_verboseReporter(self):
  319. result = reporter.VerboseTextReporter(self.stream)
  320. result.startTest(self.test)
  321. output = self.stream.getvalue()
  322. self.assertEqual(
  323. output, 'twisted.trial.test.sample.PyunitTest.test_foo ... ')
  324. def test_treeReporter(self):
  325. result = reporter.TreeReporter(self.stream)
  326. result.startTest(self.test)
  327. output = self.stream.getvalue()
  328. output = output.splitlines()[-1].strip()
  329. self.assertEqual(output, result.getDescription(self.test) + ' ...')
  330. def test_getDescription(self):
  331. result = reporter.TreeReporter(self.stream)
  332. output = result.getDescription(self.test)
  333. self.assertEqual(output, 'test_foo')
  334. def test_minimalReporter(self):
  335. """
  336. The summary of L{reporter.MinimalReporter} is a simple list of numbers,
  337. indicating how many tests ran, how many failed etc.
  338. The numbers represents:
  339. * the run time of the tests
  340. * the number of tests run, printed 2 times for legacy reasons
  341. * the number of errors
  342. * the number of failures
  343. * the number of skips
  344. """
  345. result = reporter.MinimalReporter(self.stream)
  346. self.test.run(result)
  347. result._printSummary()
  348. output = self.stream.getvalue().strip().split(' ')
  349. self.assertEqual(output[1:], ['1', '1', '0', '0', '0'])
  350. def test_minimalReporterTime(self):
  351. """
  352. L{reporter.MinimalReporter} reports the time to run the tests as first
  353. data in its output.
  354. """
  355. times = [1.0, 1.2, 1.5, 1.9]
  356. result = reporter.MinimalReporter(self.stream)
  357. result._getTime = lambda: times.pop(0)
  358. self.test.run(result)
  359. result._printSummary()
  360. output = self.stream.getvalue().strip().split(' ')
  361. timer = output[0]
  362. self.assertEqual(timer, "0.7")
  363. def test_emptyMinimalReporter(self):
  364. """
  365. The summary of L{reporter.MinimalReporter} is a list of zeroes when no
  366. test is actually run.
  367. """
  368. result = reporter.MinimalReporter(self.stream)
  369. result._printSummary()
  370. output = self.stream.getvalue().strip().split(' ')
  371. self.assertEqual(output, ['0', '0', '0', '0', '0', '0'])
  372. class DirtyReactorTests(unittest.SynchronousTestCase):
  373. """
  374. The trial script has an option to treat L{DirtyReactorAggregateError}s as
  375. warnings, as a migration tool for test authors. It causes a wrapper to be
  376. placed around reporters that replaces L{DirtyReactorAggregatErrors} with
  377. warnings.
  378. """
  379. def setUp(self):
  380. self.dirtyError = Failure(
  381. util.DirtyReactorAggregateError(['foo'], ['bar']))
  382. self.output = NativeStringIO()
  383. self.test = DirtyReactorTests('test_errorByDefault')
  384. def test_errorByDefault(self):
  385. """
  386. L{DirtyReactorAggregateError}s are reported as errors with the default
  387. Reporter.
  388. """
  389. result = reporter.Reporter(stream=self.output)
  390. result.addError(self.test, self.dirtyError)
  391. self.assertEqual(len(result.errors), 1)
  392. self.assertEqual(result.errors[0][1], self.dirtyError)
  393. def test_warningsEnabled(self):
  394. """
  395. L{DirtyReactorAggregateError}s are reported as warnings when using
  396. the L{UncleanWarningsReporterWrapper}.
  397. """
  398. result = UncleanWarningsReporterWrapper(
  399. reporter.Reporter(stream=self.output))
  400. self.assertWarns(UserWarning, self.dirtyError.getErrorMessage(),
  401. reporter.__file__,
  402. result.addError, self.test, self.dirtyError)
  403. def test_warningsMaskErrors(self):
  404. """
  405. L{DirtyReactorAggregateError}s are I{not} reported as errors if the
  406. L{UncleanWarningsReporterWrapper} is used.
  407. """
  408. result = UncleanWarningsReporterWrapper(
  409. reporter.Reporter(stream=self.output))
  410. self.assertWarns(UserWarning, self.dirtyError.getErrorMessage(),
  411. reporter.__file__,
  412. result.addError, self.test, self.dirtyError)
  413. self.assertEqual(result._originalReporter.errors, [])
  414. def test_dealsWithThreeTuples(self):
  415. """
  416. Some annoying stuff can pass three-tuples to addError instead of
  417. Failures (like PyUnit). The wrapper, of course, handles this case,
  418. since it is a part of L{twisted.trial.itrial.IReporter}! But it does
  419. not convert L{DirtyReactorAggregateError} to warnings in this case,
  420. because nobody should be passing those in the form of three-tuples.
  421. """
  422. result = UncleanWarningsReporterWrapper(
  423. reporter.Reporter(stream=self.output))
  424. result.addError(self.test,
  425. (self.dirtyError.type, self.dirtyError.value, None))
  426. self.assertEqual(len(result._originalReporter.errors), 1)
  427. self.assertEqual(result._originalReporter.errors[0][1].type,
  428. self.dirtyError.type)
  429. self.assertEqual(result._originalReporter.errors[0][1].value,
  430. self.dirtyError.value)
  431. class TrialNamesTests(unittest.SynchronousTestCase):
  432. def setUp(self):
  433. self.stream = NativeStringIO()
  434. self.test = sample.FooTest('test_foo')
  435. def test_verboseReporter(self):
  436. result = reporter.VerboseTextReporter(self.stream)
  437. result.startTest(self.test)
  438. output = self.stream.getvalue()
  439. self.assertEqual(output, self.test.id() + ' ... ')
  440. def test_treeReporter(self):
  441. result = reporter.TreeReporter(self.stream)
  442. result.startTest(self.test)
  443. output = self.stream.getvalue()
  444. output = output.splitlines()[-1].strip()
  445. self.assertEqual(output, result.getDescription(self.test) + ' ...')
  446. def test_treeReporterWithDocstrings(self):
  447. """A docstring"""
  448. result = reporter.TreeReporter(self.stream)
  449. self.assertEqual(result.getDescription(self),
  450. 'test_treeReporterWithDocstrings')
  451. def test_getDescription(self):
  452. result = reporter.TreeReporter(self.stream)
  453. output = result.getDescription(self.test)
  454. self.assertEqual(output, "test_foo")
  455. class SkipTests(unittest.SynchronousTestCase):
  456. """
  457. Tests for L{reporter.Reporter}'s handling of skips.
  458. """
  459. def setUp(self):
  460. self.stream = NativeStringIO()
  461. self.result = reporter.Reporter(self.stream)
  462. self.test = sample.FooTest('test_foo')
  463. def _getSkips(self, result):
  464. """
  465. Get the number of skips that happened to a reporter.
  466. """
  467. return len(result.skips)
  468. def test_accumulation(self):
  469. self.result.addSkip(self.test, 'some reason')
  470. self.assertEqual(self._getSkips(self.result), 1)
  471. def test_success(self):
  472. self.result.addSkip(self.test, 'some reason')
  473. self.assertEqual(True, self.result.wasSuccessful())
  474. def test_summary(self):
  475. """
  476. The summary of a successful run with skips indicates that the test
  477. suite passed and includes the number of skips.
  478. """
  479. self.result.addSkip(self.test, 'some reason')
  480. self.result.done()
  481. output = self.stream.getvalue().splitlines()[-1]
  482. prefix = 'PASSED '
  483. self.assertTrue(output.startswith(prefix))
  484. self.assertEqual(output[len(prefix):].strip(), '(skips=1)')
  485. def test_basicErrors(self):
  486. """
  487. The output at the end of a test run with skips includes the reasons
  488. for skipping those tests.
  489. """
  490. self.result.addSkip(self.test, 'some reason')
  491. self.result.done()
  492. output = self.stream.getvalue().splitlines()[3]
  493. self.assertEqual(output.strip(), 'some reason')
  494. def test_booleanSkip(self):
  495. """
  496. Tests can be skipped without specifying a reason by setting the 'skip'
  497. attribute to True. When this happens, the test output includes 'True'
  498. as the reason.
  499. """
  500. self.result.addSkip(self.test, True)
  501. self.result.done()
  502. output = self.stream.getvalue().splitlines()[3]
  503. self.assertEqual(output, 'True')
  504. def test_exceptionSkip(self):
  505. """
  506. Skips can be raised as errors. When this happens, the error is
  507. included in the summary at the end of the test suite.
  508. """
  509. try:
  510. 1/0
  511. except Exception as e:
  512. error = e
  513. self.result.addSkip(self.test, error)
  514. self.result.done()
  515. output = '\n'.join(self.stream.getvalue().splitlines()[3:5]).strip()
  516. self.assertEqual(output, str(error))
  517. class UncleanWarningSkipTests(SkipTests):
  518. """
  519. Tests for skips on a L{reporter.Reporter} wrapped by an
  520. L{UncleanWarningsReporterWrapper}.
  521. """
  522. def setUp(self):
  523. SkipTests.setUp(self)
  524. self.result = UncleanWarningsReporterWrapper(self.result)
  525. def _getSkips(self, result):
  526. """
  527. Get the number of skips that happened to a reporter inside of an
  528. unclean warnings reporter wrapper.
  529. """
  530. return len(result._originalReporter.skips)
  531. class TodoTests(unittest.SynchronousTestCase):
  532. """
  533. Tests for L{reporter.Reporter}'s handling of todos.
  534. """
  535. def setUp(self):
  536. self.stream = NativeStringIO()
  537. self.result = reporter.Reporter(self.stream)
  538. self.test = sample.FooTest('test_foo')
  539. def _getTodos(self, result):
  540. """
  541. Get the expected failures that happened to a reporter.
  542. """
  543. return result.expectedFailures
  544. def _getUnexpectedSuccesses(self, result):
  545. """
  546. Get the unexpected successes that happened to a reporter.
  547. """
  548. return result.unexpectedSuccesses
  549. def test_accumulation(self):
  550. """
  551. L{reporter.Reporter} accumulates the expected failures that it
  552. is notified of.
  553. """
  554. self.result.addExpectedFailure(self.test, Failure(Exception()),
  555. makeTodo('todo!'))
  556. self.assertEqual(len(self._getTodos(self.result)), 1)
  557. def test_noTodoProvided(self):
  558. """
  559. If no C{Todo} is provided to C{addExpectedFailure}, then
  560. L{reporter.Reporter} makes up a sensible default.
  561. This allows standard Python unittests to use Twisted reporters.
  562. """
  563. failure = Failure(Exception())
  564. self.result.addExpectedFailure(self.test, failure)
  565. [(test, error, todo)] = self._getTodos(self.result)
  566. self.assertEqual(test, self.test)
  567. self.assertEqual(error, failure)
  568. self.assertEqual(repr(todo), repr(makeTodo('Test expected to fail')))
  569. def test_success(self):
  570. """
  571. A test run is still successful even if there are expected failures.
  572. """
  573. self.result.addExpectedFailure(self.test, Failure(Exception()),
  574. makeTodo('todo!'))
  575. self.assertEqual(True, self.result.wasSuccessful())
  576. def test_unexpectedSuccess(self):
  577. """
  578. A test which is marked as todo but succeeds will have an unexpected
  579. success reported to its result. A test run is still successful even
  580. when this happens.
  581. """
  582. self.result.addUnexpectedSuccess(self.test, makeTodo("Heya!"))
  583. self.assertEqual(True, self.result.wasSuccessful())
  584. self.assertEqual(len(self._getUnexpectedSuccesses(self.result)), 1)
  585. def test_unexpectedSuccessNoTodo(self):
  586. """
  587. A test which is marked as todo but succeeds will have an unexpected
  588. success reported to its result. A test run is still successful even
  589. when this happens.
  590. If no C{Todo} is provided, then we make up a sensible default. This
  591. allows standard Python unittests to use Twisted reporters.
  592. """
  593. self.result.addUnexpectedSuccess(self.test)
  594. [(test, todo)] = self._getUnexpectedSuccesses(self.result)
  595. self.assertEqual(test, self.test)
  596. self.assertEqual(repr(todo), repr(makeTodo('Test expected to fail')))
  597. def test_summary(self):
  598. """
  599. The reporter's C{printSummary} method should print the number of
  600. expected failures that occurred.
  601. """
  602. self.result.addExpectedFailure(self.test, Failure(Exception()),
  603. makeTodo('some reason'))
  604. self.result.done()
  605. output = self.stream.getvalue().splitlines()[-1]
  606. prefix = 'PASSED '
  607. self.assertTrue(output.startswith(prefix))
  608. self.assertEqual(output[len(prefix):].strip(),
  609. '(expectedFailures=1)')
  610. def test_basicErrors(self):
  611. """
  612. The reporter's L{printErrors} method should include the value of the
  613. Todo.
  614. """
  615. self.result.addExpectedFailure(self.test, Failure(Exception()),
  616. makeTodo('some reason'))
  617. self.result.done()
  618. output = self.stream.getvalue().splitlines()[3].strip()
  619. self.assertEqual(output, "Reason: 'some reason'")
  620. def test_booleanTodo(self):
  621. """
  622. Booleans CAN'T be used as the value of a todo. Maybe this sucks. This
  623. is a test for current behavior, not a requirement.
  624. """
  625. self.result.addExpectedFailure(self.test, Failure(Exception()), True)
  626. self.assertRaises(Exception, self.result.done)
  627. def test_exceptionTodo(self):
  628. """
  629. The exception for expected failures should be shown in the
  630. C{printErrors} output.
  631. """
  632. try:
  633. 1/0
  634. except Exception as e:
  635. error = e
  636. self.result.addExpectedFailure(self.test, Failure(error),
  637. makeTodo("todo!"))
  638. self.result.done()
  639. output = '\n'.join(self.stream.getvalue().splitlines()[3:]).strip()
  640. self.assertTrue(str(error) in output)
  641. def test_standardLibraryCompatibilityFailure(self):
  642. """
  643. Tests that use the standard library C{expectedFailure} feature worth
  644. with Trial reporters.
  645. """
  646. class Test(StdlibTestCase):
  647. @expectedFailure
  648. def test_fail(self):
  649. self.fail('failure')
  650. test = Test('test_fail')
  651. test.run(self.result)
  652. self.assertEqual(len(self._getTodos(self.result)), 1)
  653. def test_standardLibraryCompatibilitySuccess(self):
  654. """
  655. Tests that use the standard library C{expectedFailure} feature worth
  656. with Trial reporters.
  657. """
  658. class Test(StdlibTestCase):
  659. @expectedFailure
  660. def test_success(self):
  661. pass
  662. test = Test('test_success')
  663. test.run(self.result)
  664. self.assertEqual(len(self._getUnexpectedSuccesses(self.result)), 1)
  665. class UncleanWarningTodoTests(TodoTests):
  666. """
  667. Tests for L{UncleanWarningsReporterWrapper}'s handling of todos.
  668. """
  669. def setUp(self):
  670. TodoTests.setUp(self)
  671. self.result = UncleanWarningsReporterWrapper(self.result)
  672. def _getTodos(self, result):
  673. """
  674. Get the todos that happened to a reporter inside of an unclean
  675. warnings reporter wrapper.
  676. """
  677. return result._originalReporter.expectedFailures
  678. def _getUnexpectedSuccesses(self, result):
  679. """
  680. Get the number of unexpected successes that happened to a reporter
  681. inside of an unclean warnings reporter wrapper.
  682. """
  683. return result._originalReporter.unexpectedSuccesses
  684. class MockColorizer(object):
  685. """
  686. Used by TreeReporterTests to make sure that output is colored correctly.
  687. """
  688. def __init__(self, stream):
  689. self.log = []
  690. def write(self, text, color):
  691. self.log.append((color, text))
  692. class TreeReporterTests(unittest.SynchronousTestCase):
  693. def setUp(self):
  694. self.test = sample.FooTest('test_foo')
  695. self.stream = NativeStringIO()
  696. self.result = reporter.TreeReporter(self.stream)
  697. self.result._colorizer = MockColorizer(self.stream)
  698. self.log = self.result._colorizer.log
  699. def makeError(self):
  700. try:
  701. 1/0
  702. except ZeroDivisionError:
  703. f = Failure()
  704. return f
  705. def test_summaryColoredSuccess(self):
  706. """
  707. The summary in case of success should have a good count of successes
  708. and be colored properly.
  709. """
  710. self.result.addSuccess(self.test)
  711. self.result.done()
  712. self.assertEqual(self.log[1], (self.result.SUCCESS, 'PASSED'))
  713. self.assertEqual(
  714. self.stream.getvalue().splitlines()[-1].strip(), "(successes=1)")
  715. def test_summaryColoredFailure(self):
  716. """
  717. The summary in case of failure should have a good count of errors
  718. and be colored properly.
  719. """
  720. try:
  721. raise RuntimeError('foo')
  722. except RuntimeError:
  723. self.result.addError(self, sys.exc_info())
  724. self.result.done()
  725. self.assertEqual(self.log[1], (self.result.FAILURE, 'FAILED'))
  726. self.assertEqual(
  727. self.stream.getvalue().splitlines()[-1].strip(), "(errors=1)")
  728. def test_getPrelude(self):
  729. """
  730. The tree needs to get the segments of the test ID that correspond
  731. to the module and class that it belongs to.
  732. """
  733. self.assertEqual(
  734. ['foo.bar', 'baz'],
  735. self.result._getPreludeSegments('foo.bar.baz.qux'))
  736. self.assertEqual(
  737. ['foo', 'bar'],
  738. self.result._getPreludeSegments('foo.bar.baz'))
  739. self.assertEqual(
  740. ['foo'],
  741. self.result._getPreludeSegments('foo.bar'))
  742. self.assertEqual([], self.result._getPreludeSegments('foo'))
  743. def test_groupResults(self):
  744. """
  745. If two different tests have the same error, L{Reporter._groupResults}
  746. includes them together in one of the tuples in the list it returns.
  747. """
  748. try:
  749. raise RuntimeError('foo')
  750. except RuntimeError:
  751. self.result.addError(self, sys.exc_info())
  752. self.result.addError(self.test, sys.exc_info())
  753. try:
  754. raise RuntimeError('bar')
  755. except RuntimeError:
  756. extra = sample.FooTest('test_bar')
  757. self.result.addError(extra, sys.exc_info())
  758. self.result.done()
  759. grouped = self.result._groupResults(
  760. self.result.errors, self.result._formatFailureTraceback)
  761. self.assertEqual(grouped[0][1], [self, self.test])
  762. self.assertEqual(grouped[1][1], [extra])
  763. def test_printResults(self):
  764. """
  765. L{Reporter._printResults} uses the results list and formatter callable
  766. passed to it to produce groups of results to write to its output
  767. stream.
  768. """
  769. def formatter(n):
  770. return str(n) + '\n'
  771. first = sample.FooTest('test_foo')
  772. second = sample.FooTest('test_bar')
  773. third = sample.PyunitTest('test_foo')
  774. self.result._printResults(
  775. 'FOO', [(first, 1), (second, 1), (third, 2)], formatter)
  776. self.assertEqual(
  777. self.stream.getvalue(),
  778. "%(double separator)s\n"
  779. "FOO\n"
  780. "1\n"
  781. "\n"
  782. "%(first)s\n"
  783. "%(second)s\n"
  784. "%(double separator)s\n"
  785. "FOO\n"
  786. "2\n"
  787. "\n"
  788. "%(third)s\n" % {
  789. 'double separator': self.result._doubleSeparator,
  790. 'first': first.id(),
  791. 'second': second.id(),
  792. 'third': third.id(),
  793. })
  794. class ReporterInterfaceTests(unittest.SynchronousTestCase):
  795. """
  796. Tests for the bare interface of a trial reporter.
  797. Subclass this test case and provide a different 'resultFactory' to test
  798. that a particular reporter implementation will work with the rest of
  799. Trial.
  800. @cvar resultFactory: A callable that returns a reporter to be tested. The
  801. callable must take the same parameters as L{reporter.Reporter}.
  802. """
  803. resultFactory = reporter.Reporter
  804. def setUp(self):
  805. self.test = sample.FooTest('test_foo')
  806. self.stream = NativeStringIO()
  807. self.publisher = log.LogPublisher()
  808. self.result = self.resultFactory(self.stream, publisher=self.publisher)
  809. def test_shouldStopInitiallyFalse(self):
  810. """
  811. shouldStop is False to begin with.
  812. """
  813. self.assertEqual(False, self.result.shouldStop)
  814. def test_shouldStopTrueAfterStop(self):
  815. """
  816. shouldStop becomes True soon as someone calls stop().
  817. """
  818. self.result.stop()
  819. self.assertEqual(True, self.result.shouldStop)
  820. def test_wasSuccessfulInitiallyTrue(self):
  821. """
  822. wasSuccessful() is True when there have been no results reported.
  823. """
  824. self.assertEqual(True, self.result.wasSuccessful())
  825. def test_wasSuccessfulTrueAfterSuccesses(self):
  826. """
  827. wasSuccessful() is True when there have been only successes, False
  828. otherwise.
  829. """
  830. self.result.addSuccess(self.test)
  831. self.assertEqual(True, self.result.wasSuccessful())
  832. def test_wasSuccessfulFalseAfterErrors(self):
  833. """
  834. wasSuccessful() becomes False after errors have been reported.
  835. """
  836. try:
  837. 1 / 0
  838. except ZeroDivisionError:
  839. self.result.addError(self.test, sys.exc_info())
  840. self.assertEqual(False, self.result.wasSuccessful())
  841. def test_wasSuccessfulFalseAfterFailures(self):
  842. """
  843. wasSuccessful() becomes False after failures have been reported.
  844. """
  845. try:
  846. self.fail("foo")
  847. except self.failureException:
  848. self.result.addFailure(self.test, sys.exc_info())
  849. self.assertEqual(False, self.result.wasSuccessful())
  850. class ReporterTests(ReporterInterfaceTests):
  851. """
  852. Tests for the base L{reporter.Reporter} class.
  853. """
  854. def setUp(self):
  855. ReporterInterfaceTests.setUp(self)
  856. self._timer = 0
  857. self.result._getTime = self._getTime
  858. def _getTime(self):
  859. self._timer += 1
  860. return self._timer
  861. def test_startStop(self):
  862. self.result.startTest(self.test)
  863. self.result.stopTest(self.test)
  864. self.assertTrue(self.result._lastTime > 0)
  865. self.assertEqual(self.result.testsRun, 1)
  866. self.assertEqual(self.result.wasSuccessful(), True)
  867. def test_brokenStream(self):
  868. """
  869. Test that the reporter safely writes to its stream.
  870. """
  871. result = self.resultFactory(stream=BrokenStream(self.stream))
  872. result._writeln("Hello")
  873. self.assertEqual(self.stream.getvalue(), 'Hello\n')
  874. self.stream.truncate(0)
  875. self.stream.seek(0)
  876. result._writeln("Hello %s!", 'World')
  877. self.assertEqual(self.stream.getvalue(), 'Hello World!\n')
  878. def test_warning(self):
  879. """
  880. L{reporter.Reporter} observes warnings emitted by the Twisted log
  881. system and writes them to its output stream.
  882. """
  883. message = RuntimeWarning("some warning text")
  884. category = 'exceptions.RuntimeWarning'
  885. filename = "path/to/some/file.py"
  886. lineno = 71
  887. self.publisher.msg(
  888. warning=message, category=category,
  889. filename=filename, lineno=lineno)
  890. self.assertEqual(
  891. self.stream.getvalue(),
  892. "%s:%d: %s: %s\n" % (
  893. filename, lineno, category.split('.')[-1], message))
  894. def test_duplicateWarningSuppressed(self):
  895. """
  896. A warning emitted twice within a single test is only written to the
  897. stream once.
  898. """
  899. # Emit the warning and assert that it shows up
  900. self.test_warning()
  901. # Emit the warning again and assert that the stream still only has one
  902. # warning on it.
  903. self.test_warning()
  904. def test_warningEmittedForNewTest(self):
  905. """
  906. A warning emitted again after a new test has started is written to the
  907. stream again.
  908. """
  909. test = self.__class__('test_warningEmittedForNewTest')
  910. self.result.startTest(test)
  911. # Clear whatever startTest wrote to the stream
  912. self.stream.seek(0)
  913. self.stream.truncate()
  914. # Emit a warning (and incidentally, assert that it was emitted)
  915. self.test_warning()
  916. # Clean up from the first warning to simplify the rest of the
  917. # assertions.
  918. self.stream.seek(0)
  919. self.stream.truncate()
  920. # Stop the first test and start another one (it just happens to be the
  921. # same one, but that doesn't matter)
  922. self.result.stopTest(test)
  923. self.result.startTest(test)
  924. # Clean up the stopTest/startTest output
  925. self.stream.seek(0)
  926. self.stream.truncate()
  927. # Emit the warning again and make sure it shows up
  928. self.test_warning()
  929. def test_stopObserving(self):
  930. """
  931. L{reporter.Reporter} stops observing log events when its C{done} method
  932. is called.
  933. """
  934. self.result.done()
  935. self.stream.seek(0)
  936. self.stream.truncate()
  937. self.publisher.msg(
  938. warning=RuntimeWarning("some message"),
  939. category='exceptions.RuntimeWarning',
  940. filename="file/name.py", lineno=17)
  941. self.assertEqual(self.stream.getvalue(), "")
  942. class SafeStreamTests(unittest.SynchronousTestCase):
  943. def test_safe(self):
  944. """
  945. Test that L{reporter.SafeStream} successfully write to its original
  946. stream even if an interrupt happens during the write.
  947. """
  948. stream = NativeStringIO()
  949. broken = BrokenStream(stream)
  950. safe = reporter.SafeStream(broken)
  951. safe.write("Hello")
  952. self.assertEqual(stream.getvalue(), "Hello")
  953. class SubunitReporterTests(ReporterInterfaceTests):
  954. """
  955. Tests for the subunit reporter.
  956. This just tests that the subunit reporter implements the basic interface.
  957. """
  958. resultFactory = reporter.SubunitReporter
  959. def setUp(self):
  960. if reporter.TestProtocolClient is None:
  961. raise SkipTest(
  962. "Subunit not installed, cannot test SubunitReporter")
  963. self.test = sample.FooTest('test_foo')
  964. self.stream = BytesIO()
  965. self.publisher = log.LogPublisher()
  966. self.result = self.resultFactory(self.stream, publisher=self.publisher)
  967. def assertForwardsToSubunit(self, methodName, *args, **kwargs):
  968. """
  969. Assert that 'methodName' on L{SubunitReporter} forwards to the
  970. equivalent method on subunit.
  971. Checks that the return value from subunit is returned from the
  972. L{SubunitReporter} and that the reporter writes the same data to its
  973. stream as subunit does to its own.
  974. Assumes that the method on subunit has the same name as the method on
  975. L{SubunitReporter}.
  976. """
  977. stream = BytesIO()
  978. subunitClient = reporter.TestProtocolClient(stream)
  979. subunitReturn = getattr(subunitClient, methodName)(*args, **kwargs)
  980. subunitOutput = stream.getvalue()
  981. reporterReturn = getattr(self.result, methodName)(*args, **kwargs)
  982. self.assertEqual(subunitReturn, reporterReturn)
  983. self.assertEqual(subunitOutput, self.stream.getvalue())
  984. def removeMethod(self, klass, methodName):
  985. """
  986. Remove 'methodName' from 'klass'.
  987. If 'klass' does not have a method named 'methodName', then
  988. 'removeMethod' succeeds silently.
  989. If 'klass' does have a method named 'methodName', then it is removed
  990. using delattr. Also, methods of the same name are removed from all
  991. base classes of 'klass', thus removing the method entirely.
  992. @param klass: The class to remove the method from.
  993. @param methodName: The name of the method to remove.
  994. """
  995. method = getattr(klass, methodName, None)
  996. if method is None:
  997. return
  998. for base in getmro(klass):
  999. try:
  1000. delattr(base, methodName)
  1001. except (AttributeError, TypeError):
  1002. break
  1003. else:
  1004. self.addCleanup(setattr, base, methodName, method)
  1005. def test_subunitWithoutAddExpectedFailureInstalled(self):
  1006. """
  1007. Some versions of subunit don't have "addExpectedFailure". For these
  1008. versions, we report expected failures as successes.
  1009. """
  1010. self.removeMethod(reporter.TestProtocolClient, 'addExpectedFailure')
  1011. try:
  1012. 1 / 0
  1013. except ZeroDivisionError:
  1014. self.result.addExpectedFailure(self.test, sys.exc_info(), "todo")
  1015. expectedFailureOutput = self.stream.getvalue()
  1016. self.stream.truncate(0)
  1017. self.stream.seek(0)
  1018. self.result.addSuccess(self.test)
  1019. successOutput = self.stream.getvalue()
  1020. self.assertEqual(successOutput, expectedFailureOutput)
  1021. def test_subunitWithoutAddSkipInstalled(self):
  1022. """
  1023. Some versions of subunit don't have "addSkip". For these versions, we
  1024. report skips as successes.
  1025. """
  1026. self.removeMethod(reporter.TestProtocolClient, 'addSkip')
  1027. self.result.addSkip(self.test, "reason")
  1028. skipOutput = self.stream.getvalue()
  1029. self.stream.truncate(0)
  1030. self.stream.seek(0)
  1031. self.result.addSuccess(self.test)
  1032. successOutput = self.stream.getvalue()
  1033. self.assertEqual(successOutput, skipOutput)
  1034. def test_addExpectedFailurePassedThrough(self):
  1035. """
  1036. Some versions of subunit have "addExpectedFailure". For these
  1037. versions, when we call 'addExpectedFailure' on the test result, we
  1038. pass the error and test through to the subunit client.
  1039. """
  1040. addExpectedFailureCalls = []
  1041. def addExpectedFailure(test, error):
  1042. addExpectedFailureCalls.append((test, error))
  1043. # Provide our own addExpectedFailure, whether or not the locally
  1044. # installed subunit has addExpectedFailure.
  1045. self.result._subunit.addExpectedFailure = addExpectedFailure
  1046. try:
  1047. 1 / 0
  1048. except ZeroDivisionError:
  1049. exc_info = sys.exc_info()
  1050. self.result.addExpectedFailure(self.test, exc_info, 'todo')
  1051. self.assertEqual(addExpectedFailureCalls, [(self.test, exc_info)])
  1052. def test_addSkipSendsSubunitAddSkip(self):
  1053. """
  1054. Some versions of subunit have "addSkip". For these versions, when we
  1055. call 'addSkip' on the test result, we pass the test and reason through
  1056. to the subunit client.
  1057. """
  1058. addSkipCalls = []
  1059. def addSkip(test, reason):
  1060. addSkipCalls.append((test, reason))
  1061. # Provide our own addSkip, whether or not the locally-installed
  1062. # subunit has addSkip.
  1063. self.result._subunit.addSkip = addSkip
  1064. self.result.addSkip(self.test, 'reason')
  1065. self.assertEqual(addSkipCalls, [(self.test, 'reason')])
  1066. def test_doneDoesNothing(self):
  1067. """
  1068. The subunit reporter doesn't need to print out a summary -- the stream
  1069. of results is everything. Thus, done() does nothing.
  1070. """
  1071. self.result.done()
  1072. self.assertEqual(b'', self.stream.getvalue())
  1073. def test_startTestSendsSubunitStartTest(self):
  1074. """
  1075. SubunitReporter.startTest() sends the subunit 'startTest' message.
  1076. """
  1077. self.assertForwardsToSubunit('startTest', self.test)
  1078. def test_stopTestSendsSubunitStopTest(self):
  1079. """
  1080. SubunitReporter.stopTest() sends the subunit 'stopTest' message.
  1081. """
  1082. self.assertForwardsToSubunit('stopTest', self.test)
  1083. def test_addSuccessSendsSubunitAddSuccess(self):
  1084. """
  1085. SubunitReporter.addSuccess() sends the subunit 'addSuccess' message.
  1086. """
  1087. self.assertForwardsToSubunit('addSuccess', self.test)
  1088. def test_addErrorSendsSubunitAddError(self):
  1089. """
  1090. SubunitReporter.addError() sends the subunit 'addError' message.
  1091. """
  1092. try:
  1093. 1 / 0
  1094. except ZeroDivisionError:
  1095. error = sys.exc_info()
  1096. self.assertForwardsToSubunit('addError', self.test, error)
  1097. def test_addFailureSendsSubunitAddFailure(self):
  1098. """
  1099. SubunitReporter.addFailure() sends the subunit 'addFailure' message.
  1100. """
  1101. try:
  1102. self.fail('hello')
  1103. except self.failureException:
  1104. failure = sys.exc_info()
  1105. self.assertForwardsToSubunit('addFailure', self.test, failure)
  1106. def test_addUnexpectedSuccessSendsSubunitAddSuccess(self):
  1107. """
  1108. SubunitReporter.addFailure() sends the subunit 'addSuccess' message,
  1109. since subunit doesn't model unexpected success.
  1110. """
  1111. stream = BytesIO()
  1112. subunitClient = reporter.TestProtocolClient(stream)
  1113. subunitClient.addSuccess(self.test)
  1114. subunitOutput = stream.getvalue()
  1115. self.result.addUnexpectedSuccess(self.test)
  1116. self.assertEqual(subunitOutput, self.stream.getvalue())
  1117. def test_loadTimeErrors(self):
  1118. """
  1119. Load-time errors are reported like normal errors.
  1120. """
  1121. test = runner.TestLoader().loadByName('doesntexist')
  1122. test.run(self.result)
  1123. output = self.stream.getvalue()
  1124. # Just check that 'doesntexist' is in the output, rather than
  1125. # assembling the expected stack trace.
  1126. self.assertIn(b'doesntexist', output)
  1127. class SubunitReporterNotInstalledTests(unittest.SynchronousTestCase):
  1128. """
  1129. Test behaviour when the subunit reporter is not installed.
  1130. """
  1131. def test_subunitNotInstalled(self):
  1132. """
  1133. If subunit is not installed, TestProtocolClient will be None, and
  1134. SubunitReporter will raise an error when you try to construct it.
  1135. """
  1136. stream = NativeStringIO()
  1137. self.patch(reporter, 'TestProtocolClient', None)
  1138. e = self.assertRaises(Exception, reporter.SubunitReporter, stream)
  1139. self.assertEqual("Subunit not available", str(e))
  1140. class TimingReporterTests(ReporterTests):
  1141. resultFactory = reporter.TimingTextReporter
  1142. class LoggingReporter(reporter.Reporter):
  1143. """
  1144. Simple reporter that stores the last test that was passed to it.
  1145. """
  1146. def __init__(self, *args, **kwargs):
  1147. reporter.Reporter.__init__(self, *args, **kwargs)
  1148. self.test = None
  1149. def addError(self, test, error):
  1150. self.test = test
  1151. def addExpectedFailure(self, test, failure, todo=None):
  1152. self.test = test
  1153. def addFailure(self, test, failure):
  1154. self.test = test
  1155. def addSkip(self, test, skip):
  1156. self.test = test
  1157. def addUnexpectedSuccess(self, test, todo=None):
  1158. self.test = test
  1159. def startTest(self, test):
  1160. self.test = test
  1161. def stopTest(self, test):
  1162. self.test = test
  1163. class AdaptedReporterTests(unittest.SynchronousTestCase):
  1164. """
  1165. L{reporter._AdaptedReporter} is a reporter wrapper that wraps all of the
  1166. tests it receives before passing them on to the original reporter.
  1167. """
  1168. def setUp(self):
  1169. self.wrappedResult = self.getWrappedResult()
  1170. def _testAdapter(self, test):
  1171. return test.id()
  1172. def assertWrapped(self, wrappedResult, test):
  1173. self.assertEqual(wrappedResult._originalReporter.test,
  1174. self._testAdapter(test))
  1175. def getFailure(self, exceptionInstance):
  1176. """
  1177. Return a L{Failure} from raising the given exception.
  1178. @param exceptionInstance: The exception to raise.
  1179. @return: L{Failure}
  1180. """
  1181. try:
  1182. raise exceptionInstance
  1183. except:
  1184. return Failure()
  1185. def getWrappedResult(self):
  1186. result = LoggingReporter()
  1187. return reporter._AdaptedReporter(result, self._testAdapter)
  1188. def test_addError(self):
  1189. """
  1190. C{addError} wraps its test with the provided adapter.
  1191. """
  1192. self.wrappedResult.addError(self, self.getFailure(RuntimeError()))
  1193. self.assertWrapped(self.wrappedResult, self)
  1194. def test_addFailure(self):
  1195. """
  1196. C{addFailure} wraps its test with the provided adapter.
  1197. """
  1198. self.wrappedResult.addFailure(self, self.getFailure(AssertionError()))
  1199. self.assertWrapped(self.wrappedResult, self)
  1200. def test_addSkip(self):
  1201. """
  1202. C{addSkip} wraps its test with the provided adapter.
  1203. """
  1204. self.wrappedResult.addSkip(
  1205. self, self.getFailure(SkipTest('no reason')))
  1206. self.assertWrapped(self.wrappedResult, self)
  1207. def test_startTest(self):
  1208. """
  1209. C{startTest} wraps its test with the provided adapter.
  1210. """
  1211. self.wrappedResult.startTest(self)
  1212. self.assertWrapped(self.wrappedResult, self)
  1213. def test_stopTest(self):
  1214. """
  1215. C{stopTest} wraps its test with the provided adapter.
  1216. """
  1217. self.wrappedResult.stopTest(self)
  1218. self.assertWrapped(self.wrappedResult, self)
  1219. def test_addExpectedFailure(self):
  1220. """
  1221. C{addExpectedFailure} wraps its test with the provided adapter.
  1222. """
  1223. self.wrappedResult.addExpectedFailure(
  1224. self, self.getFailure(RuntimeError()), Todo("no reason"))
  1225. self.assertWrapped(self.wrappedResult, self)
  1226. def test_expectedFailureWithoutTodo(self):
  1227. """
  1228. C{addExpectedFailure} works without a C{Todo}.
  1229. """
  1230. self.wrappedResult.addExpectedFailure(
  1231. self, self.getFailure(RuntimeError()))
  1232. self.assertWrapped(self.wrappedResult, self)
  1233. def test_addUnexpectedSuccess(self):
  1234. """
  1235. C{addUnexpectedSuccess} wraps its test with the provided adapter.
  1236. """
  1237. self.wrappedResult.addUnexpectedSuccess(self, Todo("no reason"))
  1238. self.assertWrapped(self.wrappedResult, self)
  1239. def test_unexpectedSuccessWithoutTodo(self):
  1240. """
  1241. C{addUnexpectedSuccess} works without a C{Todo}.
  1242. """
  1243. self.wrappedResult.addUnexpectedSuccess(self)
  1244. self.assertWrapped(self.wrappedResult, self)
  1245. class FakeStream(object):
  1246. """
  1247. A fake stream which C{isatty} method returns some predictable.
  1248. @ivar tty: returned value of C{isatty}.
  1249. @type tty: C{bool}
  1250. """
  1251. def __init__(self, tty=True):
  1252. self.tty = tty
  1253. def isatty(self):
  1254. return self.tty
  1255. class AnsiColorizerTests(unittest.SynchronousTestCase):
  1256. """
  1257. Tests for L{reporter._AnsiColorizer}.
  1258. """
  1259. def setUp(self):
  1260. self.savedModules = sys.modules.copy()
  1261. def tearDown(self):
  1262. sys.modules.clear()
  1263. sys.modules.update(self.savedModules)
  1264. def test_supportedStdOutTTY(self):
  1265. """
  1266. L{reporter._AnsiColorizer.supported} returns C{False} if the given
  1267. stream is not a TTY.
  1268. """
  1269. self.assertFalse(reporter._AnsiColorizer.supported(FakeStream(False)))
  1270. def test_supportedNoCurses(self):
  1271. """
  1272. L{reporter._AnsiColorizer.supported} returns C{False} if the curses
  1273. module can't be imported.
  1274. """
  1275. sys.modules['curses'] = None
  1276. self.assertFalse(reporter._AnsiColorizer.supported(FakeStream()))
  1277. def test_supportedSetupTerm(self):
  1278. """
  1279. L{reporter._AnsiColorizer.supported} returns C{True} if
  1280. C{curses.tigetnum} returns more than 2 supported colors. It only tries
  1281. to call C{curses.setupterm} if C{curses.tigetnum} previously failed
  1282. with a C{curses.error}.
  1283. """
  1284. class fakecurses(object):
  1285. error = RuntimeError
  1286. setUp = 0
  1287. def setupterm(self):
  1288. self.setUp += 1
  1289. def tigetnum(self, value):
  1290. if self.setUp:
  1291. return 3
  1292. else:
  1293. raise self.error()
  1294. sys.modules['curses'] = fakecurses()
  1295. self.assertTrue(reporter._AnsiColorizer.supported(FakeStream()))
  1296. self.assertTrue(reporter._AnsiColorizer.supported(FakeStream()))
  1297. self.assertEqual(sys.modules['curses'].setUp, 1)
  1298. def test_supportedTigetNumWrongError(self):
  1299. """
  1300. L{reporter._AnsiColorizer.supported} returns C{False} and doesn't try
  1301. to call C{curses.setupterm} if C{curses.tigetnum} returns something
  1302. different than C{curses.error}.
  1303. """
  1304. class fakecurses(object):
  1305. error = RuntimeError
  1306. def tigetnum(self, value):
  1307. raise ValueError()
  1308. sys.modules['curses'] = fakecurses()
  1309. self.assertFalse(reporter._AnsiColorizer.supported(FakeStream()))
  1310. def test_supportedTigetNumNotEnoughColor(self):
  1311. """
  1312. L{reporter._AnsiColorizer.supported} returns C{False} if
  1313. C{curses.tigetnum} returns less than 2 supported colors.
  1314. """
  1315. class fakecurses(object):
  1316. error = RuntimeError
  1317. def tigetnum(self, value):
  1318. return 1
  1319. sys.modules['curses'] = fakecurses()
  1320. self.assertFalse(reporter._AnsiColorizer.supported(FakeStream()))
  1321. def test_supportedTigetNumErrors(self):
  1322. """
  1323. L{reporter._AnsiColorizer.supported} returns C{False} if
  1324. C{curses.tigetnum} raises an error, and calls C{curses.setupterm} once.
  1325. """
  1326. class fakecurses(object):
  1327. error = RuntimeError
  1328. setUp = 0
  1329. def setupterm(self):
  1330. self.setUp += 1
  1331. def tigetnum(self, value):
  1332. raise self.error()
  1333. sys.modules['curses'] = fakecurses()
  1334. self.assertFalse(reporter._AnsiColorizer.supported(FakeStream()))
  1335. self.assertEqual(sys.modules['curses'].setUp, 1)
  1336. class ExitWrapperTests(unittest.SynchronousTestCase):
  1337. """
  1338. Tests for L{reporter._ExitWrapper}.
  1339. """
  1340. def setUp(self):
  1341. self.failure = Failure(Exception("I am a Failure"))
  1342. self.test = sample.FooTest('test_foo')
  1343. self.result = reporter.TestResult()
  1344. self.wrapped = _ExitWrapper(self.result)
  1345. self.assertFalse(self.wrapped.shouldStop)
  1346. def test_stopOnFailure(self):
  1347. """
  1348. L{reporter._ExitWrapper} causes a wrapped reporter to stop after its
  1349. first failure.
  1350. """
  1351. self.wrapped.addFailure(self.test, self.failure)
  1352. self.assertTrue(self.wrapped.shouldStop)
  1353. self.assertEqual(self.result.failures, [(self.test, self.failure)])
  1354. def test_stopOnError(self):
  1355. """
  1356. L{reporter._ExitWrapper} causes a wrapped reporter to stop after its
  1357. first error.
  1358. """
  1359. self.wrapped.addError(self.test, self.failure)
  1360. self.assertTrue(self.wrapped.shouldStop)
  1361. self.assertEqual(self.result.errors, [(self.test, self.failure)])
  1362. def test_doesNotStopOnUnexpectedSuccess(self):
  1363. """
  1364. L{reporter._ExitWrapper} does not cause a wrapped reporter to stop
  1365. after an unexpected success.
  1366. """
  1367. self.wrapped.addUnexpectedSuccess(self.test, self.failure)
  1368. self.assertFalse(self.wrapped.shouldStop)
  1369. self.assertEqual(
  1370. self.result.unexpectedSuccesses, [(self.test, self.failure)])