1
0

test.py 9.4 KB

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