PageRenderTime 84ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/twisted-trunk/twisted/trial/test/test_reporter.py

https://bitbucket.org/csenger/benchmarks
Python | 1649 lines | 1627 code | 11 blank | 11 comment | 3 complexity | 974a81797697db0f7b014ee64a30b088 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file