Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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