test_script.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. from __future__ import absolute_import, division
  4. import gc
  5. import re
  6. import sys
  7. import textwrap
  8. import types
  9. from twisted.python import util
  10. from twisted.python.compat import NativeStringIO
  11. from twisted.python.filepath import FilePath
  12. from twisted.python.usage import UsageError
  13. from twisted.scripts import trial
  14. from twisted.trial import unittest
  15. from twisted.trial._dist.disttrial import DistTrialRunner
  16. from twisted.trial.runner import TestLoader
  17. from twisted.trial.runner import TrialRunner, TestSuite, DestructiveTestSuite
  18. from twisted.trial.test.test_loader import testNames
  19. pyunit = __import__('unittest')
  20. def sibpath(filename):
  21. """
  22. For finding files in twisted/trial/test
  23. """
  24. return util.sibpath(__file__, filename)
  25. class ForceGarbageCollectionTests(unittest.SynchronousTestCase):
  26. """
  27. Tests for the --force-gc option.
  28. """
  29. def setUp(self):
  30. self.config = trial.Options()
  31. self.log = []
  32. self.patch(gc, 'collect', self.collect)
  33. test = pyunit.FunctionTestCase(self.simpleTest)
  34. self.test = TestSuite([test, test])
  35. def simpleTest(self):
  36. """
  37. A simple test method that records that it was run.
  38. """
  39. self.log.append('test')
  40. def collect(self):
  41. """
  42. A replacement for gc.collect that logs calls to itself.
  43. """
  44. self.log.append('collect')
  45. def makeRunner(self):
  46. """
  47. Return a L{TrialRunner} object that is safe to use in tests.
  48. """
  49. runner = trial._makeRunner(self.config)
  50. runner.stream = NativeStringIO()
  51. return runner
  52. def test_forceGc(self):
  53. """
  54. Passing the --force-gc option to the trial script forces the garbage
  55. collector to run before and after each test.
  56. """
  57. self.config['force-gc'] = True
  58. self.config.postOptions()
  59. runner = self.makeRunner()
  60. runner.run(self.test)
  61. self.assertEqual(self.log, ['collect', 'test', 'collect',
  62. 'collect', 'test', 'collect'])
  63. def test_unforceGc(self):
  64. """
  65. By default, no garbage collection is forced.
  66. """
  67. self.config.postOptions()
  68. runner = self.makeRunner()
  69. runner.run(self.test)
  70. self.assertEqual(self.log, ['test', 'test'])
  71. class SuiteUsedTests(unittest.SynchronousTestCase):
  72. """
  73. Check the category of tests suite used by the loader.
  74. """
  75. def setUp(self):
  76. """
  77. Create a trial configuration object.
  78. """
  79. self.config = trial.Options()
  80. def test_defaultSuite(self):
  81. """
  82. By default, the loader should use L{DestructiveTestSuite}
  83. """
  84. loader = trial._getLoader(self.config)
  85. self.assertEqual(loader.suiteFactory, DestructiveTestSuite)
  86. def test_untilFailureSuite(self):
  87. """
  88. The C{until-failure} configuration uses the L{TestSuite} to keep
  89. instances alive across runs.
  90. """
  91. self.config['until-failure'] = True
  92. loader = trial._getLoader(self.config)
  93. self.assertEqual(loader.suiteFactory, TestSuite)
  94. class TestModuleTests(unittest.SynchronousTestCase):
  95. def setUp(self):
  96. self.config = trial.Options()
  97. def tearDown(self):
  98. self.config = None
  99. def test_testNames(self):
  100. """
  101. Check that the testNames helper method accurately collects the
  102. names of tests in suite.
  103. """
  104. self.assertEqual(testNames(self), [self.id()])
  105. def assertSuitesEqual(self, test1, names):
  106. loader = TestLoader()
  107. names1 = testNames(test1)
  108. names2 = testNames(TestSuite(map(loader.loadByName, names)))
  109. names1.sort()
  110. names2.sort()
  111. self.assertEqual(names1, names2)
  112. def test_baseState(self):
  113. self.assertEqual(0, len(self.config['tests']))
  114. def test_testmoduleOnModule(self):
  115. """
  116. Check that --testmodule loads a suite which contains the tests
  117. referred to in test-case-name inside its parameter.
  118. """
  119. self.config.opt_testmodule(sibpath('moduletest.py'))
  120. self.assertSuitesEqual(trial._getSuite(self.config),
  121. ['twisted.trial.test.test_log'])
  122. def test_testmoduleTwice(self):
  123. """
  124. When the same module is specified with two --testmodule flags, it
  125. should only appear once in the suite.
  126. """
  127. self.config.opt_testmodule(sibpath('moduletest.py'))
  128. self.config.opt_testmodule(sibpath('moduletest.py'))
  129. self.assertSuitesEqual(trial._getSuite(self.config),
  130. ['twisted.trial.test.test_log'])
  131. def test_testmoduleOnSourceAndTarget(self):
  132. """
  133. If --testmodule is specified twice, once for module A and once for
  134. a module which refers to module A, then make sure module A is only
  135. added once.
  136. """
  137. self.config.opt_testmodule(sibpath('moduletest.py'))
  138. self.config.opt_testmodule(sibpath('test_log.py'))
  139. self.assertSuitesEqual(trial._getSuite(self.config),
  140. ['twisted.trial.test.test_log'])
  141. def test_testmoduleOnSelfModule(self):
  142. """
  143. When given a module that refers to *itself* in the test-case-name
  144. variable, check that --testmodule only adds the tests once.
  145. """
  146. self.config.opt_testmodule(sibpath('moduleself.py'))
  147. self.assertSuitesEqual(trial._getSuite(self.config),
  148. ['twisted.trial.test.moduleself'])
  149. def test_testmoduleOnScript(self):
  150. """
  151. Check that --testmodule loads tests referred to in test-case-name
  152. buffer variables.
  153. """
  154. self.config.opt_testmodule(sibpath('scripttest.py'))
  155. self.assertSuitesEqual(trial._getSuite(self.config),
  156. ['twisted.trial.test.test_log',
  157. 'twisted.trial.test.test_runner'])
  158. def test_testmoduleOnNonexistentFile(self):
  159. """
  160. Check that --testmodule displays a meaningful error message when
  161. passed a non-existent filename.
  162. """
  163. buffy = NativeStringIO()
  164. stderr, sys.stderr = sys.stderr, buffy
  165. filename = 'test_thisbetternoteverexist.py'
  166. try:
  167. self.config.opt_testmodule(filename)
  168. self.assertEqual(0, len(self.config['tests']))
  169. self.assertEqual("File %r doesn't exist\n" % (filename,),
  170. buffy.getvalue())
  171. finally:
  172. sys.stderr = stderr
  173. def test_testmoduleOnEmptyVars(self):
  174. """
  175. Check that --testmodule adds no tests to the suite for modules
  176. which lack test-case-name buffer variables.
  177. """
  178. self.config.opt_testmodule(sibpath('novars.py'))
  179. self.assertEqual(0, len(self.config['tests']))
  180. def test_testmoduleOnModuleName(self):
  181. """
  182. Check that --testmodule does *not* support module names as arguments
  183. and that it displays a meaningful error message.
  184. """
  185. buffy = NativeStringIO()
  186. stderr, sys.stderr = sys.stderr, buffy
  187. moduleName = 'twisted.trial.test.test_script'
  188. try:
  189. self.config.opt_testmodule(moduleName)
  190. self.assertEqual(0, len(self.config['tests']))
  191. self.assertEqual("File %r doesn't exist\n" % (moduleName,),
  192. buffy.getvalue())
  193. finally:
  194. sys.stderr = stderr
  195. def test_parseLocalVariable(self):
  196. declaration = '-*- test-case-name: twisted.trial.test.test_tests -*-'
  197. localVars = trial._parseLocalVariables(declaration)
  198. self.assertEqual({'test-case-name':
  199. 'twisted.trial.test.test_tests'},
  200. localVars)
  201. def test_trailingSemicolon(self):
  202. declaration = '-*- test-case-name: twisted.trial.test.test_tests; -*-'
  203. localVars = trial._parseLocalVariables(declaration)
  204. self.assertEqual({'test-case-name':
  205. 'twisted.trial.test.test_tests'},
  206. localVars)
  207. def test_parseLocalVariables(self):
  208. declaration = ('-*- test-case-name: twisted.trial.test.test_tests; '
  209. 'foo: bar -*-')
  210. localVars = trial._parseLocalVariables(declaration)
  211. self.assertEqual({'test-case-name':
  212. 'twisted.trial.test.test_tests',
  213. 'foo': 'bar'},
  214. localVars)
  215. def test_surroundingGuff(self):
  216. declaration = ('## -*- test-case-name: '
  217. 'twisted.trial.test.test_tests -*- #')
  218. localVars = trial._parseLocalVariables(declaration)
  219. self.assertEqual({'test-case-name':
  220. 'twisted.trial.test.test_tests'},
  221. localVars)
  222. def test_invalidLine(self):
  223. self.assertRaises(ValueError, trial._parseLocalVariables,
  224. 'foo')
  225. def test_invalidDeclaration(self):
  226. self.assertRaises(ValueError, trial._parseLocalVariables,
  227. '-*- foo -*-')
  228. self.assertRaises(ValueError, trial._parseLocalVariables,
  229. '-*- foo: bar; qux -*-')
  230. self.assertRaises(ValueError, trial._parseLocalVariables,
  231. '-*- foo: bar: baz; qux: qax -*-')
  232. def test_variablesFromFile(self):
  233. localVars = trial.loadLocalVariables(sibpath('moduletest.py'))
  234. self.assertEqual({'test-case-name':
  235. 'twisted.trial.test.test_log'},
  236. localVars)
  237. def test_noVariablesInFile(self):
  238. localVars = trial.loadLocalVariables(sibpath('novars.py'))
  239. self.assertEqual({}, localVars)
  240. def test_variablesFromScript(self):
  241. localVars = trial.loadLocalVariables(sibpath('scripttest.py'))
  242. self.assertEqual(
  243. {'test-case-name': ('twisted.trial.test.test_log,'
  244. 'twisted.trial.test.test_runner')},
  245. localVars)
  246. def test_getTestModules(self):
  247. modules = trial.getTestModules(sibpath('moduletest.py'))
  248. self.assertEqual(modules, ['twisted.trial.test.test_log'])
  249. def test_getTestModules_noVars(self):
  250. modules = trial.getTestModules(sibpath('novars.py'))
  251. self.assertEqual(len(modules), 0)
  252. def test_getTestModules_multiple(self):
  253. modules = trial.getTestModules(sibpath('scripttest.py'))
  254. self.assertEqual(set(modules),
  255. set(['twisted.trial.test.test_log',
  256. 'twisted.trial.test.test_runner']))
  257. def test_looksLikeTestModule(self):
  258. for filename in ['test_script.py', 'twisted/trial/test/test_script.py']:
  259. self.assertTrue(trial.isTestFile(filename),
  260. "%r should be a test file" % (filename,))
  261. for filename in ['twisted/trial/test/moduletest.py',
  262. sibpath('scripttest.py'), sibpath('test_foo.bat')]:
  263. self.assertFalse(trial.isTestFile(filename),
  264. "%r should *not* be a test file" % (filename,))
  265. class WithoutModuleTests(unittest.SynchronousTestCase):
  266. """
  267. Test the C{without-module} flag.
  268. """
  269. def setUp(self):
  270. """
  271. Create a L{trial.Options} object to be used in the tests, and save
  272. C{sys.modules}.
  273. """
  274. self.config = trial.Options()
  275. self.savedModules = dict(sys.modules)
  276. def tearDown(self):
  277. """
  278. Restore C{sys.modules}.
  279. """
  280. for module in ('imaplib', 'smtplib'):
  281. if module in self.savedModules:
  282. sys.modules[module] = self.savedModules[module]
  283. else:
  284. sys.modules.pop(module, None)
  285. def _checkSMTP(self):
  286. """
  287. Try to import the C{smtplib} module, and return it.
  288. """
  289. import smtplib
  290. return smtplib
  291. def _checkIMAP(self):
  292. """
  293. Try to import the C{imaplib} module, and return it.
  294. """
  295. import imaplib
  296. return imaplib
  297. def test_disableOneModule(self):
  298. """
  299. Check that after disabling a module, it can't be imported anymore.
  300. """
  301. self.config.parseOptions(["--without-module", "smtplib"])
  302. self.assertRaises(ImportError, self._checkSMTP)
  303. # Restore sys.modules
  304. del sys.modules["smtplib"]
  305. # Then the function should succeed
  306. self.assertIsInstance(self._checkSMTP(), types.ModuleType)
  307. def test_disableMultipleModules(self):
  308. """
  309. Check that several modules can be disabled at once.
  310. """
  311. self.config.parseOptions(["--without-module", "smtplib,imaplib"])
  312. self.assertRaises(ImportError, self._checkSMTP)
  313. self.assertRaises(ImportError, self._checkIMAP)
  314. # Restore sys.modules
  315. del sys.modules["smtplib"]
  316. del sys.modules["imaplib"]
  317. # Then the functions should succeed
  318. self.assertIsInstance(self._checkSMTP(), types.ModuleType)
  319. self.assertIsInstance(self._checkIMAP(), types.ModuleType)
  320. def test_disableAlreadyImportedModule(self):
  321. """
  322. Disabling an already imported module should produce a warning.
  323. """
  324. self.assertIsInstance(self._checkSMTP(), types.ModuleType)
  325. self.assertWarns(RuntimeWarning,
  326. "Module 'smtplib' already imported, disabling anyway.",
  327. trial.__file__,
  328. self.config.parseOptions, ["--without-module", "smtplib"])
  329. self.assertRaises(ImportError, self._checkSMTP)
  330. class CoverageTests(unittest.SynchronousTestCase):
  331. """
  332. Tests for the I{coverage} option.
  333. """
  334. if getattr(sys, 'gettrace', None) is None:
  335. skip = (
  336. "Cannot test trace hook installation without inspection API.")
  337. def setUp(self):
  338. """
  339. Arrange for the current trace hook to be restored when the
  340. test is complete.
  341. """
  342. self.addCleanup(sys.settrace, sys.gettrace())
  343. def test_tracerInstalled(self):
  344. """
  345. L{trial.Options} handles C{"--coverage"} by installing a trace
  346. hook to record coverage information.
  347. """
  348. options = trial.Options()
  349. options.parseOptions(["--coverage"])
  350. self.assertEqual(sys.gettrace(), options.tracer.globaltrace)
  351. def test_coverdirDefault(self):
  352. """
  353. L{trial.Options.coverdir} returns a L{FilePath} based on the default
  354. for the I{temp-directory} option if that option is not specified.
  355. """
  356. options = trial.Options()
  357. self.assertEqual(
  358. options.coverdir(),
  359. FilePath(".").descendant([options["temp-directory"], "coverage"]))
  360. def test_coverdirOverridden(self):
  361. """
  362. If a value is specified for the I{temp-directory} option,
  363. L{trial.Options.coverdir} returns a child of that path.
  364. """
  365. path = self.mktemp()
  366. options = trial.Options()
  367. options.parseOptions(["--temp-directory", path])
  368. self.assertEqual(
  369. options.coverdir(), FilePath(path).child("coverage"))
  370. class OptionsTests(unittest.TestCase):
  371. """
  372. Tests for L{trial.Options}.
  373. """
  374. def setUp(self):
  375. """
  376. Build an L{Options} object to be used in the tests.
  377. """
  378. self.options = trial.Options()
  379. def test_getWorkerArguments(self):
  380. """
  381. C{_getWorkerArguments} discards options like C{random} as they only
  382. matter in the manager, and forwards options like C{recursionlimit} or
  383. C{disablegc}.
  384. """
  385. self.addCleanup(sys.setrecursionlimit, sys.getrecursionlimit())
  386. if gc.isenabled():
  387. self.addCleanup(gc.enable)
  388. self.options.parseOptions(["--recursionlimit", "2000", "--random",
  389. "4", "--disablegc"])
  390. args = self.options._getWorkerArguments()
  391. self.assertIn("--disablegc", args)
  392. args.remove("--disablegc")
  393. self.assertEqual(["--recursionlimit", "2000"], args)
  394. def test_jobsConflictWithDebug(self):
  395. """
  396. C{parseOptions} raises a C{UsageError} when C{--debug} is passed along
  397. C{--jobs} as it's not supported yet.
  398. @see: U{http://twistedmatrix.com/trac/ticket/5825}
  399. """
  400. error = self.assertRaises(
  401. UsageError, self.options.parseOptions, ["--jobs", "4", "--debug"])
  402. self.assertEqual("You can't specify --debug when using --jobs",
  403. str(error))
  404. def test_jobsConflictWithProfile(self):
  405. """
  406. C{parseOptions} raises a C{UsageError} when C{--profile} is passed
  407. along C{--jobs} as it's not supported yet.
  408. @see: U{http://twistedmatrix.com/trac/ticket/5827}
  409. """
  410. error = self.assertRaises(
  411. UsageError, self.options.parseOptions,
  412. ["--jobs", "4", "--profile"])
  413. self.assertEqual("You can't specify --profile when using --jobs",
  414. str(error))
  415. def test_jobsConflictWithDebugStackTraces(self):
  416. """
  417. C{parseOptions} raises a C{UsageError} when C{--debug-stacktraces} is
  418. passed along C{--jobs} as it's not supported yet.
  419. @see: U{http://twistedmatrix.com/trac/ticket/5826}
  420. """
  421. error = self.assertRaises(
  422. UsageError, self.options.parseOptions,
  423. ["--jobs", "4", "--debug-stacktraces"])
  424. self.assertEqual(
  425. "You can't specify --debug-stacktraces when using --jobs",
  426. str(error))
  427. def test_jobsConflictWithExitFirst(self):
  428. """
  429. C{parseOptions} raises a C{UsageError} when C{--exitfirst} is passed
  430. along C{--jobs} as it's not supported yet.
  431. @see: U{http://twistedmatrix.com/trac/ticket/6436}
  432. """
  433. error = self.assertRaises(
  434. UsageError, self.options.parseOptions,
  435. ["--jobs", "4", "--exitfirst"])
  436. self.assertEqual(
  437. "You can't specify --exitfirst when using --jobs",
  438. str(error))
  439. def test_orderConflictWithRandom(self):
  440. """
  441. C{parseOptions} raises a C{UsageError} when C{--order} is passed along
  442. with C{--random}.
  443. """
  444. error = self.assertRaises(
  445. UsageError,
  446. self.options.parseOptions,
  447. ["--order", "alphabetical", "--random", "1234"])
  448. self.assertEqual("You can't specify --random when using --order",
  449. str(error))
  450. class MakeRunnerTests(unittest.TestCase):
  451. """
  452. Tests for the L{_makeRunner} helper.
  453. """
  454. def setUp(self):
  455. self.options = trial.Options()
  456. def test_jobs(self):
  457. """
  458. L{_makeRunner} returns a L{DistTrialRunner} instance when the C{--jobs}
  459. option is passed, and passes the C{workerNumber} and C{workerArguments}
  460. parameters to it.
  461. """
  462. self.options.parseOptions(["--jobs", "4", "--force-gc"])
  463. runner = trial._makeRunner(self.options)
  464. self.assertIsInstance(runner, DistTrialRunner)
  465. self.assertEqual(4, runner._workerNumber)
  466. self.assertEqual(["--force-gc"], runner._workerArguments)
  467. def test_dryRunWithJobs(self):
  468. """
  469. L{_makeRunner} returns a L{TrialRunner} instance in C{DRY_RUN} mode
  470. when the C{--dry-run} option is passed, even if C{--jobs} is set.
  471. """
  472. self.options.parseOptions(["--jobs", "4", "--dry-run"])
  473. runner = trial._makeRunner(self.options)
  474. self.assertIsInstance(runner, TrialRunner)
  475. self.assertEqual(TrialRunner.DRY_RUN, runner.mode)
  476. def test_DebuggerNotFound(self):
  477. namedAny = trial.reflect.namedAny
  478. def namedAnyExceptdoNotFind(fqn):
  479. if fqn == "doNotFind":
  480. raise trial.reflect.ModuleNotFound(fqn)
  481. return namedAny(fqn)
  482. self.patch(trial.reflect, "namedAny", namedAnyExceptdoNotFind)
  483. options = trial.Options()
  484. options.parseOptions(["--debug", "--debugger", "doNotFind"])
  485. self.assertRaises(trial._DebuggerNotFound, trial._makeRunner, options)
  486. def test_exitfirst(self):
  487. """
  488. Passing C{--exitfirst} wraps the reporter with a
  489. L{reporter._ExitWrapper} that stops on any non-success.
  490. """
  491. self.options.parseOptions(["--exitfirst"])
  492. runner = trial._makeRunner(self.options)
  493. self.assertTrue(runner._exitFirst)
  494. class RunTests(unittest.TestCase):
  495. """
  496. Tests for the L{run} function.
  497. """
  498. def setUp(self):
  499. # don't re-parse cmdline options, because if --reactor was passed to
  500. # the test run trial will try to restart the (already running) reactor
  501. self.patch(trial.Options, "parseOptions", lambda self: None)
  502. def test_debuggerNotFound(self):
  503. """
  504. When a debugger is not found, an error message is printed to the user.
  505. """
  506. def _makeRunner(*args, **kwargs):
  507. raise trial._DebuggerNotFound('foo')
  508. self.patch(trial, "_makeRunner", _makeRunner)
  509. try:
  510. trial.run()
  511. except SystemExit as e:
  512. self.assertIn("foo", str(e))
  513. else:
  514. self.fail("Should have exited due to non-existent debugger!")
  515. class TestArgumentOrderTests(unittest.TestCase):
  516. """
  517. Tests for the order-preserving behavior on provided command-line tests.
  518. """
  519. def setUp(self):
  520. self.config = trial.Options()
  521. self.loader = TestLoader()
  522. def test_preserveArgumentOrder(self):
  523. """
  524. Multiple tests passed on the command line are not reordered.
  525. """
  526. tests = [
  527. "twisted.trial.test.test_tests",
  528. "twisted.trial.test.test_assertions",
  529. "twisted.trial.test.test_deferred",
  530. ]
  531. self.config.parseOptions(tests)
  532. suite = trial._getSuite(self.config)
  533. names = testNames(suite)
  534. expectedSuite = TestSuite(map(self.loader.loadByName, tests))
  535. expectedNames = testNames(expectedSuite)
  536. self.assertEqual(names, expectedNames)
  537. class OrderTests(unittest.TestCase):
  538. """
  539. Tests for the --order option.
  540. """
  541. def setUp(self):
  542. self.config = trial.Options()
  543. def test_alphabetical(self):
  544. """
  545. --order=alphabetical causes trial to run tests alphabetically within
  546. each test case.
  547. """
  548. self.config.parseOptions([
  549. "--order", "alphabetical",
  550. "twisted.trial.test.ordertests.FooTest"])
  551. loader = trial._getLoader(self.config)
  552. suite = loader.loadByNames(self.config['tests'])
  553. self.assertEqual(
  554. testNames(suite), [
  555. 'twisted.trial.test.ordertests.FooTest.test_first',
  556. 'twisted.trial.test.ordertests.FooTest.test_fourth',
  557. 'twisted.trial.test.ordertests.FooTest.test_second',
  558. 'twisted.trial.test.ordertests.FooTest.test_third'])
  559. def test_alphabeticalModule(self):
  560. """
  561. --order=alphabetical causes trial to run test classes within a given
  562. module alphabetically.
  563. """
  564. self.config.parseOptions([
  565. "--order", "alphabetical", "twisted.trial.test.ordertests"])
  566. loader = trial._getLoader(self.config)
  567. suite = loader.loadByNames(self.config['tests'])
  568. self.assertEqual(
  569. testNames(suite), [
  570. 'twisted.trial.test.ordertests.BarTest.test_bar',
  571. 'twisted.trial.test.ordertests.BazTest.test_baz',
  572. 'twisted.trial.test.ordertests.FooTest.test_first',
  573. 'twisted.trial.test.ordertests.FooTest.test_fourth',
  574. 'twisted.trial.test.ordertests.FooTest.test_second',
  575. 'twisted.trial.test.ordertests.FooTest.test_third'])
  576. def test_alphabeticalPackage(self):
  577. """
  578. --order=alphabetical causes trial to run test modules within a given
  579. package alphabetically, with tests within each module alphabetized.
  580. """
  581. self.config.parseOptions([
  582. "--order", "alphabetical", "twisted.trial.test"])
  583. loader = trial._getLoader(self.config)
  584. suite = loader.loadByNames(self.config['tests'])
  585. names = testNames(suite)
  586. self.assertTrue(names, msg="Failed to load any tests!")
  587. self.assertEqual(names, sorted(names))
  588. def test_toptobottom(self):
  589. """
  590. --order=toptobottom causes trial to run test methods within a given
  591. test case from top to bottom as they are defined in the body of the
  592. class.
  593. """
  594. self.config.parseOptions([
  595. "--order", "toptobottom",
  596. "twisted.trial.test.ordertests.FooTest"])
  597. loader = trial._getLoader(self.config)
  598. suite = loader.loadByNames(self.config['tests'])
  599. self.assertEqual(
  600. testNames(suite), [
  601. 'twisted.trial.test.ordertests.FooTest.test_first',
  602. 'twisted.trial.test.ordertests.FooTest.test_second',
  603. 'twisted.trial.test.ordertests.FooTest.test_third',
  604. 'twisted.trial.test.ordertests.FooTest.test_fourth'])
  605. def test_toptobottomModule(self):
  606. """
  607. --order=toptobottom causes trial to run test classes within a given
  608. module from top to bottom as they are defined in the module's source.
  609. """
  610. self.config.parseOptions([
  611. "--order", "toptobottom", "twisted.trial.test.ordertests"])
  612. loader = trial._getLoader(self.config)
  613. suite = loader.loadByNames(self.config['tests'])
  614. self.assertEqual(
  615. testNames(suite), [
  616. 'twisted.trial.test.ordertests.FooTest.test_first',
  617. 'twisted.trial.test.ordertests.FooTest.test_second',
  618. 'twisted.trial.test.ordertests.FooTest.test_third',
  619. 'twisted.trial.test.ordertests.FooTest.test_fourth',
  620. 'twisted.trial.test.ordertests.BazTest.test_baz',
  621. 'twisted.trial.test.ordertests.BarTest.test_bar'])
  622. def test_toptobottomPackage(self):
  623. """
  624. --order=toptobottom causes trial to run test modules within a given
  625. package alphabetically, with tests within each module run top to
  626. bottom.
  627. """
  628. self.config.parseOptions([
  629. "--order", "toptobottom", "twisted.trial.test"])
  630. loader = trial._getLoader(self.config)
  631. suite = loader.loadByNames(self.config['tests'])
  632. names = testNames(suite)
  633. # twisted.trial.test.test_module, so split and key on the first 4 to
  634. # get stable alphabetical sort on those
  635. self.assertEqual(
  636. names, sorted(names, key=lambda name : name.split(".")[:4]),
  637. )
  638. def test_toptobottomMissingSource(self):
  639. """
  640. --order=toptobottom detects the source line of methods from modules
  641. whose source file is missing.
  642. """
  643. tempdir = self.mktemp()
  644. package = FilePath(tempdir).child('twisted_toptobottom_temp')
  645. package.makedirs()
  646. package.child('__init__.py').setContent(b'')
  647. package.child('test_missing.py').setContent(textwrap.dedent('''
  648. from twisted.trial.unittest import TestCase
  649. class TestMissing(TestCase):
  650. def test_second(self): pass
  651. def test_third(self): pass
  652. def test_fourth(self): pass
  653. def test_first(self): pass
  654. ''').encode('utf8'))
  655. pathEntry = package.parent().path
  656. sys.path.insert(0, pathEntry)
  657. self.addCleanup(sys.path.remove, pathEntry)
  658. from twisted_toptobottom_temp import test_missing
  659. self.addCleanup(sys.modules.pop, 'twisted_toptobottom_temp')
  660. self.addCleanup(sys.modules.pop, test_missing.__name__)
  661. package.child('test_missing.py').remove()
  662. self.config.parseOptions([
  663. "--order", "toptobottom", "twisted.trial.test.ordertests"])
  664. loader = trial._getLoader(self.config)
  665. suite = loader.loadModule(test_missing)
  666. self.assertEqual(
  667. testNames(suite), [
  668. 'twisted_toptobottom_temp.test_missing.TestMissing.test_second',
  669. 'twisted_toptobottom_temp.test_missing.TestMissing.test_third',
  670. 'twisted_toptobottom_temp.test_missing.TestMissing.test_fourth',
  671. 'twisted_toptobottom_temp.test_missing.TestMissing.test_first'])
  672. def test_unknownOrder(self):
  673. """
  674. An unknown order passed to --order raises a L{UsageError}.
  675. """
  676. self.assertRaises(
  677. UsageError, self.config.parseOptions, ["--order", "I don't exist"])
  678. class HelpOrderTests(unittest.TestCase):
  679. """
  680. Tests for the --help-orders flag.
  681. """
  682. def test_help_ordersPrintsSynopsisAndQuits(self):
  683. """
  684. --help-orders prints each of the available orders and then exits.
  685. """
  686. self.patch(sys, "stdout", NativeStringIO())
  687. exc = self.assertRaises(
  688. SystemExit, trial.Options().parseOptions, ["--help-orders"])
  689. self.assertEqual(exc.code, 0)
  690. output = sys.stdout.getvalue()
  691. msg = "%r with its description not properly described in %r"
  692. for orderName, (orderDesc, _) in trial._runOrders.items():
  693. match = re.search(
  694. "%s.*%s" % (re.escape(orderName), re.escape(orderDesc)),
  695. output,
  696. )
  697. self.assertTrue(match, msg=msg % (orderName, output))