test_loader.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for loading tests by name.
  5. """
  6. from __future__ import absolute_import, division
  7. import os
  8. import sys
  9. import unittest as pyunit
  10. from hashlib import md5
  11. from twisted.python import util, filepath
  12. from twisted.trial.test import packages
  13. from twisted.trial import runner, reporter, unittest
  14. from twisted.trial.itrial import ITestCase
  15. from twisted.trial._asyncrunner import _iterateTests
  16. from twisted.python.modules import getModule
  17. from twisted.python.compat import _PY3
  18. def testNames(tests):
  19. """
  20. Return the id of each test within the given test suite or case.
  21. """
  22. names = []
  23. for test in _iterateTests(tests):
  24. names.append(test.id())
  25. return names
  26. class FinderTests(packages.PackageTest):
  27. """
  28. Tests for L{runner.TestLoader.findByName}.
  29. """
  30. def setUp(self):
  31. packages.PackageTest.setUp(self)
  32. self.loader = runner.TestLoader()
  33. def tearDown(self):
  34. packages.PackageTest.tearDown(self)
  35. def test_findPackage(self):
  36. sample1 = self.loader.findByName('twisted')
  37. import twisted as sample2
  38. self.assertEqual(sample1, sample2)
  39. def test_findModule(self):
  40. sample1 = self.loader.findByName('twisted.trial.test.sample')
  41. from twisted.trial.test import sample as sample2
  42. self.assertEqual(sample1, sample2)
  43. def test_findFile(self):
  44. path = util.sibpath(__file__, 'sample.py')
  45. sample1 = self.loader.findByName(path)
  46. from twisted.trial.test import sample as sample2
  47. self.assertEqual(sample1, sample2)
  48. def test_findObject(self):
  49. sample1 = self.loader.findByName('twisted.trial.test.sample.FooTest')
  50. from twisted.trial.test import sample
  51. self.assertEqual(sample.FooTest, sample1)
  52. if _PY3:
  53. # In Python 3, `findByName` returns full TestCases, not the objects
  54. # inside them. This because on Python 3, unbound methods don't exist,
  55. # so you can't simply make a TestCase after finding it -- it's easier
  56. # to just find it and put it in a TestCase immediately.
  57. _Py3SkipMsg = ("Not relevant on Python 3")
  58. test_findPackage.skip = _Py3SkipMsg
  59. test_findModule.skip = _Py3SkipMsg
  60. test_findFile.skip = _Py3SkipMsg
  61. test_findObject.skip = _Py3SkipMsg
  62. def test_findNonModule(self):
  63. self.assertRaises(AttributeError,
  64. self.loader.findByName,
  65. 'twisted.trial.test.nonexistent')
  66. def test_findNonPackage(self):
  67. self.assertRaises(ValueError,
  68. self.loader.findByName,
  69. 'nonextant')
  70. def test_findNonFile(self):
  71. path = util.sibpath(__file__, 'nonexistent.py')
  72. self.assertRaises(ValueError, self.loader.findByName, path)
  73. class FileTests(packages.SysPathManglingTest):
  74. """
  75. Tests for L{runner.filenameToModule}.
  76. """
  77. def test_notFile(self):
  78. """
  79. L{runner.filenameToModule} raises a C{ValueError} when a non-existing
  80. file is passed.
  81. """
  82. err = self.assertRaises(ValueError, runner.filenameToModule, 'it')
  83. self.assertEqual(str(err), "'it' doesn't exist")
  84. def test_moduleInPath(self):
  85. """
  86. If the file in question is a module on the Python path, then it should
  87. properly import and return that module.
  88. """
  89. sample1 = runner.filenameToModule(util.sibpath(__file__, 'sample.py'))
  90. from twisted.trial.test import sample as sample2
  91. self.assertEqual(sample2, sample1)
  92. def test_moduleNotInPath(self):
  93. """
  94. If passed the path to a file containing the implementation of a
  95. module within a package which is not on the import path,
  96. L{runner.filenameToModule} returns a module object loosely
  97. resembling the module defined by that file anyway.
  98. """
  99. # "test_sample" isn't actually the name of this module. However,
  100. # filenameToModule can't seem to figure that out. So clean up this
  101. # misnamed module. It would be better if this weren't necessary
  102. # and filenameToModule either didn't exist or added a correctly
  103. # named module to sys.modules.
  104. self.addCleanup(sys.modules.pop, 'test_sample', None)
  105. self.mangleSysPath(self.oldPath)
  106. sample1 = runner.filenameToModule(
  107. os.path.join(self.parent, 'goodpackage', 'test_sample.py'))
  108. self.mangleSysPath(self.newPath)
  109. from goodpackage import test_sample as sample2
  110. self.assertEqual(os.path.splitext(sample2.__file__)[0],
  111. os.path.splitext(sample1.__file__)[0])
  112. def test_packageInPath(self):
  113. """
  114. If the file in question is a package on the Python path, then it should
  115. properly import and return that package.
  116. """
  117. package1 = runner.filenameToModule(os.path.join(self.parent,
  118. 'goodpackage'))
  119. import goodpackage
  120. self.assertEqual(goodpackage, package1)
  121. def test_packageNotInPath(self):
  122. """
  123. If passed the path to a directory which represents a package which
  124. is not on the import path, L{runner.filenameToModule} returns a
  125. module object loosely resembling the package defined by that
  126. directory anyway.
  127. """
  128. # "__init__" isn't actually the name of the package! However,
  129. # filenameToModule is pretty stupid and decides that is its name
  130. # after all. Make sure it gets cleaned up. See the comment in
  131. # test_moduleNotInPath for possible courses of action related to
  132. # this.
  133. self.addCleanup(sys.modules.pop, "__init__")
  134. self.mangleSysPath(self.oldPath)
  135. package1 = runner.filenameToModule(
  136. os.path.join(self.parent, 'goodpackage'))
  137. self.mangleSysPath(self.newPath)
  138. import goodpackage
  139. self.assertEqual(os.path.splitext(goodpackage.__file__)[0],
  140. os.path.splitext(package1.__file__)[0])
  141. def test_directoryNotPackage(self):
  142. """
  143. L{runner.filenameToModule} raises a C{ValueError} when the name of an
  144. empty directory is passed that isn't considered a valid Python package
  145. because it doesn't contain a C{__init__.py} file.
  146. """
  147. emptyDir = filepath.FilePath(self.parent).child("emptyDirectory")
  148. emptyDir.createDirectory()
  149. err = self.assertRaises(ValueError, runner.filenameToModule,
  150. emptyDir.path)
  151. self.assertEqual(str(err), "%r is not a package directory" % (
  152. emptyDir.path,))
  153. def test_filenameNotPython(self):
  154. """
  155. L{runner.filenameToModule} raises a C{SyntaxError} when a non-Python
  156. file is passed.
  157. """
  158. filename = filepath.FilePath(self.parent).child('notpython')
  159. filename.setContent(b"This isn't python")
  160. self.assertRaises(
  161. SyntaxError, runner.filenameToModule, filename.path)
  162. def test_filenameMatchesPackage(self):
  163. """
  164. The C{__file__} attribute of the module should match the package name.
  165. """
  166. filename = filepath.FilePath(self.parent).child('goodpackage.py')
  167. filename.setContent(packages.testModule.encode("utf8"))
  168. try:
  169. module = runner.filenameToModule(filename.path)
  170. self.assertEqual(filename.path, module.__file__)
  171. finally:
  172. filename.remove()
  173. def test_directory(self):
  174. """
  175. Test loader against a filesystem directory containing an empty
  176. C{__init__.py} file. It should handle 'path' and 'path/' the same way.
  177. """
  178. goodDir = filepath.FilePath(self.parent).child('goodDirectory')
  179. goodDir.createDirectory()
  180. goodDir.child('__init__.py').setContent(b'')
  181. try:
  182. module = runner.filenameToModule(goodDir.path)
  183. self.assertTrue(module.__name__.endswith('goodDirectory'))
  184. module = runner.filenameToModule(goodDir.path + os.path.sep)
  185. self.assertTrue(module.__name__.endswith('goodDirectory'))
  186. finally:
  187. goodDir.remove()
  188. class LoaderTests(packages.SysPathManglingTest):
  189. """
  190. Tests for L{trial.TestLoader}.
  191. """
  192. def setUp(self):
  193. self.loader = runner.TestLoader()
  194. packages.SysPathManglingTest.setUp(self)
  195. def test_sortCases(self):
  196. from twisted.trial.test import sample
  197. suite = self.loader.loadClass(sample.AlphabetTest)
  198. self.assertEqual(['test_a', 'test_b', 'test_c'],
  199. [test._testMethodName for test in suite._tests])
  200. newOrder = ['test_b', 'test_c', 'test_a']
  201. sortDict = dict(zip(newOrder, range(3)))
  202. self.loader.sorter = lambda x : sortDict.get(x.shortDescription(), -1)
  203. suite = self.loader.loadClass(sample.AlphabetTest)
  204. self.assertEqual(newOrder,
  205. [test._testMethodName for test in suite._tests])
  206. def test_loadMethod(self):
  207. from twisted.trial.test import sample
  208. suite = self.loader.loadMethod(sample.FooTest.test_foo)
  209. self.assertEqual(1, suite.countTestCases())
  210. self.assertEqual('test_foo', suite._testMethodName)
  211. def test_loadFailingMethod(self):
  212. # test added for issue1353
  213. from twisted.trial.test import erroneous
  214. suite = self.loader.loadMethod(erroneous.TestRegularFail.test_fail)
  215. result = reporter.TestResult()
  216. suite.run(result)
  217. self.assertEqual(result.testsRun, 1)
  218. self.assertEqual(len(result.failures), 1)
  219. def test_loadFailure(self):
  220. """
  221. Loading a test that fails and getting the result of it ends up with one
  222. test ran and one failure.
  223. """
  224. suite = self.loader.loadByName(
  225. "twisted.trial.test.erroneous.TestRegularFail.test_fail")
  226. result = reporter.TestResult()
  227. suite.run(result)
  228. self.assertEqual(result.testsRun, 1)
  229. self.assertEqual(len(result.failures), 1)
  230. def test_loadNonMethod(self):
  231. from twisted.trial.test import sample
  232. self.assertRaises(TypeError, self.loader.loadMethod, sample)
  233. self.assertRaises(TypeError,
  234. self.loader.loadMethod, sample.FooTest)
  235. self.assertRaises(TypeError, self.loader.loadMethod, "string")
  236. self.assertRaises(TypeError,
  237. self.loader.loadMethod, ('foo', 'bar'))
  238. def test_loadBadDecorator(self):
  239. """
  240. A decorated test method for which the decorator has failed to set the
  241. method's __name__ correctly is loaded and its name in the class scope
  242. discovered.
  243. """
  244. from twisted.trial.test import sample
  245. suite = self.loader.loadAnything(
  246. sample.DecorationTest.test_badDecorator,
  247. parent=sample.DecorationTest,
  248. qualName=["sample", "DecorationTest", "test_badDecorator"])
  249. self.assertEqual(1, suite.countTestCases())
  250. self.assertEqual('test_badDecorator', suite._testMethodName)
  251. def test_loadGoodDecorator(self):
  252. """
  253. A decorated test method for which the decorator has set the method's
  254. __name__ correctly is loaded and the only name by which it goes is used.
  255. """
  256. from twisted.trial.test import sample
  257. suite = self.loader.loadAnything(
  258. sample.DecorationTest.test_goodDecorator,
  259. parent=sample.DecorationTest,
  260. qualName=["sample", "DecorationTest", "test_goodDecorator"])
  261. self.assertEqual(1, suite.countTestCases())
  262. self.assertEqual('test_goodDecorator', suite._testMethodName)
  263. def test_loadRenamedDecorator(self):
  264. """
  265. Load a decorated method which has been copied to a new name inside the
  266. class. Thus its __name__ and its key in the class's __dict__ no
  267. longer match.
  268. """
  269. from twisted.trial.test import sample
  270. suite = self.loader.loadAnything(
  271. sample.DecorationTest.test_renamedDecorator,
  272. parent=sample.DecorationTest,
  273. qualName=["sample", "DecorationTest", "test_renamedDecorator"])
  274. self.assertEqual(1, suite.countTestCases())
  275. self.assertEqual('test_renamedDecorator', suite._testMethodName)
  276. def test_loadClass(self):
  277. from twisted.trial.test import sample
  278. suite = self.loader.loadClass(sample.FooTest)
  279. self.assertEqual(2, suite.countTestCases())
  280. self.assertEqual(['test_bar', 'test_foo'],
  281. [test._testMethodName for test in suite._tests])
  282. def test_loadNonClass(self):
  283. from twisted.trial.test import sample
  284. self.assertRaises(TypeError, self.loader.loadClass, sample)
  285. self.assertRaises(TypeError,
  286. self.loader.loadClass, sample.FooTest.test_foo)
  287. self.assertRaises(TypeError, self.loader.loadClass, "string")
  288. self.assertRaises(TypeError,
  289. self.loader.loadClass, ('foo', 'bar'))
  290. def test_loadNonTestCase(self):
  291. from twisted.trial.test import sample
  292. self.assertRaises(ValueError, self.loader.loadClass,
  293. sample.NotATest)
  294. def test_loadModule(self):
  295. from twisted.trial.test import sample
  296. suite = self.loader.loadModule(sample)
  297. self.assertEqual(10, suite.countTestCases())
  298. def test_loadNonModule(self):
  299. from twisted.trial.test import sample
  300. self.assertRaises(TypeError,
  301. self.loader.loadModule, sample.FooTest)
  302. self.assertRaises(TypeError,
  303. self.loader.loadModule, sample.FooTest.test_foo)
  304. self.assertRaises(TypeError, self.loader.loadModule, "string")
  305. self.assertRaises(TypeError,
  306. self.loader.loadModule, ('foo', 'bar'))
  307. def test_loadPackage(self):
  308. import goodpackage
  309. suite = self.loader.loadPackage(goodpackage)
  310. self.assertEqual(7, suite.countTestCases())
  311. def test_loadNonPackage(self):
  312. from twisted.trial.test import sample
  313. self.assertRaises(TypeError,
  314. self.loader.loadPackage, sample.FooTest)
  315. self.assertRaises(TypeError,
  316. self.loader.loadPackage, sample.FooTest.test_foo)
  317. self.assertRaises(TypeError, self.loader.loadPackage, "string")
  318. self.assertRaises(TypeError,
  319. self.loader.loadPackage, ('foo', 'bar'))
  320. def test_loadModuleAsPackage(self):
  321. from twisted.trial.test import sample
  322. ## XXX -- should this instead raise a ValueError? -- jml
  323. self.assertRaises(TypeError, self.loader.loadPackage, sample)
  324. def test_loadPackageRecursive(self):
  325. import goodpackage
  326. suite = self.loader.loadPackage(goodpackage, recurse=True)
  327. self.assertEqual(14, suite.countTestCases())
  328. def test_loadAnythingOnModule(self):
  329. from twisted.trial.test import sample
  330. suite = self.loader.loadAnything(sample)
  331. self.assertEqual(sample.__name__,
  332. suite._tests[0]._tests[0].__class__.__module__)
  333. def test_loadAnythingOnClass(self):
  334. from twisted.trial.test import sample
  335. suite = self.loader.loadAnything(sample.FooTest)
  336. self.assertEqual(2, suite.countTestCases())
  337. def test_loadAnythingOnMethod(self):
  338. from twisted.trial.test import sample
  339. suite = self.loader.loadAnything(sample.FooTest.test_foo)
  340. self.assertEqual(1, suite.countTestCases())
  341. def test_loadAnythingOnPackage(self):
  342. import goodpackage
  343. suite = self.loader.loadAnything(goodpackage)
  344. self.assertTrue(isinstance(suite, self.loader.suiteFactory))
  345. self.assertEqual(7, suite.countTestCases())
  346. def test_loadAnythingOnPackageRecursive(self):
  347. import goodpackage
  348. suite = self.loader.loadAnything(goodpackage, recurse=True)
  349. self.assertTrue(isinstance(suite, self.loader.suiteFactory))
  350. self.assertEqual(14, suite.countTestCases())
  351. def test_loadAnythingOnString(self):
  352. # the important thing about this test is not the string-iness
  353. # but the non-handledness.
  354. self.assertRaises(TypeError,
  355. self.loader.loadAnything, "goodpackage")
  356. def test_importErrors(self):
  357. import package
  358. suite = self.loader.loadPackage(package, recurse=True)
  359. result = reporter.Reporter()
  360. suite.run(result)
  361. self.assertEqual(False, result.wasSuccessful())
  362. self.assertEqual(2, len(result.errors))
  363. errors = [test.id() for test, error in result.errors]
  364. errors.sort()
  365. self.assertEqual(errors, ['package.test_bad_module',
  366. 'package.test_import_module'])
  367. def test_differentInstances(self):
  368. """
  369. L{TestLoader.loadClass} returns a suite with each test method
  370. represented by a different instances of the L{TestCase} they are
  371. defined on.
  372. """
  373. class DistinctInstances(pyunit.TestCase):
  374. def test_1(self):
  375. self.first = 'test1Run'
  376. def test_2(self):
  377. self.assertFalse(hasattr(self, 'first'))
  378. suite = self.loader.loadClass(DistinctInstances)
  379. result = reporter.Reporter()
  380. suite.run(result)
  381. self.assertTrue(result.wasSuccessful())
  382. def test_loadModuleWith_test_suite(self):
  383. """
  384. Check that C{test_suite} is used when present and other L{TestCase}s are
  385. not included.
  386. """
  387. from twisted.trial.test import mockcustomsuite
  388. suite = self.loader.loadModule(mockcustomsuite)
  389. self.assertEqual(0, suite.countTestCases())
  390. self.assertEqual("MyCustomSuite", getattr(suite, 'name', None))
  391. def test_loadModuleWith_testSuite(self):
  392. """
  393. Check that C{testSuite} is used when present and other L{TestCase}s are
  394. not included.
  395. """
  396. from twisted.trial.test import mockcustomsuite2
  397. suite = self.loader.loadModule(mockcustomsuite2)
  398. self.assertEqual(0, suite.countTestCases())
  399. self.assertEqual("MyCustomSuite", getattr(suite, 'name', None))
  400. def test_loadModuleWithBothCustom(self):
  401. """
  402. Check that if C{testSuite} and C{test_suite} are both present in a
  403. module then C{testSuite} gets priority.
  404. """
  405. from twisted.trial.test import mockcustomsuite3
  406. suite = self.loader.loadModule(mockcustomsuite3)
  407. self.assertEqual('testSuite', getattr(suite, 'name', None))
  408. def test_customLoadRaisesAttributeError(self):
  409. """
  410. Make sure that any C{AttributeError}s raised by C{testSuite} are not
  411. swallowed by L{TestLoader}.
  412. """
  413. def testSuite():
  414. raise AttributeError('should be reraised')
  415. from twisted.trial.test import mockcustomsuite2
  416. mockcustomsuite2.testSuite, original = (testSuite,
  417. mockcustomsuite2.testSuite)
  418. try:
  419. self.assertRaises(AttributeError, self.loader.loadModule,
  420. mockcustomsuite2)
  421. finally:
  422. mockcustomsuite2.testSuite = original
  423. # XXX - duplicated and modified from test_script
  424. def assertSuitesEqual(self, test1, test2):
  425. names1 = testNames(test1)
  426. names2 = testNames(test2)
  427. names1.sort()
  428. names2.sort()
  429. self.assertEqual(names1, names2)
  430. def test_loadByNamesDuplicate(self):
  431. """
  432. Check that loadByNames ignores duplicate names
  433. """
  434. module = 'twisted.trial.test.test_log'
  435. suite1 = self.loader.loadByNames([module, module], True)
  436. suite2 = self.loader.loadByName(module, True)
  437. self.assertSuitesEqual(suite1, suite2)
  438. def test_loadByNamesPreservesOrder(self):
  439. """
  440. L{TestLoader.loadByNames} preserves the order of tests provided to it.
  441. """
  442. modules = [
  443. "inheritancepackage.test_x.A.test_foo",
  444. "twisted.trial.test.sample",
  445. "goodpackage",
  446. "twisted.trial.test.test_log",
  447. "twisted.trial.test.sample.FooTest",
  448. "package.test_module"]
  449. suite1 = self.loader.loadByNames(modules)
  450. suite2 = runner.TestSuite(map(self.loader.loadByName, modules))
  451. self.assertEqual(testNames(suite1), testNames(suite2))
  452. def test_loadDifferentNames(self):
  453. """
  454. Check that loadByNames loads all the names that it is given
  455. """
  456. modules = ['goodpackage', 'package.test_module']
  457. suite1 = self.loader.loadByNames(modules)
  458. suite2 = runner.TestSuite(map(self.loader.loadByName, modules))
  459. self.assertSuitesEqual(suite1, suite2)
  460. def test_loadInheritedMethods(self):
  461. """
  462. Check that test methods names which are inherited from are all
  463. loaded rather than just one.
  464. """
  465. methods = ['inheritancepackage.test_x.A.test_foo',
  466. 'inheritancepackage.test_x.B.test_foo']
  467. suite1 = self.loader.loadByNames(methods)
  468. suite2 = runner.TestSuite(map(self.loader.loadByName, methods))
  469. self.assertSuitesEqual(suite1, suite2)
  470. if _PY3:
  471. """
  472. These tests are unable to work on Python 3, as Python 3 has no concept
  473. of "unbound methods".
  474. """
  475. _msg = "Not possible on Python 3."
  476. test_loadMethod.skip = _msg
  477. test_loadNonMethod.skip = _msg
  478. test_loadFailingMethod.skip = _msg
  479. test_loadAnythingOnMethod.skip = _msg
  480. del _msg
  481. class ZipLoadingTests(LoaderTests):
  482. def setUp(self):
  483. from twisted.python.test.test_zippath import zipit
  484. LoaderTests.setUp(self)
  485. zipit(self.parent, self.parent+'.zip')
  486. self.parent += '.zip'
  487. self.mangleSysPath(self.oldPath+[self.parent])
  488. class PackageOrderingTests(packages.SysPathManglingTest):
  489. def setUp(self):
  490. self.loader = runner.TestLoader()
  491. self.topDir = self.mktemp()
  492. parent = os.path.join(self.topDir, "uberpackage")
  493. os.makedirs(parent)
  494. open(os.path.join(parent, "__init__.py"), "wb").close()
  495. packages.SysPathManglingTest.setUp(self, parent)
  496. self.mangleSysPath(self.oldPath + [self.topDir])
  497. def _trialSortAlgorithm(self, sorter):
  498. """
  499. Right now, halfway by accident, trial sorts like this:
  500. 1. all modules are grouped together in one list and sorted.
  501. 2. within each module, the classes are grouped together in one list
  502. and sorted.
  503. 3. finally within each class, each test method is grouped together
  504. in a list and sorted.
  505. This attempts to return a sorted list of testable thingies following
  506. those rules, so that we can compare the behavior of loadPackage.
  507. The things that show as 'cases' are errors from modules which failed to
  508. import, and test methods. Let's gather all those together.
  509. """
  510. pkg = getModule('uberpackage')
  511. testModules = []
  512. for testModule in pkg.walkModules():
  513. if testModule.name.split(".")[-1].startswith("test_"):
  514. testModules.append(testModule)
  515. sortedModules = sorted(testModules, key=sorter) # ONE
  516. for modinfo in sortedModules:
  517. # Now let's find all the classes.
  518. module = modinfo.load(None)
  519. if module is None:
  520. yield modinfo
  521. else:
  522. testClasses = []
  523. for attrib in modinfo.iterAttributes():
  524. if runner.isTestCase(attrib.load()):
  525. testClasses.append(attrib)
  526. sortedClasses = sorted(testClasses, key=sorter) # TWO
  527. for clsinfo in sortedClasses:
  528. testMethods = []
  529. for attr in clsinfo.iterAttributes():
  530. if attr.name.split(".")[-1].startswith('test'):
  531. testMethods.append(attr)
  532. sortedMethods = sorted(testMethods, key=sorter) # THREE
  533. for methinfo in sortedMethods:
  534. yield methinfo
  535. def loadSortedPackages(self, sorter=runner.name):
  536. """
  537. Verify that packages are loaded in the correct order.
  538. """
  539. import uberpackage
  540. self.loader.sorter = sorter
  541. suite = self.loader.loadPackage(uberpackage, recurse=True)
  542. # XXX: Work around strange, unexplained Zope crap.
  543. # jml, 2007-11-15.
  544. suite = unittest.decorate(suite, ITestCase)
  545. resultingTests = list(_iterateTests(suite))
  546. manifest = list(self._trialSortAlgorithm(sorter))
  547. for number, (manifestTest, actualTest) in enumerate(
  548. zip(manifest, resultingTests)):
  549. self.assertEqual(
  550. manifestTest.name, actualTest.id(),
  551. "#%d: %s != %s" %
  552. (number, manifestTest.name, actualTest.id()))
  553. self.assertEqual(len(manifest), len(resultingTests))
  554. def test_sortPackagesDefaultOrder(self):
  555. self.loadSortedPackages()
  556. def test_sortPackagesSillyOrder(self):
  557. def sillySorter(s):
  558. # This has to work on fully-qualified class names and class
  559. # objects, which is silly, but it's the "spec", such as it is.
  560. # if isinstance(s, type) or isinstance(s, types.ClassType):
  561. # return s.__module__+'.'+s.__name__
  562. n = runner.name(s)
  563. d = md5(n.encode('utf8')).hexdigest()
  564. return d
  565. self.loadSortedPackages(sillySorter)