/nose/suite.py

https://bitbucket.org/jpellerin/nose/ · Python · 607 lines · 459 code · 48 blank · 100 comment · 109 complexity · d902fd3c7df42cf0151aec50639c1c33 MD5 · raw file

  1. """
  2. Test Suites
  3. -----------
  4. Provides a LazySuite, which is a suite whose test list is a generator
  5. function, and ContextSuite,which can run fixtures (setup/teardown
  6. functions or methods) for the context that contains its tests.
  7. """
  8. from __future__ import generators
  9. import logging
  10. import sys
  11. import unittest
  12. from nose.case import Test
  13. from nose.config import Config
  14. from nose.proxy import ResultProxyFactory
  15. from nose.util import isclass, resolve_name, try_run
  16. if sys.platform == 'cli':
  17. if sys.version_info[:2] < (2, 6):
  18. import clr
  19. clr.AddReference("IronPython")
  20. from IronPython.Runtime.Exceptions import StringException
  21. else:
  22. class StringException(Exception):
  23. pass
  24. log = logging.getLogger(__name__)
  25. #log.setLevel(logging.DEBUG)
  26. # Singleton for default value -- see ContextSuite.__init__ below
  27. _def = object()
  28. def _strclass(cls):
  29. return "%s.%s" % (cls.__module__, cls.__name__)
  30. class MixedContextError(Exception):
  31. """Error raised when a context suite sees tests from more than
  32. one context.
  33. """
  34. pass
  35. class LazySuite(unittest.TestSuite):
  36. """A suite that may use a generator as its list of tests
  37. """
  38. def __init__(self, tests=()):
  39. """Initialize the suite. tests may be an iterable or a generator
  40. """
  41. self._set_tests(tests)
  42. def __iter__(self):
  43. return iter(self._tests)
  44. def __repr__(self):
  45. return "<%s tests=generator (%s)>" % (
  46. _strclass(self.__class__), id(self))
  47. def __hash__(self):
  48. return object.__hash__(self)
  49. __str__ = __repr__
  50. def addTest(self, test):
  51. self._precache.append(test)
  52. # added to bypass run changes in 2.7's unittest
  53. def run(self, result):
  54. for test in self._tests:
  55. if result.shouldStop:
  56. break
  57. test(result)
  58. return result
  59. def __nonzero__(self):
  60. log.debug("tests in %s?", id(self))
  61. if self._precache:
  62. return True
  63. if self.test_generator is None:
  64. return False
  65. try:
  66. test = self.test_generator.next()
  67. if test is not None:
  68. self._precache.append(test)
  69. return True
  70. except StopIteration:
  71. pass
  72. return False
  73. def _get_tests(self):
  74. log.debug("precache is %s", self._precache)
  75. for test in self._precache:
  76. yield test
  77. if self.test_generator is None:
  78. return
  79. for test in self.test_generator:
  80. yield test
  81. def _set_tests(self, tests):
  82. self._precache = []
  83. is_suite = isinstance(tests, unittest.TestSuite)
  84. if callable(tests) and not is_suite:
  85. self.test_generator = tests()
  86. elif is_suite:
  87. # Suites need special treatment: they must be called like
  88. # tests for their setup/teardown to run (if any)
  89. self.addTests([tests])
  90. self.test_generator = None
  91. else:
  92. self.addTests(tests)
  93. self.test_generator = None
  94. _tests = property(_get_tests, _set_tests, None,
  95. "Access the tests in this suite. Access is through a "
  96. "generator, so iteration may not be repeatable.")
  97. class ContextSuite(LazySuite):
  98. """A suite with context.
  99. A ContextSuite executes fixtures (setup and teardown functions or
  100. methods) for the context containing its tests.
  101. The context may be explicitly passed. If it is not, a context (or
  102. nested set of contexts) will be constructed by examining the tests
  103. in the suite.
  104. """
  105. failureException = unittest.TestCase.failureException
  106. was_setup = False
  107. was_torndown = False
  108. classSetup = ('setup_class', 'setup_all', 'setupClass', 'setupAll',
  109. 'setUpClass', 'setUpAll')
  110. classTeardown = ('teardown_class', 'teardown_all', 'teardownClass',
  111. 'teardownAll', 'tearDownClass', 'tearDownAll')
  112. moduleSetup = ('setup_module', 'setupModule', 'setUpModule', 'setup',
  113. 'setUp')
  114. moduleTeardown = ('teardown_module', 'teardownModule', 'tearDownModule',
  115. 'teardown', 'tearDown')
  116. packageSetup = ('setup_package', 'setupPackage', 'setUpPackage')
  117. packageTeardown = ('teardown_package', 'teardownPackage',
  118. 'tearDownPackage')
  119. def __init__(self, tests=(), context=None, factory=None,
  120. config=None, resultProxy=None, can_split=True):
  121. log.debug("Context suite for %s (%s) (%s)", tests, context, id(self))
  122. self.context = context
  123. self.factory = factory
  124. if config is None:
  125. config = Config()
  126. self.config = config
  127. self.resultProxy = resultProxy
  128. self.has_run = False
  129. self.can_split = can_split
  130. self.error_context = None
  131. LazySuite.__init__(self, tests)
  132. def __repr__(self):
  133. return "<%s context=%s>" % (
  134. _strclass(self.__class__),
  135. getattr(self.context, '__name__', self.context))
  136. __str__ = __repr__
  137. def id(self):
  138. if self.error_context:
  139. return '%s:%s' % (repr(self), self.error_context)
  140. else:
  141. return repr(self)
  142. def __hash__(self):
  143. return object.__hash__(self)
  144. # 2.3 compat -- force 2.4 call sequence
  145. def __call__(self, *arg, **kw):
  146. return self.run(*arg, **kw)
  147. def exc_info(self):
  148. """Hook for replacing error tuple output
  149. """
  150. return sys.exc_info()
  151. def _exc_info(self):
  152. """Bottleneck to fix up IronPython string exceptions
  153. """
  154. e = self.exc_info()
  155. if sys.platform == 'cli':
  156. if isinstance(e[0], StringException):
  157. # IronPython throws these StringExceptions, but
  158. # traceback checks type(etype) == str. Make a real
  159. # string here.
  160. e = (str(e[0]), e[1], e[2])
  161. return e
  162. def run(self, result):
  163. """Run tests in suite inside of suite fixtures.
  164. """
  165. # proxy the result for myself
  166. log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests)
  167. #import pdb
  168. #pdb.set_trace()
  169. if self.resultProxy:
  170. result, orig = self.resultProxy(result, self), result
  171. else:
  172. result, orig = result, result
  173. try:
  174. self.setUp()
  175. except KeyboardInterrupt:
  176. raise
  177. except:
  178. self.error_context = 'setup'
  179. result.addError(self, self._exc_info())
  180. return
  181. try:
  182. for test in self._tests:
  183. if result.shouldStop:
  184. log.debug("stopping")
  185. break
  186. # each nose.case.Test will create its own result proxy
  187. # so the cases need the original result, to avoid proxy
  188. # chains
  189. test(orig)
  190. finally:
  191. self.has_run = True
  192. try:
  193. self.tearDown()
  194. except KeyboardInterrupt:
  195. raise
  196. except:
  197. self.error_context = 'teardown'
  198. result.addError(self, self._exc_info())
  199. def hasFixtures(self, ctx_callback=None):
  200. context = self.context
  201. if context is None:
  202. return False
  203. if self.implementsAnyFixture(context, ctx_callback=ctx_callback):
  204. return True
  205. # My context doesn't have any, but its ancestors might
  206. factory = self.factory
  207. if factory:
  208. ancestors = factory.context.get(self, [])
  209. for ancestor in ancestors:
  210. if self.implementsAnyFixture(
  211. ancestor, ctx_callback=ctx_callback):
  212. return True
  213. return False
  214. def implementsAnyFixture(self, context, ctx_callback):
  215. if isclass(context):
  216. names = self.classSetup + self.classTeardown
  217. else:
  218. names = self.moduleSetup + self.moduleTeardown
  219. if hasattr(context, '__path__'):
  220. names += self.packageSetup + self.packageTeardown
  221. # If my context has any fixture attribute, I have fixtures
  222. fixt = False
  223. for m in names:
  224. if hasattr(context, m):
  225. fixt = True
  226. break
  227. if ctx_callback is None:
  228. return fixt
  229. return ctx_callback(context, fixt)
  230. def setUp(self):
  231. log.debug("suite %s setUp called, tests: %s", id(self), self._tests)
  232. if not self:
  233. # I have no tests
  234. log.debug("suite %s has no tests", id(self))
  235. return
  236. if self.was_setup:
  237. log.debug("suite %s already set up", id(self))
  238. return
  239. context = self.context
  240. if context is None:
  241. return
  242. # before running my own context's setup, I need to
  243. # ask the factory if my context's contexts' setups have been run
  244. factory = self.factory
  245. if factory:
  246. # get a copy, since we'll be destroying it as we go
  247. ancestors = factory.context.get(self, [])[:]
  248. while ancestors:
  249. ancestor = ancestors.pop()
  250. log.debug("ancestor %s may need setup", ancestor)
  251. if ancestor in factory.was_setup:
  252. continue
  253. log.debug("ancestor %s does need setup", ancestor)
  254. self.setupContext(ancestor)
  255. if not context in factory.was_setup:
  256. self.setupContext(context)
  257. else:
  258. self.setupContext(context)
  259. self.was_setup = True
  260. log.debug("completed suite setup")
  261. def setupContext(self, context):
  262. self.config.plugins.startContext(context)
  263. log.debug("%s setup context %s", self, context)
  264. if self.factory:
  265. if context in self.factory.was_setup:
  266. return
  267. # note that I ran the setup for this context, so that I'll run
  268. # the teardown in my teardown
  269. self.factory.was_setup[context] = self
  270. if isclass(context):
  271. names = self.classSetup
  272. else:
  273. names = self.moduleSetup
  274. if hasattr(context, '__path__'):
  275. names = self.packageSetup + names
  276. try_run(context, names)
  277. def shortDescription(self):
  278. if self.context is None:
  279. return "test suite"
  280. return "test suite for %s" % self.context
  281. def tearDown(self):
  282. log.debug('context teardown')
  283. if not self.was_setup or self.was_torndown:
  284. log.debug(
  285. "No reason to teardown (was_setup? %s was_torndown? %s)"
  286. % (self.was_setup, self.was_torndown))
  287. return
  288. self.was_torndown = True
  289. context = self.context
  290. if context is None:
  291. log.debug("No context to tear down")
  292. return
  293. # for each ancestor... if the ancestor was setup
  294. # and I did the setup, I can do teardown
  295. factory = self.factory
  296. if factory:
  297. ancestors = factory.context.get(self, []) + [context]
  298. for ancestor in ancestors:
  299. log.debug('ancestor %s may need teardown', ancestor)
  300. if not ancestor in factory.was_setup:
  301. log.debug('ancestor %s was not setup', ancestor)
  302. continue
  303. if ancestor in factory.was_torndown:
  304. log.debug('ancestor %s already torn down', ancestor)
  305. continue
  306. setup = factory.was_setup[ancestor]
  307. log.debug("%s setup ancestor %s", setup, ancestor)
  308. if setup is self:
  309. self.teardownContext(ancestor)
  310. else:
  311. self.teardownContext(context)
  312. def teardownContext(self, context):
  313. log.debug("%s teardown context %s", self, context)
  314. if self.factory:
  315. if context in self.factory.was_torndown:
  316. return
  317. self.factory.was_torndown[context] = self
  318. if isclass(context):
  319. names = self.classTeardown
  320. else:
  321. names = self.moduleTeardown
  322. if hasattr(context, '__path__'):
  323. names = self.packageTeardown + names
  324. try_run(context, names)
  325. self.config.plugins.stopContext(context)
  326. # FIXME the wrapping has to move to the factory?
  327. def _get_wrapped_tests(self):
  328. for test in self._get_tests():
  329. if isinstance(test, Test) or isinstance(test, unittest.TestSuite):
  330. yield test
  331. else:
  332. yield Test(test,
  333. config=self.config,
  334. resultProxy=self.resultProxy)
  335. _tests = property(_get_wrapped_tests, LazySuite._set_tests, None,
  336. "Access the tests in this suite. Tests are returned "
  337. "inside of a context wrapper.")
  338. class ContextSuiteFactory(object):
  339. """Factory for ContextSuites. Called with a collection of tests,
  340. the factory decides on a hierarchy of contexts by introspecting
  341. the collection or the tests themselves to find the objects
  342. containing the test objects. It always returns one suite, but that
  343. suite may consist of a hierarchy of nested suites.
  344. """
  345. suiteClass = ContextSuite
  346. def __init__(self, config=None, suiteClass=None, resultProxy=_def):
  347. if config is None:
  348. config = Config()
  349. self.config = config
  350. if suiteClass is not None:
  351. self.suiteClass = suiteClass
  352. # Using a singleton to represent default instead of None allows
  353. # passing resultProxy=None to turn proxying off.
  354. if resultProxy is _def:
  355. resultProxy = ResultProxyFactory(config=config)
  356. self.resultProxy = resultProxy
  357. self.suites = {}
  358. self.context = {}
  359. self.was_setup = {}
  360. self.was_torndown = {}
  361. def __call__(self, tests, **kw):
  362. """Return ``ContextSuite`` for tests. ``tests`` may either
  363. be a callable (in which case the resulting ContextSuite will
  364. have no parent context and be evaluated lazily) or an
  365. iterable. In that case the tests will wrapped in
  366. nose.case.Test, be examined and the context of each found and a
  367. suite of suites returned, organized into a stack with the
  368. outermost suites belonging to the outermost contexts.
  369. """
  370. log.debug("Create suite for %s", tests)
  371. context = kw.pop('context', getattr(tests, 'context', None))
  372. log.debug("tests %s context %s", tests, context)
  373. if context is None:
  374. tests = self.wrapTests(tests)
  375. try:
  376. context = self.findContext(tests)
  377. except MixedContextError:
  378. return self.makeSuite(self.mixedSuites(tests), None, **kw)
  379. return self.makeSuite(tests, context, **kw)
  380. def ancestry(self, context):
  381. """Return the ancestry of the context (that is, all of the
  382. packages and modules containing the context), in order of
  383. descent with the outermost ancestor last.
  384. This method is a generator.
  385. """
  386. log.debug("get ancestry %s", context)
  387. if context is None:
  388. return
  389. # Methods include reference to module they are defined in, we
  390. # don't want that, instead want the module the class is in now
  391. # (classes are re-ancestored elsewhere).
  392. if hasattr(context, 'im_class'):
  393. context = context.im_class
  394. elif hasattr(context, '__self__'):
  395. context = context.__self__.__class__
  396. if hasattr(context, '__module__'):
  397. ancestors = context.__module__.split('.')
  398. elif hasattr(context, '__name__'):
  399. ancestors = context.__name__.split('.')[:-1]
  400. else:
  401. raise TypeError("%s has no ancestors?" % context)
  402. while ancestors:
  403. log.debug(" %s ancestors %s", context, ancestors)
  404. yield resolve_name('.'.join(ancestors))
  405. ancestors.pop()
  406. def findContext(self, tests):
  407. if callable(tests) or isinstance(tests, unittest.TestSuite):
  408. return None
  409. context = None
  410. for test in tests:
  411. # Don't look at suites for contexts, only tests
  412. ctx = getattr(test, 'context', None)
  413. if ctx is None:
  414. continue
  415. if context is None:
  416. context = ctx
  417. elif context != ctx:
  418. raise MixedContextError(
  419. "Tests with different contexts in same suite! %s != %s"
  420. % (context, ctx))
  421. return context
  422. def makeSuite(self, tests, context, **kw):
  423. suite = self.suiteClass(
  424. tests, context=context, config=self.config, factory=self,
  425. resultProxy=self.resultProxy, **kw)
  426. if context is not None:
  427. self.suites.setdefault(context, []).append(suite)
  428. self.context.setdefault(suite, []).append(context)
  429. log.debug("suite %s has context %s", suite,
  430. getattr(context, '__name__', None))
  431. for ancestor in self.ancestry(context):
  432. self.suites.setdefault(ancestor, []).append(suite)
  433. self.context[suite].append(ancestor)
  434. log.debug("suite %s has ancestor %s", suite, ancestor.__name__)
  435. return suite
  436. def mixedSuites(self, tests):
  437. """The complex case where there are tests that don't all share
  438. the same context. Groups tests into suites with common ancestors,
  439. according to the following (essentially tail-recursive) procedure:
  440. Starting with the context of the first test, if it is not
  441. None, look for tests in the remaining tests that share that
  442. ancestor. If any are found, group into a suite with that
  443. ancestor as the context, and replace the current suite with
  444. that suite. Continue this process for each ancestor of the
  445. first test, until all ancestors have been processed. At this
  446. point if any tests remain, recurse with those tests as the
  447. input, returning a list of the common suite (which may be the
  448. suite or test we started with, if no common tests were found)
  449. plus the results of recursion.
  450. """
  451. if not tests:
  452. return []
  453. head = tests.pop(0)
  454. if not tests:
  455. return [head] # short circuit when none are left to combine
  456. suite = head # the common ancestry suite, so far
  457. tail = tests[:]
  458. context = getattr(head, 'context', None)
  459. if context is not None:
  460. ancestors = [context] + [a for a in self.ancestry(context)]
  461. for ancestor in ancestors:
  462. common = [suite] # tests with ancestor in common, so far
  463. remain = [] # tests that remain to be processed
  464. for test in tail:
  465. found_common = False
  466. test_ctx = getattr(test, 'context', None)
  467. if test_ctx is None:
  468. remain.append(test)
  469. continue
  470. if test_ctx is ancestor:
  471. common.append(test)
  472. continue
  473. for test_ancestor in self.ancestry(test_ctx):
  474. if test_ancestor is ancestor:
  475. common.append(test)
  476. found_common = True
  477. break
  478. if not found_common:
  479. remain.append(test)
  480. if common:
  481. suite = self.makeSuite(common, ancestor)
  482. tail = self.mixedSuites(remain)
  483. return [suite] + tail
  484. def wrapTests(self, tests):
  485. log.debug("wrap %s", tests)
  486. if callable(tests) or isinstance(tests, unittest.TestSuite):
  487. log.debug("I won't wrap")
  488. return tests
  489. wrapped = []
  490. for test in tests:
  491. log.debug("wrapping %s", test)
  492. if isinstance(test, Test) or isinstance(test, unittest.TestSuite):
  493. wrapped.append(test)
  494. elif isinstance(test, ContextList):
  495. wrapped.append(self.makeSuite(test, context=test.context))
  496. else:
  497. wrapped.append(
  498. Test(test, config=self.config, resultProxy=self.resultProxy)
  499. )
  500. return wrapped
  501. class ContextList(object):
  502. """Not quite a suite -- a group of tests in a context. This is used
  503. to hint the ContextSuiteFactory about what context the tests
  504. belong to, in cases where it may be ambiguous or missing.
  505. """
  506. def __init__(self, tests, context=None):
  507. self.tests = tests
  508. self.context = context
  509. def __iter__(self):
  510. return iter(self.tests)
  511. class FinalizingSuiteWrapper(unittest.TestSuite):
  512. """Wraps suite and calls final function after suite has
  513. executed. Used to call final functions in cases (like running in
  514. the standard test runner) where test running is not under nose's
  515. control.
  516. """
  517. def __init__(self, suite, finalize):
  518. self.suite = suite
  519. self.finalize = finalize
  520. def __call__(self, *arg, **kw):
  521. return self.run(*arg, **kw)
  522. # 2.7 compat
  523. def __iter__(self):
  524. return iter(self.suite)
  525. def run(self, *arg, **kw):
  526. try:
  527. return self.suite(*arg, **kw)
  528. finally:
  529. self.finalize(*arg, **kw)
  530. # backwards compat -- sort of
  531. class TestDir:
  532. def __init__(*arg, **kw):
  533. raise NotImplementedError(
  534. "TestDir is not usable with nose 0.10. The class is present "
  535. "in nose.suite for backwards compatibility purposes but it "
  536. "may not be used.")
  537. class TestModule:
  538. def __init__(*arg, **kw):
  539. raise NotImplementedError(
  540. "TestModule is not usable with nose 0.10. The class is present "
  541. "in nose.suite for backwards compatibility purposes but it "
  542. "may not be used.")