test.py 9.0 KB

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