test.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import os
  2. import operator
  3. import sys
  4. import contextlib
  5. import itertools
  6. import unittest
  7. from distutils.errors import DistutilsError, DistutilsOptionError
  8. from distutils import log
  9. from unittest import TestLoader
  10. from pkg_resources import (resource_listdir, resource_exists, normalize_path,
  11. working_set, _namespace_packages, evaluate_marker,
  12. add_activation_listener, require, EntryPoint)
  13. from setuptools import Command
  14. from .build_py import _unique_everseen
  15. class ScanningLoader(TestLoader):
  16. def __init__(self):
  17. TestLoader.__init__(self)
  18. self._visited = set()
  19. def loadTestsFromModule(self, module, pattern=None):
  20. """Return a suite of all tests cases contained in the given module
  21. If the module is a package, load tests from all the modules in it.
  22. If the module has an ``additional_tests`` function, call it and add
  23. the return value to the tests.
  24. """
  25. if module in self._visited:
  26. return None
  27. self._visited.add(module)
  28. tests = []
  29. tests.append(TestLoader.loadTestsFromModule(self, module))
  30. if hasattr(module, "additional_tests"):
  31. tests.append(module.additional_tests())
  32. if hasattr(module, '__path__'):
  33. for file in resource_listdir(module.__name__, ''):
  34. if file.endswith('.py') and file != '__init__.py':
  35. submodule = module.__name__ + '.' + file[:-3]
  36. else:
  37. if resource_exists(module.__name__, file + '/__init__.py'):
  38. submodule = module.__name__ + '.' + file
  39. else:
  40. continue
  41. tests.append(self.loadTestsFromName(submodule))
  42. if len(tests) != 1:
  43. return self.suiteClass(tests)
  44. else:
  45. return tests[0] # don't create a nested suite for only one return
  46. # adapted from jaraco.classes.properties:NonDataProperty
  47. class NonDataProperty:
  48. def __init__(self, fget):
  49. self.fget = fget
  50. def __get__(self, obj, objtype=None):
  51. if obj is None:
  52. return self
  53. return self.fget(obj)
  54. class test(Command):
  55. """Command to run unit tests after in-place build"""
  56. description = "run unit tests after in-place build (deprecated)"
  57. user_options = [
  58. ('test-module=', 'm', "Run 'test_suite' in specified module"),
  59. ('test-suite=', 's',
  60. "Run single test, case or suite (e.g. 'module.test_suite')"),
  61. ('test-runner=', 'r', "Test runner to use"),
  62. ]
  63. def initialize_options(self):
  64. self.test_suite = None
  65. self.test_module = None
  66. self.test_loader = None
  67. self.test_runner = None
  68. def finalize_options(self):
  69. if self.test_suite and self.test_module:
  70. msg = "You may specify a module or a suite, but not both"
  71. raise DistutilsOptionError(msg)
  72. if self.test_suite is None:
  73. if self.test_module is None:
  74. self.test_suite = self.distribution.test_suite
  75. else:
  76. self.test_suite = self.test_module + ".test_suite"
  77. if self.test_loader is None:
  78. self.test_loader = getattr(self.distribution, 'test_loader', None)
  79. if self.test_loader is None:
  80. self.test_loader = "setuptools.command.test:ScanningLoader"
  81. if self.test_runner is None:
  82. self.test_runner = getattr(self.distribution, 'test_runner', None)
  83. @NonDataProperty
  84. def test_args(self):
  85. return list(self._test_args())
  86. def _test_args(self):
  87. if not self.test_suite and sys.version_info >= (2, 7):
  88. yield 'discover'
  89. if self.verbose:
  90. yield '--verbose'
  91. if self.test_suite:
  92. yield self.test_suite
  93. def with_project_on_sys_path(self, func):
  94. """
  95. Backward compatibility for project_on_sys_path context.
  96. """
  97. with self.project_on_sys_path():
  98. func()
  99. @contextlib.contextmanager
  100. def project_on_sys_path(self, include_dists=[]):
  101. with_2to3 = getattr(self.distribution, 'use_2to3', False)
  102. if with_2to3:
  103. # If we run 2to3 we can not do this inplace:
  104. # Ensure metadata is up-to-date
  105. self.reinitialize_command('build_py', inplace=0)
  106. self.run_command('build_py')
  107. bpy_cmd = self.get_finalized_command("build_py")
  108. build_path = normalize_path(bpy_cmd.build_lib)
  109. # Build extensions
  110. self.reinitialize_command('egg_info', egg_base=build_path)
  111. self.run_command('egg_info')
  112. self.reinitialize_command('build_ext', inplace=0)
  113. self.run_command('build_ext')
  114. else:
  115. # Without 2to3 inplace works fine:
  116. self.run_command('egg_info')
  117. # Build extensions in-place
  118. self.reinitialize_command('build_ext', inplace=1)
  119. self.run_command('build_ext')
  120. ei_cmd = self.get_finalized_command("egg_info")
  121. old_path = sys.path[:]
  122. old_modules = sys.modules.copy()
  123. try:
  124. project_path = normalize_path(ei_cmd.egg_base)
  125. sys.path.insert(0, project_path)
  126. working_set.__init__()
  127. add_activation_listener(lambda dist: dist.activate())
  128. require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
  129. with self.paths_on_pythonpath([project_path]):
  130. yield
  131. finally:
  132. sys.path[:] = old_path
  133. sys.modules.clear()
  134. sys.modules.update(old_modules)
  135. working_set.__init__()
  136. @staticmethod
  137. @contextlib.contextmanager
  138. def paths_on_pythonpath(paths):
  139. """
  140. Add the indicated paths to the head of the PYTHONPATH environment
  141. variable so that subprocesses will also see the packages at
  142. these paths.
  143. Do this in a context that restores the value on exit.
  144. """
  145. nothing = object()
  146. orig_pythonpath = os.environ.get('PYTHONPATH', nothing)
  147. current_pythonpath = os.environ.get('PYTHONPATH', '')
  148. try:
  149. prefix = os.pathsep.join(_unique_everseen(paths))
  150. to_join = filter(None, [prefix, current_pythonpath])
  151. new_path = os.pathsep.join(to_join)
  152. if new_path:
  153. os.environ['PYTHONPATH'] = new_path
  154. yield
  155. finally:
  156. if orig_pythonpath is nothing:
  157. os.environ.pop('PYTHONPATH', None)
  158. else:
  159. os.environ['PYTHONPATH'] = orig_pythonpath
  160. @staticmethod
  161. def install_dists(dist):
  162. """
  163. Install the requirements indicated by self.distribution and
  164. return an iterable of the dists that were built.
  165. """
  166. ir_d = dist.fetch_build_eggs(dist.install_requires)
  167. tr_d = dist.fetch_build_eggs(dist.tests_require or [])
  168. er_d = dist.fetch_build_eggs(
  169. v for k, v in dist.extras_require.items()
  170. if k.startswith(':') and evaluate_marker(k[1:])
  171. )
  172. return itertools.chain(ir_d, tr_d, er_d)
  173. def run(self):
  174. self.announce(
  175. "WARNING: Testing via this command is deprecated and will be "
  176. "removed in a future version. Users looking for a generic test "
  177. "entry point independent of test runner are encouraged to use "
  178. "tox.",
  179. log.WARN,
  180. )
  181. installed_dists = self.install_dists(self.distribution)
  182. cmd = ' '.join(self._argv)
  183. if self.dry_run:
  184. self.announce('skipping "%s" (dry run)' % cmd)
  185. return
  186. self.announce('running "%s"' % cmd)
  187. paths = map(operator.attrgetter('location'), installed_dists)
  188. with self.paths_on_pythonpath(paths):
  189. with self.project_on_sys_path():
  190. self.run_tests()
  191. def run_tests(self):
  192. # Purge modules under test from sys.modules. The test loader will
  193. # re-import them from the build location. Required when 2to3 is used
  194. # with namespace packages.
  195. if getattr(self.distribution, 'use_2to3', False):
  196. module = self.test_suite.split('.')[0]
  197. if module in _namespace_packages:
  198. del_modules = []
  199. if module in sys.modules:
  200. del_modules.append(module)
  201. module += '.'
  202. for name in sys.modules:
  203. if name.startswith(module):
  204. del_modules.append(name)
  205. list(map(sys.modules.__delitem__, del_modules))
  206. test = unittest.main(
  207. None, None, self._argv,
  208. testLoader=self._resolve_as_ep(self.test_loader),
  209. testRunner=self._resolve_as_ep(self.test_runner),
  210. exit=False,
  211. )
  212. if not test.result.wasSuccessful():
  213. msg = 'Test failed: %s' % test.result
  214. self.announce(msg, log.ERROR)
  215. raise DistutilsError(msg)
  216. @property
  217. def _argv(self):
  218. return ['unittest'] + self.test_args
  219. @staticmethod
  220. def _resolve_as_ep(val):
  221. """
  222. Load the indicated attribute value, called, as a as if it were
  223. specified as an entry point.
  224. """
  225. if val is None:
  226. return
  227. parsed = EntryPoint.parse("x=" + val)
  228. return parsed.resolve()()