test.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import sys
  2. import contextlib
  3. from distutils.errors import DistutilsOptionError
  4. from unittest import TestLoader
  5. from setuptools.extern import six
  6. from setuptools.extern.six.moves import map
  7. from pkg_resources import (resource_listdir, resource_exists, normalize_path,
  8. working_set, _namespace_packages,
  9. add_activation_listener, require, EntryPoint)
  10. from setuptools import Command
  11. from setuptools.py31compat import unittest_main
  12. class ScanningLoader(TestLoader):
  13. def loadTestsFromModule(self, module, pattern=None):
  14. """Return a suite of all tests cases contained in the given module
  15. If the module is a package, load tests from all the modules in it.
  16. If the module has an ``additional_tests`` function, call it and add
  17. the return value to the tests.
  18. """
  19. tests = []
  20. tests.append(TestLoader.loadTestsFromModule(self, module))
  21. if hasattr(module, "additional_tests"):
  22. tests.append(module.additional_tests())
  23. if hasattr(module, '__path__'):
  24. for file in resource_listdir(module.__name__, ''):
  25. if file.endswith('.py') and file != '__init__.py':
  26. submodule = module.__name__ + '.' + file[:-3]
  27. else:
  28. if resource_exists(module.__name__, file + '/__init__.py'):
  29. submodule = module.__name__ + '.' + file
  30. else:
  31. continue
  32. tests.append(self.loadTestsFromName(submodule))
  33. if len(tests) != 1:
  34. return self.suiteClass(tests)
  35. else:
  36. return tests[0] # don't create a nested suite for only one return
  37. # adapted from jaraco.classes.properties:NonDataProperty
  38. class NonDataProperty(object):
  39. def __init__(self, fget):
  40. self.fget = fget
  41. def __get__(self, obj, objtype=None):
  42. if obj is None:
  43. return self
  44. return self.fget(obj)
  45. class test(Command):
  46. """Command to run unit tests after in-place build"""
  47. description = "run unit tests after in-place build"
  48. user_options = [
  49. ('test-module=', 'm', "Run 'test_suite' in specified module"),
  50. ('test-suite=', 's',
  51. "Test suite to run (e.g. 'some_module.test_suite')"),
  52. ('test-runner=', 'r', "Test runner to use"),
  53. ]
  54. def initialize_options(self):
  55. self.test_suite = None
  56. self.test_module = None
  57. self.test_loader = None
  58. self.test_runner = None
  59. def finalize_options(self):
  60. if self.test_suite and self.test_module:
  61. msg = "You may specify a module or a suite, but not both"
  62. raise DistutilsOptionError(msg)
  63. if self.test_suite is None:
  64. if self.test_module is None:
  65. self.test_suite = self.distribution.test_suite
  66. else:
  67. self.test_suite = self.test_module + ".test_suite"
  68. if self.test_loader is None:
  69. self.test_loader = getattr(self.distribution, 'test_loader', None)
  70. if self.test_loader is None:
  71. self.test_loader = "setuptools.command.test:ScanningLoader"
  72. if self.test_runner is None:
  73. self.test_runner = getattr(self.distribution, 'test_runner', None)
  74. @NonDataProperty
  75. def test_args(self):
  76. return list(self._test_args())
  77. def _test_args(self):
  78. if self.verbose:
  79. yield '--verbose'
  80. if self.test_suite:
  81. yield self.test_suite
  82. def with_project_on_sys_path(self, func):
  83. """
  84. Backward compatibility for project_on_sys_path context.
  85. """
  86. with self.project_on_sys_path():
  87. func()
  88. @contextlib.contextmanager
  89. def project_on_sys_path(self):
  90. with_2to3 = six.PY3 and getattr(self.distribution, 'use_2to3', False)
  91. if with_2to3:
  92. # If we run 2to3 we can not do this inplace:
  93. # Ensure metadata is up-to-date
  94. self.reinitialize_command('build_py', inplace=0)
  95. self.run_command('build_py')
  96. bpy_cmd = self.get_finalized_command("build_py")
  97. build_path = normalize_path(bpy_cmd.build_lib)
  98. # Build extensions
  99. self.reinitialize_command('egg_info', egg_base=build_path)
  100. self.run_command('egg_info')
  101. self.reinitialize_command('build_ext', inplace=0)
  102. self.run_command('build_ext')
  103. else:
  104. # Without 2to3 inplace works fine:
  105. self.run_command('egg_info')
  106. # Build extensions in-place
  107. self.reinitialize_command('build_ext', inplace=1)
  108. self.run_command('build_ext')
  109. ei_cmd = self.get_finalized_command("egg_info")
  110. old_path = sys.path[:]
  111. old_modules = sys.modules.copy()
  112. try:
  113. sys.path.insert(0, normalize_path(ei_cmd.egg_base))
  114. working_set.__init__()
  115. add_activation_listener(lambda dist: dist.activate())
  116. require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
  117. yield
  118. finally:
  119. sys.path[:] = old_path
  120. sys.modules.clear()
  121. sys.modules.update(old_modules)
  122. working_set.__init__()
  123. def run(self):
  124. if self.distribution.install_requires:
  125. self.distribution.fetch_build_eggs(
  126. self.distribution.install_requires)
  127. if self.distribution.tests_require:
  128. self.distribution.fetch_build_eggs(self.distribution.tests_require)
  129. cmd = ' '.join(self._argv)
  130. if self.dry_run:
  131. self.announce('skipping "%s" (dry run)' % cmd)
  132. return
  133. self.announce('running "%s"' % cmd)
  134. with self.project_on_sys_path():
  135. self.run_tests()
  136. def run_tests(self):
  137. # Purge modules under test from sys.modules. The test loader will
  138. # re-import them from the build location. Required when 2to3 is used
  139. # with namespace packages.
  140. if six.PY3 and getattr(self.distribution, 'use_2to3', False):
  141. module = self.test_suite.split('.')[0]
  142. if module in _namespace_packages:
  143. del_modules = []
  144. if module in sys.modules:
  145. del_modules.append(module)
  146. module += '.'
  147. for name in sys.modules:
  148. if name.startswith(module):
  149. del_modules.append(name)
  150. list(map(sys.modules.__delitem__, del_modules))
  151. unittest_main(
  152. None, None, self._argv,
  153. testLoader=self._resolve_as_ep(self.test_loader),
  154. testRunner=self._resolve_as_ep(self.test_runner),
  155. )
  156. @property
  157. def _argv(self):
  158. return ['unittest'] + self.test_args
  159. @staticmethod
  160. def _resolve_as_ep(val):
  161. """
  162. Load the indicated attribute value, called, as a as if it were
  163. specified as an entry point.
  164. """
  165. if val is None:
  166. return
  167. parsed = EntryPoint.parse("x=" + val)
  168. return parsed.resolve()()