test_tests.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for the behaviour of unit tests.
  5. Many tests in this module follow a simple pattern. A mixin is defined which
  6. includes test methods for a certain feature. The mixin is inherited from twice,
  7. once by a class also inheriting from SynchronousTestCase and once from a class
  8. inheriting from TestCase. These two subclasses are named like
  9. I{SynchronousFooTests} and I{AsynchronousFooTests}, where I{Foo} is related to
  10. the name of the mixin. Sometimes the mixin is defined in another module, along
  11. with the synchronous subclass. The mixin is imported into this module to define
  12. the asynchronous subclass.
  13. This pattern allows the same tests to be applied to the two base test case
  14. classes trial provides, ensuring their behavior is the same.
  15. Most new tests should be added in this pattern. Tests for functionality which
  16. is intentionally only provided by TestCase, not SynchronousTestCase, is excepted
  17. of course.
  18. """
  19. from __future__ import division, absolute_import
  20. import gc, sys, weakref
  21. import unittest as pyunit
  22. from twisted.python.compat import NativeStringIO, _PY3
  23. from twisted.python.reflect import namedAny
  24. from twisted.internet import defer, reactor
  25. from twisted.trial import unittest, reporter, util
  26. from twisted.trial import runner
  27. from twisted.trial.test import erroneous
  28. from twisted.trial.test.test_suppression import SuppressionMixin
  29. from twisted.trial._asyncrunner import (
  30. _clearSuite,
  31. _ForceGarbageCollectionDecorator,
  32. _iterateTests,
  33. )
  34. class ResultsTestMixin(object):
  35. """
  36. Provide useful APIs for test cases that are about test cases.
  37. """
  38. def loadSuite(self, suite):
  39. """
  40. Load tests from the given test case class and create a new reporter to
  41. use for running it.
  42. """
  43. self.loader = pyunit.TestLoader()
  44. self.suite = self.loader.loadTestsFromTestCase(suite)
  45. self.reporter = reporter.TestResult()
  46. def test_setUp(self):
  47. """
  48. test the setup
  49. """
  50. self.assertTrue(self.reporter.wasSuccessful())
  51. self.assertEqual(self.reporter.errors, [])
  52. self.assertEqual(self.reporter.failures, [])
  53. self.assertEqual(self.reporter.skips, [])
  54. def assertCount(self, numTests):
  55. """
  56. Asserts that the test count is plausible
  57. """
  58. self.assertEqual(self.suite.countTestCases(), numTests)
  59. self.suite(self.reporter)
  60. self.assertEqual(self.reporter.testsRun, numTests)
  61. class SuccessMixin(object):
  62. """
  63. Tests for the reporting of successful tests in L{twisted.trial.unittest.TestCase}.
  64. """
  65. def setUp(self):
  66. """
  67. Setup our test case
  68. """
  69. self.result = reporter.TestResult()
  70. def test_successful(self):
  71. """
  72. A successful test, used by other tests.
  73. """
  74. def assertSuccessful(self, test, result):
  75. """
  76. Utility function -- assert there is one success and the state is
  77. plausible
  78. """
  79. self.assertEqual(result.successes, 1)
  80. self.assertEqual(result.failures, [])
  81. self.assertEqual(result.errors, [])
  82. self.assertEqual(result.expectedFailures, [])
  83. self.assertEqual(result.unexpectedSuccesses, [])
  84. self.assertEqual(result.skips, [])
  85. def test_successfulIsReported(self):
  86. """
  87. Test that when a successful test is run, it is reported as a success,
  88. and not as any other kind of result.
  89. """
  90. test = self.__class__('test_successful')
  91. test.run(self.result)
  92. self.assertSuccessful(test, self.result)
  93. def test_defaultIsSuccessful(self):
  94. """
  95. The test case type can be instantiated with no arguments, run, and
  96. reported as being successful.
  97. """
  98. test = self.__class__()
  99. test.run(self.result)
  100. self.assertSuccessful(test, self.result)
  101. def test_noReference(self):
  102. """
  103. Test that no reference is kept on a successful test.
  104. """
  105. test = self.__class__('test_successful')
  106. ref = weakref.ref(test)
  107. test.run(self.result)
  108. self.assertSuccessful(test, self.result)
  109. del test
  110. gc.collect()
  111. self.assertIdentical(ref(), None)
  112. class SynchronousSuccessTests(SuccessMixin, unittest.SynchronousTestCase):
  113. """
  114. Tests for the reporting of successful tests in the synchronous case.
  115. """
  116. class AsynchronousSuccessTests(SuccessMixin, unittest.TestCase):
  117. """
  118. Tests for the reporting of successful tests in the synchronous case.
  119. """
  120. class SkipMethodsMixin(ResultsTestMixin):
  121. """
  122. Tests for the reporting of skipping tests in L{twisted.trial.unittest.TestCase}.
  123. """
  124. def setUp(self):
  125. """
  126. Setup our test case
  127. """
  128. self.loadSuite(self.Skipping)
  129. def test_counting(self):
  130. """
  131. Assert that there are three tests.
  132. """
  133. self.assertCount(3)
  134. def test_results(self):
  135. """
  136. Running a suite in which all methods are individually set to skip
  137. produces a successful result with no recorded errors or failures, all
  138. the skipped methods recorded as skips, and no methods recorded as
  139. successes.
  140. """
  141. self.suite(self.reporter)
  142. self.assertTrue(self.reporter.wasSuccessful())
  143. self.assertEqual(self.reporter.errors, [])
  144. self.assertEqual(self.reporter.failures, [])
  145. self.assertEqual(len(self.reporter.skips), 3)
  146. self.assertEqual(self.reporter.successes, 0)
  147. def test_setUp(self):
  148. """
  149. Running a suite in which all methods are skipped by C{setUp} raising
  150. L{SkipTest} produces a successful result with no recorded errors or
  151. failures, all skipped methods recorded as skips, and no methods recorded
  152. as successes.
  153. """
  154. self.loadSuite(self.SkippingSetUp)
  155. self.suite(self.reporter)
  156. self.assertTrue(self.reporter.wasSuccessful())
  157. self.assertEqual(self.reporter.errors, [])
  158. self.assertEqual(self.reporter.failures, [])
  159. self.assertEqual(len(self.reporter.skips), 2)
  160. self.assertEqual(self.reporter.successes, 0)
  161. def test_reasons(self):
  162. """
  163. Test that reasons work
  164. """
  165. self.suite(self.reporter)
  166. prefix = 'test_'
  167. # whiteboxing reporter
  168. for test, reason in self.reporter.skips:
  169. self.assertEqual(test.shortDescription()[len(prefix):],
  170. str(reason))
  171. def test_deprecatedSkipWithoutReason(self):
  172. """
  173. If a test method raises L{SkipTest} with no reason, a deprecation
  174. warning is emitted.
  175. """
  176. self.loadSuite(self.DeprecatedReasonlessSkip)
  177. self.suite(self.reporter)
  178. warnings = self.flushWarnings([
  179. self.DeprecatedReasonlessSkip.test_1])
  180. self.assertEqual(1, len(warnings))
  181. self.assertEqual(DeprecationWarning, warnings[0]['category'])
  182. self.assertEqual(
  183. "Do not raise unittest.SkipTest with no arguments! Give a reason "
  184. "for skipping tests!",
  185. warnings[0]['message'])
  186. class SynchronousSkipMethodTests(SkipMethodsMixin, unittest.SynchronousTestCase):
  187. """
  188. Tests for the reporting of skipping tests in the synchronous case.
  189. See: L{twisted.trial.test.test_tests.SkipMethodsMixin}
  190. """
  191. Skipping = namedAny('twisted.trial.test.skipping.SynchronousSkipping')
  192. SkippingSetUp = namedAny(
  193. 'twisted.trial.test.skipping.SynchronousSkippingSetUp')
  194. DeprecatedReasonlessSkip = namedAny(
  195. 'twisted.trial.test.skipping.SynchronousDeprecatedReasonlessSkip')
  196. class AsynchronousSkipMethodTests(SkipMethodsMixin, unittest.TestCase):
  197. """
  198. Tests for the reporting of skipping tests in the asynchronous case.
  199. See: L{twisted.trial.test.test_tests.SkipMethodsMixin}
  200. """
  201. Skipping = namedAny('twisted.trial.test.skipping.AsynchronousSkipping')
  202. SkippingSetUp = namedAny(
  203. 'twisted.trial.test.skipping.AsynchronousSkippingSetUp')
  204. DeprecatedReasonlessSkip = namedAny(
  205. 'twisted.trial.test.skipping.AsynchronousDeprecatedReasonlessSkip')
  206. class SkipClassesMixin(ResultsTestMixin):
  207. """
  208. Test the class skipping features of L{twisted.trial.unittest.TestCase}.
  209. """
  210. def setUp(self):
  211. """
  212. Setup our test case
  213. """
  214. self.loadSuite(self.SkippedClass)
  215. self.SkippedClass._setUpRan = False
  216. def test_counting(self):
  217. """
  218. Skipped test methods still contribute to the total test count.
  219. """
  220. self.assertCount(4)
  221. def test_setUpRan(self):
  222. """
  223. The C{setUp} method is not called if the class is set to skip.
  224. """
  225. self.suite(self.reporter)
  226. self.assertFalse(self.SkippedClass._setUpRan)
  227. def test_results(self):
  228. """
  229. Skipped test methods don't cause C{wasSuccessful} to return C{False},
  230. nor do they contribute to the C{errors} or C{failures} of the reporter,
  231. or to the count of successes. They do, however, add elements to the
  232. reporter's C{skips} list.
  233. """
  234. self.suite(self.reporter)
  235. self.assertTrue(self.reporter.wasSuccessful())
  236. self.assertEqual(self.reporter.errors, [])
  237. self.assertEqual(self.reporter.failures, [])
  238. self.assertEqual(len(self.reporter.skips), 4)
  239. self.assertEqual(self.reporter.successes, 0)
  240. def test_reasons(self):
  241. """
  242. Test methods which raise L{unittest.SkipTest} or have their C{skip}
  243. attribute set to something are skipped.
  244. """
  245. self.suite(self.reporter)
  246. expectedReasons = ['class', 'skip2', 'class', 'class']
  247. # whitebox reporter
  248. reasonsGiven = [reason for test, reason in self.reporter.skips]
  249. self.assertEqual(expectedReasons, reasonsGiven)
  250. class SynchronousSkipClassTests(SkipClassesMixin, unittest.SynchronousTestCase):
  251. """
  252. Test the class skipping features in the synchronous case.
  253. See: L{twisted.trial.test.test_tests.SkipClassesMixin}
  254. """
  255. SkippedClass = namedAny(
  256. 'twisted.trial.test.skipping.SynchronousSkippedClass')
  257. class AsynchronousSkipClassTests(SkipClassesMixin, unittest.TestCase):
  258. """
  259. Test the class skipping features in the asynchronous case.
  260. See: L{twisted.trial.test.test_tests.SkipClassesMixin}
  261. """
  262. SkippedClass = namedAny(
  263. 'twisted.trial.test.skipping.AsynchronousSkippedClass')
  264. class TodoMixin(ResultsTestMixin):
  265. """
  266. Tests for the individual test method I{expected failure} features of
  267. L{twisted.trial.unittest.TestCase}.
  268. """
  269. def setUp(self):
  270. """
  271. Setup our test case
  272. """
  273. self.loadSuite(self.Todo)
  274. def test_counting(self):
  275. """
  276. Ensure that we've got three test cases.
  277. """
  278. self.assertCount(3)
  279. def test_results(self):
  280. """
  281. Running a suite in which all methods are individually marked as expected
  282. to fail produces a successful result with no recorded errors, failures,
  283. or skips, all methods which fail and were expected to fail recorded as
  284. C{expectedFailures}, and all methods which pass but which were expected
  285. to fail recorded as C{unexpectedSuccesses}. Additionally, no tests are
  286. recorded as successes.
  287. """
  288. self.suite(self.reporter)
  289. self.assertTrue(self.reporter.wasSuccessful())
  290. self.assertEqual(self.reporter.errors, [])
  291. self.assertEqual(self.reporter.failures, [])
  292. self.assertEqual(self.reporter.skips, [])
  293. self.assertEqual(len(self.reporter.expectedFailures), 2)
  294. self.assertEqual(len(self.reporter.unexpectedSuccesses), 1)
  295. self.assertEqual(self.reporter.successes, 0)
  296. def test_expectedFailures(self):
  297. """
  298. Ensure that expected failures are handled properly.
  299. """
  300. self.suite(self.reporter)
  301. expectedReasons = ['todo1', 'todo2']
  302. reasonsGiven = [ r.reason
  303. for t, e, r in self.reporter.expectedFailures ]
  304. self.assertEqual(expectedReasons, reasonsGiven)
  305. def test_unexpectedSuccesses(self):
  306. """
  307. Ensure that unexpected successes are caught.
  308. """
  309. self.suite(self.reporter)
  310. expectedReasons = ['todo3']
  311. reasonsGiven = [ r.reason
  312. for t, r in self.reporter.unexpectedSuccesses ]
  313. self.assertEqual(expectedReasons, reasonsGiven)
  314. def test_expectedSetUpFailure(self):
  315. """
  316. C{setUp} is excluded from the failure expectation defined by a C{todo}
  317. attribute on a test method.
  318. """
  319. self.loadSuite(self.SetUpTodo)
  320. self.suite(self.reporter)
  321. self.assertFalse(self.reporter.wasSuccessful())
  322. self.assertEqual(len(self.reporter.errors), 1)
  323. self.assertEqual(self.reporter.failures, [])
  324. self.assertEqual(self.reporter.skips, [])
  325. self.assertEqual(len(self.reporter.expectedFailures), 0)
  326. self.assertEqual(len(self.reporter.unexpectedSuccesses), 0)
  327. self.assertEqual(self.reporter.successes, 0)
  328. def test_expectedTearDownFailure(self):
  329. """
  330. C{tearDown} is excluded from the failure expectation defined by a C{todo}
  331. attribute on a test method.
  332. """
  333. self.loadSuite(self.TearDownTodo)
  334. self.suite(self.reporter)
  335. self.assertFalse(self.reporter.wasSuccessful())
  336. self.assertEqual(len(self.reporter.errors), 1)
  337. self.assertEqual(self.reporter.failures, [])
  338. self.assertEqual(self.reporter.skips, [])
  339. self.assertEqual(len(self.reporter.expectedFailures), 0)
  340. # This seems strange, since tearDown raised an exception. However, the
  341. # test method did complete without error. The tearDown error is
  342. # reflected in the errors list, checked above.
  343. self.assertEqual(len(self.reporter.unexpectedSuccesses), 1)
  344. self.assertEqual(self.reporter.successes, 0)
  345. class SynchronousTodoTests(TodoMixin, unittest.SynchronousTestCase):
  346. """
  347. Test the class skipping features in the synchronous case.
  348. See: L{twisted.trial.test.test_tests.TodoMixin}
  349. """
  350. Todo = namedAny('twisted.trial.test.skipping.SynchronousTodo')
  351. SetUpTodo = namedAny('twisted.trial.test.skipping.SynchronousSetUpTodo')
  352. TearDownTodo = namedAny(
  353. 'twisted.trial.test.skipping.SynchronousTearDownTodo')
  354. class AsynchronousTodoTests(TodoMixin, unittest.TestCase):
  355. """
  356. Test the class skipping features in the asynchronous case.
  357. See: L{twisted.trial.test.test_tests.TodoMixin}
  358. """
  359. Todo = namedAny('twisted.trial.test.skipping.AsynchronousTodo')
  360. SetUpTodo = namedAny('twisted.trial.test.skipping.AsynchronousSetUpTodo')
  361. TearDownTodo = namedAny(
  362. 'twisted.trial.test.skipping.AsynchronousTearDownTodo')
  363. class ClassTodoMixin(ResultsTestMixin):
  364. """
  365. Tests for the class-wide I{expected failure} features of
  366. L{twisted.trial.unittest.TestCase}.
  367. """
  368. def setUp(self):
  369. """
  370. Setup our test case
  371. """
  372. self.loadSuite(self.TodoClass)
  373. def test_counting(self):
  374. """
  375. Ensure that we've got four test cases.
  376. """
  377. self.assertCount(4)
  378. def test_results(self):
  379. """
  380. Running a suite in which an entire class is marked as expected to fail
  381. produces a successful result with no recorded errors, failures, or
  382. skips, all methods which fail and were expected to fail recorded as
  383. C{expectedFailures}, and all methods which pass but which were expected
  384. to fail recorded as C{unexpectedSuccesses}. Additionally, no tests are
  385. recorded as successes.
  386. """
  387. self.suite(self.reporter)
  388. self.assertTrue(self.reporter.wasSuccessful())
  389. self.assertEqual(self.reporter.errors, [])
  390. self.assertEqual(self.reporter.failures, [])
  391. self.assertEqual(self.reporter.skips, [])
  392. self.assertEqual(len(self.reporter.expectedFailures), 2)
  393. self.assertEqual(len(self.reporter.unexpectedSuccesses), 2)
  394. self.assertEqual(self.reporter.successes, 0)
  395. def test_expectedFailures(self):
  396. """
  397. Ensure that expected failures are handled properly.
  398. """
  399. self.suite(self.reporter)
  400. expectedReasons = ['method', 'class']
  401. reasonsGiven = [ r.reason
  402. for t, e, r in self.reporter.expectedFailures ]
  403. self.assertEqual(expectedReasons, reasonsGiven)
  404. def test_unexpectedSuccesses(self):
  405. """
  406. Ensure that unexpected successes are caught.
  407. """
  408. self.suite(self.reporter)
  409. expectedReasons = ['method', 'class']
  410. reasonsGiven = [ r.reason
  411. for t, r in self.reporter.unexpectedSuccesses ]
  412. self.assertEqual(expectedReasons, reasonsGiven)
  413. class SynchronousClassTodoTests(ClassTodoMixin, unittest.SynchronousTestCase):
  414. """
  415. Tests for the class-wide I{expected failure} features in the synchronous case.
  416. See: L{twisted.trial.test.test_tests.ClassTodoMixin}
  417. """
  418. TodoClass = namedAny('twisted.trial.test.skipping.SynchronousTodoClass')
  419. class AsynchronousClassTodoTests(ClassTodoMixin, unittest.TestCase):
  420. """
  421. Tests for the class-wide I{expected failure} features in the asynchronous case.
  422. See: L{twisted.trial.test.test_tests.ClassTodoMixin}
  423. """
  424. TodoClass = namedAny('twisted.trial.test.skipping.AsynchronousTodoClass')
  425. class StrictTodoMixin(ResultsTestMixin):
  426. """
  427. Tests for the I{expected failure} features of
  428. L{twisted.trial.unittest.TestCase} in which the exact failure which is
  429. expected is indicated.
  430. """
  431. def setUp(self):
  432. """
  433. Setup our test case
  434. """
  435. self.loadSuite(self.StrictTodo)
  436. def test_counting(self):
  437. """
  438. Assert there are seven test cases
  439. """
  440. self.assertCount(7)
  441. def test_results(self):
  442. """
  443. A test method which is marked as expected to fail with a particular
  444. exception is only counted as an expected failure if it does fail with
  445. that exception, not if it fails with some other exception.
  446. """
  447. self.suite(self.reporter)
  448. self.assertFalse(self.reporter.wasSuccessful())
  449. self.assertEqual(len(self.reporter.errors), 2)
  450. self.assertEqual(len(self.reporter.failures), 1)
  451. self.assertEqual(len(self.reporter.expectedFailures), 3)
  452. self.assertEqual(len(self.reporter.unexpectedSuccesses), 1)
  453. self.assertEqual(self.reporter.successes, 0)
  454. self.assertEqual(self.reporter.skips, [])
  455. def test_expectedFailures(self):
  456. """
  457. Ensure that expected failures are handled properly.
  458. """
  459. self.suite(self.reporter)
  460. expectedReasons = ['todo1', 'todo2', 'todo5']
  461. reasonsGotten = [ r.reason
  462. for t, e, r in self.reporter.expectedFailures ]
  463. self.assertEqual(expectedReasons, reasonsGotten)
  464. def test_unexpectedSuccesses(self):
  465. """
  466. Ensure that unexpected successes are caught.
  467. """
  468. self.suite(self.reporter)
  469. expectedReasons = [([RuntimeError], 'todo7')]
  470. reasonsGotten = [ (r.errors, r.reason)
  471. for t, r in self.reporter.unexpectedSuccesses ]
  472. self.assertEqual(expectedReasons, reasonsGotten)
  473. class SynchronousStrictTodoTests(StrictTodoMixin, unittest.SynchronousTestCase):
  474. """
  475. Tests for the expected failure case when the exact failure that is expected
  476. is indicated in the synchronous case
  477. See: L{twisted.trial.test.test_tests.StrictTodoMixin}
  478. """
  479. StrictTodo = namedAny('twisted.trial.test.skipping.SynchronousStrictTodo')
  480. class AsynchronousStrictTodoTests(StrictTodoMixin, unittest.TestCase):
  481. """
  482. Tests for the expected failure case when the exact failure that is expected
  483. is indicated in the asynchronous case
  484. See: L{twisted.trial.test.test_tests.StrictTodoMixin}
  485. """
  486. StrictTodo = namedAny('twisted.trial.test.skipping.AsynchronousStrictTodo')
  487. class ReactorCleanupTests(unittest.SynchronousTestCase):
  488. """
  489. Tests for cleanup and reporting of reactor event sources left behind by test
  490. methods.
  491. """
  492. def setUp(self):
  493. """
  494. Setup our test case
  495. """
  496. self.result = reporter.Reporter(NativeStringIO())
  497. self.loader = runner.TestLoader()
  498. def test_leftoverSockets(self):
  499. """
  500. Trial reports a L{util.DirtyReactorAggregateError} if a test leaves
  501. sockets behind.
  502. """
  503. suite = self.loader.loadByName(
  504. "twisted.trial.test.erroneous.SocketOpenTest.test_socketsLeftOpen")
  505. suite.run(self.result)
  506. self.assertFalse(self.result.wasSuccessful())
  507. # socket cleanup happens at end of class's tests.
  508. # all the tests in the class are successful, even if the suite
  509. # fails
  510. self.assertEqual(self.result.successes, 1)
  511. failure = self.result.errors[0][1]
  512. self.assertTrue(failure.check(util.DirtyReactorAggregateError))
  513. def test_leftoverPendingCalls(self):
  514. """
  515. Trial reports a L{util.DirtyReactorAggregateError} and fails the test
  516. if a test leaves a L{DelayedCall} hanging.
  517. """
  518. suite = erroneous.ReactorCleanupTests('test_leftoverPendingCalls')
  519. suite.run(self.result)
  520. self.assertFalse(self.result.wasSuccessful())
  521. failure = self.result.errors[0][1]
  522. self.assertEqual(self.result.successes, 0)
  523. self.assertTrue(failure.check(util.DirtyReactorAggregateError))
  524. class FixtureMixin(object):
  525. """
  526. Tests for broken fixture helper methods (e.g. setUp, tearDown).
  527. """
  528. def setUp(self):
  529. """
  530. Setup our test case
  531. """
  532. self.reporter = reporter.Reporter()
  533. self.loader = pyunit.TestLoader()
  534. def test_brokenSetUp(self):
  535. """
  536. When setUp fails, the error is recorded in the result object.
  537. """
  538. suite = self.loader.loadTestsFromTestCase(self.TestFailureInSetUp)
  539. suite.run(self.reporter)
  540. self.assertTrue(len(self.reporter.errors) > 0)
  541. self.assertIsInstance(
  542. self.reporter.errors[0][1].value, erroneous.FoolishError)
  543. self.assertEqual(0, self.reporter.successes)
  544. def test_brokenTearDown(self):
  545. """
  546. When tearDown fails, the error is recorded in the result object.
  547. """
  548. suite = self.loader.loadTestsFromTestCase(self.TestFailureInTearDown)
  549. suite.run(self.reporter)
  550. errors = self.reporter.errors
  551. self.assertTrue(len(errors) > 0)
  552. self.assertIsInstance(errors[0][1].value, erroneous.FoolishError)
  553. self.assertEqual(0, self.reporter.successes)
  554. class SynchronousFixtureTests(FixtureMixin, unittest.SynchronousTestCase):
  555. """
  556. Tests for broken fixture helper methods in the synchronous case
  557. See: L{twisted.trial.test.test_tests.FixtureMixin}
  558. """
  559. TestFailureInSetUp = namedAny(
  560. 'twisted.trial.test.erroneous.SynchronousTestFailureInSetUp')
  561. TestFailureInTearDown = namedAny(
  562. 'twisted.trial.test.erroneous.SynchronousTestFailureInTearDown')
  563. class AsynchronousFixtureTests(FixtureMixin, unittest.TestCase):
  564. """
  565. Tests for broken fixture helper methods in the asynchronous case
  566. See: L{twisted.trial.test.test_tests.FixtureMixin}
  567. """
  568. TestFailureInSetUp = namedAny(
  569. 'twisted.trial.test.erroneous.AsynchronousTestFailureInSetUp')
  570. TestFailureInTearDown = namedAny(
  571. 'twisted.trial.test.erroneous.AsynchronousTestFailureInTearDown')
  572. class AsynchronousSuppressionTests(SuppressionMixin, unittest.TestCase):
  573. """
  574. Tests for the warning suppression features of
  575. L{twisted.trial.unittest.TestCase}
  576. See L{twisted.trial.test.test_suppression.SuppressionMixin}
  577. """
  578. TestSetUpSuppression = namedAny(
  579. 'twisted.trial.test.suppression.AsynchronousTestSetUpSuppression')
  580. TestTearDownSuppression = namedAny(
  581. 'twisted.trial.test.suppression.AsynchronousTestTearDownSuppression')
  582. TestSuppression = namedAny(
  583. 'twisted.trial.test.suppression.AsynchronousTestSuppression')
  584. TestSuppression2 = namedAny(
  585. 'twisted.trial.test.suppression.AsynchronousTestSuppression2')
  586. class GCMixin(object):
  587. """
  588. I provide a few mock tests that log setUp, tearDown, test execution and
  589. garbage collection. I'm used to test whether gc.collect gets called.
  590. """
  591. class BasicTest(unittest.SynchronousTestCase):
  592. """
  593. Mock test to run.
  594. """
  595. def setUp(self):
  596. """
  597. Mock setUp
  598. """
  599. self._log('setUp')
  600. def test_foo(self):
  601. """
  602. Mock test case
  603. """
  604. self._log('test')
  605. def tearDown(self):
  606. """
  607. Mock tear tearDown
  608. """
  609. self._log('tearDown')
  610. def _log(self, msg):
  611. """
  612. Log function
  613. """
  614. self._collectCalled.append(msg)
  615. def collect(self):
  616. """Fake gc.collect"""
  617. self._log('collect')
  618. def setUp(self):
  619. """
  620. Setup our test case
  621. """
  622. self._collectCalled = []
  623. self.BasicTest._log = self._log
  624. self._oldCollect = gc.collect
  625. gc.collect = self.collect
  626. def tearDown(self):
  627. """
  628. Tear down the test
  629. """
  630. gc.collect = self._oldCollect
  631. class GarbageCollectionDefaultTests(GCMixin, unittest.SynchronousTestCase):
  632. """
  633. By default, tests should not force garbage collection.
  634. """
  635. def test_collectNotDefault(self):
  636. """
  637. By default, tests should not force garbage collection.
  638. """
  639. test = self.BasicTest('test_foo')
  640. result = reporter.TestResult()
  641. test.run(result)
  642. self.assertEqual(self._collectCalled, ['setUp', 'test', 'tearDown'])
  643. class GarbageCollectionTests(GCMixin, unittest.SynchronousTestCase):
  644. """
  645. Test that, when force GC, it works.
  646. """
  647. def test_collectCalled(self):
  648. """
  649. test gc.collect is called before and after each test.
  650. """
  651. test = GarbageCollectionTests.BasicTest('test_foo')
  652. test = _ForceGarbageCollectionDecorator(test)
  653. result = reporter.TestResult()
  654. test.run(result)
  655. self.assertEqual(
  656. self._collectCalled,
  657. ['collect', 'setUp', 'test', 'tearDown', 'collect'])
  658. class UnhandledDeferredTests(unittest.SynchronousTestCase):
  659. """
  660. Test what happens when we have an unhandled deferred left around after
  661. a test.
  662. """
  663. def setUp(self):
  664. """
  665. Setup our test case
  666. """
  667. from twisted.trial.test import weird
  668. # test_unhandledDeferred creates a cycle. we need explicit control of gc
  669. gc.disable()
  670. self.test1 = _ForceGarbageCollectionDecorator(
  671. weird.TestBleeding('test_unhandledDeferred'))
  672. def test_isReported(self):
  673. """
  674. Forcing garbage collection should cause unhandled Deferreds to be
  675. reported as errors.
  676. """
  677. result = reporter.TestResult()
  678. self.test1(result)
  679. self.assertEqual(len(result.errors), 1,
  680. 'Unhandled deferred passed without notice')
  681. def test_doesntBleed(self):
  682. """
  683. Forcing garbage collection in the test should mean that there are
  684. no unreachable cycles immediately after the test completes.
  685. """
  686. result = reporter.TestResult()
  687. self.test1(result)
  688. self.flushLoggedErrors() # test1 logs errors that get caught be us.
  689. # test1 created unreachable cycle.
  690. # it & all others should have been collected by now.
  691. if _PY3:
  692. n = len(gc.garbage)
  693. else:
  694. n = gc.collect()
  695. self.assertEqual(n, 0, 'unreachable cycle still existed')
  696. # check that last gc.collect didn't log more errors
  697. x = self.flushLoggedErrors()
  698. self.assertEqual(len(x), 0, 'Errors logged after gc.collect')
  699. def tearDown(self):
  700. """
  701. Tear down the test
  702. """
  703. gc.collect()
  704. gc.enable()
  705. self.flushLoggedErrors()
  706. class AddCleanupMixin(object):
  707. """
  708. Test the addCleanup method of TestCase.
  709. """
  710. def setUp(self):
  711. """
  712. Setup our test case
  713. """
  714. super(AddCleanupMixin, self).setUp()
  715. self.result = reporter.TestResult()
  716. self.test = self.AddCleanup()
  717. def test_addCleanupCalledIfSetUpFails(self):
  718. """
  719. Callables added with C{addCleanup} are run even if setUp fails.
  720. """
  721. self.test.setUp = self.test.brokenSetUp
  722. self.test.addCleanup(self.test.append, 'foo')
  723. self.test.run(self.result)
  724. self.assertEqual(['setUp', 'foo'], self.test.log)
  725. def test_addCleanupCalledIfSetUpSkips(self):
  726. """
  727. Callables added with C{addCleanup} are run even if setUp raises
  728. L{SkipTest}. This allows test authors to reliably provide clean up
  729. code using C{addCleanup}.
  730. """
  731. self.test.setUp = self.test.skippingSetUp
  732. self.test.addCleanup(self.test.append, 'foo')
  733. self.test.run(self.result)
  734. self.assertEqual(['setUp', 'foo'], self.test.log)
  735. def test_addCleanupCalledInReverseOrder(self):
  736. """
  737. Callables added with C{addCleanup} should be called before C{tearDown}
  738. in reverse order of addition.
  739. """
  740. self.test.addCleanup(self.test.append, "foo")
  741. self.test.addCleanup(self.test.append, 'bar')
  742. self.test.run(self.result)
  743. self.assertEqual(['setUp', 'runTest', 'bar', 'foo', 'tearDown'],
  744. self.test.log)
  745. def test_errorInCleanupIsCaptured(self):
  746. """
  747. Errors raised in cleanup functions should be treated like errors in
  748. C{tearDown}. They should be added as errors and fail the test. Skips,
  749. todos and failures are all treated as errors.
  750. """
  751. self.test.addCleanup(self.test.fail, 'foo')
  752. self.test.run(self.result)
  753. self.assertFalse(self.result.wasSuccessful())
  754. self.assertEqual(1, len(self.result.errors))
  755. [(test, error)] = self.result.errors
  756. self.assertEqual(test, self.test)
  757. self.assertEqual(error.getErrorMessage(), 'foo')
  758. def test_cleanupsContinueRunningAfterError(self):
  759. """
  760. If a cleanup raises an error then that does not stop the other
  761. cleanups from being run.
  762. """
  763. self.test.addCleanup(self.test.append, 'foo')
  764. self.test.addCleanup(self.test.fail, 'bar')
  765. self.test.run(self.result)
  766. self.assertEqual(['setUp', 'runTest', 'foo', 'tearDown'],
  767. self.test.log)
  768. self.assertEqual(1, len(self.result.errors))
  769. [(test, error)] = self.result.errors
  770. self.assertEqual(test, self.test)
  771. self.assertEqual(error.getErrorMessage(), 'bar')
  772. def test_multipleErrorsReported(self):
  773. """
  774. If more than one cleanup fails, then the test should fail with more
  775. than one error.
  776. """
  777. self.test.addCleanup(self.test.fail, 'foo')
  778. self.test.addCleanup(self.test.fail, 'bar')
  779. self.test.run(self.result)
  780. self.assertEqual(['setUp', 'runTest', 'tearDown'],
  781. self.test.log)
  782. self.assertEqual(2, len(self.result.errors))
  783. [(test1, error1), (test2, error2)] = self.result.errors
  784. self.assertEqual(test1, self.test)
  785. self.assertEqual(test2, self.test)
  786. self.assertEqual(error1.getErrorMessage(), 'bar')
  787. self.assertEqual(error2.getErrorMessage(), 'foo')
  788. class SynchronousAddCleanupTests(AddCleanupMixin, unittest.SynchronousTestCase):
  789. """
  790. Test the addCleanup method of TestCase in the synchronous case
  791. See: L{twisted.trial.test.test_tests.AddCleanupMixin}
  792. """
  793. AddCleanup = namedAny('twisted.trial.test.skipping.SynchronousAddCleanup')
  794. class AsynchronousAddCleanupTests(AddCleanupMixin, unittest.TestCase):
  795. """
  796. Test the addCleanup method of TestCase in the asynchronous case
  797. See: L{twisted.trial.test.test_tests.AddCleanupMixin}
  798. """
  799. AddCleanup = namedAny('twisted.trial.test.skipping.AsynchronousAddCleanup')
  800. def test_addCleanupWaitsForDeferreds(self):
  801. """
  802. If an added callable returns a L{Deferred}, then the test should wait
  803. until that L{Deferred} has fired before running the next cleanup
  804. method.
  805. """
  806. def cleanup(message):
  807. d = defer.Deferred()
  808. reactor.callLater(0, d.callback, message)
  809. return d.addCallback(self.test.append)
  810. self.test.addCleanup(self.test.append, 'foo')
  811. self.test.addCleanup(cleanup, 'bar')
  812. self.test.run(self.result)
  813. self.assertEqual(['setUp', 'runTest', 'bar', 'foo', 'tearDown'],
  814. self.test.log)
  815. class SuiteClearingMixin(object):
  816. """
  817. Tests for our extension that allows us to clear out a L{TestSuite}.
  818. """
  819. def test_clearSuite(self):
  820. """
  821. Calling L{_clearSuite} on a populated L{TestSuite} removes
  822. all tests.
  823. """
  824. suite = unittest.TestSuite()
  825. suite.addTest(self.TestCase())
  826. # Double check that the test suite actually has something in it.
  827. self.assertEqual(1, suite.countTestCases())
  828. _clearSuite(suite)
  829. self.assertEqual(0, suite.countTestCases())
  830. def test_clearPyunitSuite(self):
  831. """
  832. Calling L{_clearSuite} on a populated standard library
  833. L{TestSuite} removes all tests.
  834. This test is important since C{_clearSuite} operates by mutating
  835. internal variables.
  836. """
  837. pyunit = __import__('unittest')
  838. suite = pyunit.TestSuite()
  839. suite.addTest(self.TestCase())
  840. # Double check that the test suite actually has something in it.
  841. self.assertEqual(1, suite.countTestCases())
  842. _clearSuite(suite)
  843. self.assertEqual(0, suite.countTestCases())
  844. class SynchronousSuiteClearingTests(SuiteClearingMixin, unittest.SynchronousTestCase):
  845. """
  846. Tests for our extension that allows us to clear out a L{TestSuite} in the
  847. synchronous case.
  848. See L{twisted.trial.test.test_tests.SuiteClearingMixin}
  849. """
  850. TestCase = unittest.SynchronousTestCase
  851. class AsynchronousSuiteClearingTests(SuiteClearingMixin, unittest.TestCase):
  852. """
  853. Tests for our extension that allows us to clear out a L{TestSuite} in the
  854. asynchronous case.
  855. See L{twisted.trial.test.test_tests.SuiteClearingMixin}
  856. """
  857. TestCase = unittest.TestCase
  858. class TestDecoratorMixin(object):
  859. """
  860. Tests for our test decoration features.
  861. """
  862. def assertTestsEqual(self, observed, expected):
  863. """
  864. Assert that the given decorated tests are equal.
  865. """
  866. self.assertEqual(observed.__class__, expected.__class__,
  867. "Different class")
  868. observedOriginal = getattr(observed, '_originalTest', None)
  869. expectedOriginal = getattr(expected, '_originalTest', None)
  870. self.assertIdentical(observedOriginal, expectedOriginal)
  871. if observedOriginal is expectedOriginal is None:
  872. self.assertIdentical(observed, expected)
  873. def assertSuitesEqual(self, observed, expected):
  874. """
  875. Assert that the given test suites with decorated tests are equal.
  876. """
  877. self.assertEqual(observed.__class__, expected.__class__,
  878. "Different class")
  879. self.assertEqual(len(observed._tests), len(expected._tests),
  880. "Different number of tests.")
  881. for observedTest, expectedTest in zip(observed._tests,
  882. expected._tests):
  883. if getattr(observedTest, '_tests', None) is not None:
  884. self.assertSuitesEqual(observedTest, expectedTest)
  885. else:
  886. self.assertTestsEqual(observedTest, expectedTest)
  887. def test_usesAdaptedReporterWithRun(self):
  888. """
  889. For decorated tests, C{run} uses a result adapter that preserves the
  890. test decoration for calls to C{addError}, C{startTest} and the like.
  891. See L{reporter._AdaptedReporter}.
  892. """
  893. test = self.TestCase()
  894. decoratedTest = unittest.TestDecorator(test)
  895. # Move to top in ticket #5964:
  896. from twisted.trial.test.test_reporter import LoggingReporter
  897. result = LoggingReporter()
  898. decoratedTest.run(result)
  899. self.assertTestsEqual(result.test, decoratedTest)
  900. def test_usesAdaptedReporterWithCall(self):
  901. """
  902. For decorated tests, C{__call__} uses a result adapter that preserves
  903. the test decoration for calls to C{addError}, C{startTest} and the
  904. like.
  905. See L{reporter._AdaptedReporter}.
  906. """
  907. test = self.TestCase()
  908. decoratedTest = unittest.TestDecorator(test)
  909. # Move to top in ticket #5964:
  910. from twisted.trial.test.test_reporter import LoggingReporter
  911. result = LoggingReporter()
  912. decoratedTest(result)
  913. self.assertTestsEqual(result.test, decoratedTest)
  914. def test_decorateSingleTest(self):
  915. """
  916. Calling L{decorate} on a single test case returns the test case
  917. decorated with the provided decorator.
  918. """
  919. test = self.TestCase()
  920. decoratedTest = unittest.decorate(test, unittest.TestDecorator)
  921. self.assertTestsEqual(unittest.TestDecorator(test), decoratedTest)
  922. def test_decorateTestSuite(self):
  923. """
  924. Calling L{decorate} on a test suite will return a test suite with
  925. each test decorated with the provided decorator.
  926. """
  927. test = self.TestCase()
  928. suite = unittest.TestSuite([test])
  929. decoratedTest = unittest.decorate(suite, unittest.TestDecorator)
  930. self.assertSuitesEqual(
  931. decoratedTest, unittest.TestSuite([unittest.TestDecorator(test)]))
  932. def test_decorateInPlaceMutatesOriginal(self):
  933. """
  934. Calling L{decorate} on a test suite will mutate the original suite.
  935. """
  936. test = self.TestCase()
  937. suite = unittest.TestSuite([test])
  938. decoratedTest = unittest.decorate(
  939. suite, unittest.TestDecorator)
  940. self.assertSuitesEqual(
  941. decoratedTest, unittest.TestSuite([unittest.TestDecorator(test)]))
  942. self.assertSuitesEqual(
  943. suite, unittest.TestSuite([unittest.TestDecorator(test)]))
  944. def test_decorateTestSuiteReferences(self):
  945. """
  946. When decorating a test suite in-place, the number of references to the
  947. test objects in that test suite should stay the same.
  948. Previously, L{unittest.decorate} recreated a test suite, so the
  949. original suite kept references to the test objects. This test is here
  950. to ensure the problem doesn't reappear again.
  951. """
  952. getrefcount = getattr(sys, 'getrefcount', None)
  953. if getrefcount is None:
  954. raise unittest.SkipTest(
  955. "getrefcount not supported on this platform")
  956. test = self.TestCase()
  957. suite = unittest.TestSuite([test])
  958. count1 = getrefcount(test)
  959. unittest.decorate(suite, unittest.TestDecorator)
  960. count2 = getrefcount(test)
  961. self.assertEqual(count1, count2)
  962. def test_decorateNestedTestSuite(self):
  963. """
  964. Calling L{decorate} on a test suite with nested suites will return a
  965. test suite that maintains the same structure, but with all tests
  966. decorated.
  967. """
  968. test = self.TestCase()
  969. suite = unittest.TestSuite([unittest.TestSuite([test])])
  970. decoratedTest = unittest.decorate(suite, unittest.TestDecorator)
  971. expected = unittest.TestSuite(
  972. [unittest.TestSuite([unittest.TestDecorator(test)])])
  973. self.assertSuitesEqual(decoratedTest, expected)
  974. def test_decorateDecoratedSuite(self):
  975. """
  976. Calling L{decorate} on a test suite with already-decorated tests
  977. decorates all of the tests in the suite again.
  978. """
  979. test = self.TestCase()
  980. decoratedTest = unittest.decorate(test, unittest.TestDecorator)
  981. redecoratedTest = unittest.decorate(decoratedTest,
  982. unittest.TestDecorator)
  983. self.assertTestsEqual(redecoratedTest,
  984. unittest.TestDecorator(decoratedTest))
  985. def test_decoratePreservesSuite(self):
  986. """
  987. Tests can be in non-standard suites. L{decorate} preserves the
  988. non-standard suites when it decorates the tests.
  989. """
  990. test = self.TestCase()
  991. suite = runner.DestructiveTestSuite([test])
  992. decorated = unittest.decorate(suite, unittest.TestDecorator)
  993. self.assertSuitesEqual(
  994. decorated,
  995. runner.DestructiveTestSuite([unittest.TestDecorator(test)]))
  996. class SynchronousTestDecoratorTests(TestDecoratorMixin, unittest.SynchronousTestCase):
  997. """
  998. Tests for our test decoration features in the synchronous case.
  999. See L{twisted.trial.test.test_tests.TestDecoratorMixin}
  1000. """
  1001. TestCase = unittest.SynchronousTestCase
  1002. class AsynchronousTestDecoratorTests(TestDecoratorMixin, unittest.TestCase):
  1003. """
  1004. Tests for our test decoration features in the asynchronous case.
  1005. See L{twisted.trial.test.test_tests.TestDecoratorMixin}
  1006. """
  1007. TestCase = unittest.TestCase
  1008. class MonkeyPatchMixin(object):
  1009. """
  1010. Tests for the patch() helper method in L{unittest.TestCase}.
  1011. """
  1012. def setUp(self):
  1013. """
  1014. Setup our test case
  1015. """
  1016. self.originalValue = 'original'
  1017. self.patchedValue = 'patched'
  1018. self.objectToPatch = self.originalValue
  1019. self.test = self.TestCase()
  1020. def test_patch(self):
  1021. """
  1022. Calling C{patch()} on a test monkey patches the specified object and
  1023. attribute.
  1024. """
  1025. self.test.patch(self, 'objectToPatch', self.patchedValue)
  1026. self.assertEqual(self.objectToPatch, self.patchedValue)
  1027. def test_patchRestoredAfterRun(self):
  1028. """
  1029. Any monkey patches introduced by a test using C{patch()} are reverted
  1030. after the test has run.
  1031. """
  1032. self.test.patch(self, 'objectToPatch', self.patchedValue)
  1033. self.test.run(reporter.Reporter())
  1034. self.assertEqual(self.objectToPatch, self.originalValue)
  1035. def test_revertDuringTest(self):
  1036. """
  1037. C{patch()} return a L{monkey.MonkeyPatcher} object that can be used to
  1038. restore the original values before the end of the test.
  1039. """
  1040. patch = self.test.patch(self, 'objectToPatch', self.patchedValue)
  1041. patch.restore()
  1042. self.assertEqual(self.objectToPatch, self.originalValue)
  1043. def test_revertAndRepatch(self):
  1044. """
  1045. The returned L{monkey.MonkeyPatcher} object can re-apply the patch
  1046. during the test run.
  1047. """
  1048. patch = self.test.patch(self, 'objectToPatch', self.patchedValue)
  1049. patch.restore()
  1050. patch.patch()
  1051. self.assertEqual(self.objectToPatch, self.patchedValue)
  1052. def test_successivePatches(self):
  1053. """
  1054. Successive patches are applied and reverted just like a single patch.
  1055. """
  1056. self.test.patch(self, 'objectToPatch', self.patchedValue)
  1057. self.assertEqual(self.objectToPatch, self.patchedValue)
  1058. self.test.patch(self, 'objectToPatch', 'second value')
  1059. self.assertEqual(self.objectToPatch, 'second value')
  1060. self.test.run(reporter.Reporter())
  1061. self.assertEqual(self.objectToPatch, self.originalValue)
  1062. class SynchronousMonkeyPatchTests(MonkeyPatchMixin, unittest.SynchronousTestCase):
  1063. """
  1064. Tests for the patch() helper method in the synchronous case.
  1065. See L{twisted.trial.test.test_tests.MonkeyPatchMixin}
  1066. """
  1067. TestCase = unittest.SynchronousTestCase
  1068. class AsynchronousMonkeyPatchTests(MonkeyPatchMixin, unittest.TestCase):
  1069. """
  1070. Tests for the patch() helper method in the asynchronous case.
  1071. See L{twisted.trial.test.test_tests.MonkeyPatchMixin}
  1072. """
  1073. TestCase = unittest.TestCase
  1074. class IterateTestsMixin(object):
  1075. """
  1076. L{_iterateTests} returns a list of all test cases in a test suite or test
  1077. case.
  1078. """
  1079. def test_iterateTestCase(self):
  1080. """
  1081. L{_iterateTests} on a single test case returns a list containing that
  1082. test case.
  1083. """
  1084. test = self.TestCase()
  1085. self.assertEqual([test], list(_iterateTests(test)))
  1086. def test_iterateSingletonTestSuite(self):
  1087. """
  1088. L{_iterateTests} on a test suite that contains a single test case
  1089. returns a list containing that test case.
  1090. """
  1091. test = self.TestCase()
  1092. suite = runner.TestSuite([test])
  1093. self.assertEqual([test], list(_iterateTests(suite)))
  1094. def test_iterateNestedTestSuite(self):
  1095. """
  1096. L{_iterateTests} returns tests that are in nested test suites.
  1097. """
  1098. test = self.TestCase()
  1099. suite = runner.TestSuite([runner.TestSuite([test])])
  1100. self.assertEqual([test], list(_iterateTests(suite)))
  1101. def test_iterateIsLeftToRightDepthFirst(self):
  1102. """
  1103. L{_iterateTests} returns tests in left-to-right, depth-first order.
  1104. """
  1105. test = self.TestCase()
  1106. suite = runner.TestSuite([runner.TestSuite([test]), self])
  1107. self.assertEqual([test, self], list(_iterateTests(suite)))
  1108. class SynchronousIterateTestsTests(IterateTestsMixin, unittest.SynchronousTestCase):
  1109. """
  1110. Check that L{_iterateTests} returns a list of all test cases in a test suite
  1111. or test case for synchronous tests.
  1112. See L{twisted.trial.test.test_tests.IterateTestsMixin}
  1113. """
  1114. TestCase = unittest.SynchronousTestCase
  1115. class AsynchronousIterateTestsTests(IterateTestsMixin, unittest.TestCase):
  1116. """
  1117. Check that L{_iterateTests} returns a list of all test cases in a test suite
  1118. or test case for asynchronous tests.
  1119. See L{twisted.trial.test.test_tests.IterateTestsMixin}
  1120. """
  1121. TestCase = unittest.TestCase
  1122. class TrialGeneratorFunctionTests(unittest.SynchronousTestCase):
  1123. """
  1124. Tests for generator function methods in test cases.
  1125. """
  1126. def test_errorOnGeneratorFunction(self):
  1127. """
  1128. In a TestCase, a test method which is a generator function is reported
  1129. as an error, as such a method will never run assertions.
  1130. """
  1131. class GeneratorTestCase(unittest.TestCase):
  1132. """
  1133. A fake TestCase for testing purposes.
  1134. """
  1135. def test_generator(self):
  1136. """
  1137. A method which is also a generator function, for testing
  1138. purposes.
  1139. """
  1140. self.fail('this should never be reached')
  1141. yield
  1142. testCase = GeneratorTestCase('test_generator')
  1143. result = reporter.TestResult()
  1144. testCase.run(result)
  1145. self.assertEqual(len(result.failures), 0)
  1146. self.assertEqual(len(result.errors), 1)
  1147. self.assertIn("GeneratorTestCase.test_generator",
  1148. result.errors[0][1].value.args[0])
  1149. self.assertIn("GeneratorTestCase testMethod=test_generator",
  1150. result.errors[0][1].value.args[0])
  1151. self.assertIn("is a generator function and therefore will never run",
  1152. result.errors[0][1].value.args[0])
  1153. def test_synchronousTestCaseErrorOnGeneratorFunction(self):
  1154. """
  1155. In a SynchronousTestCase, a test method which is a generator function
  1156. is reported as an error, as such a method will never run assertions.
  1157. """
  1158. class GeneratorSynchronousTestCase(unittest.SynchronousTestCase):
  1159. """
  1160. A fake SynchronousTestCase for testing purposes.
  1161. """
  1162. def test_generator(self):
  1163. """
  1164. A method which is also a generator function, for testing
  1165. purposes.
  1166. """
  1167. self.fail('this should never be reached')
  1168. yield
  1169. testCase = GeneratorSynchronousTestCase('test_generator')
  1170. result = reporter.TestResult()
  1171. testCase.run(result)
  1172. self.assertEqual(len(result.failures), 0)
  1173. self.assertEqual(len(result.errors), 1)
  1174. self.assertIn("GeneratorSynchronousTestCase.test_generator",
  1175. result.errors[0][1].value.args[0])
  1176. self.assertIn("GeneratorSynchronousTestCase testMethod=test_generator",
  1177. result.errors[0][1].value.args[0])
  1178. self.assertIn("is a generator function and therefore will never run",
  1179. result.errors[0][1].value.args[0])