Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/setuptools/command/test.py
7747 views
import os1import operator2import sys3import contextlib4import itertools5import unittest6from distutils.errors import DistutilsError, DistutilsOptionError7from distutils import log8from unittest import TestLoader910from setuptools.extern import six11from setuptools.extern.six.moves import map, filter1213from pkg_resources import (resource_listdir, resource_exists, normalize_path,14working_set, _namespace_packages, evaluate_marker,15add_activation_listener, require, EntryPoint)16from setuptools import Command17from .build_py import _unique_everseen1819__metaclass__ = type202122class ScanningLoader(TestLoader):2324def __init__(self):25TestLoader.__init__(self)26self._visited = set()2728def loadTestsFromModule(self, module, pattern=None):29"""Return a suite of all tests cases contained in the given module3031If the module is a package, load tests from all the modules in it.32If the module has an ``additional_tests`` function, call it and add33the return value to the tests.34"""35if module in self._visited:36return None37self._visited.add(module)3839tests = []40tests.append(TestLoader.loadTestsFromModule(self, module))4142if hasattr(module, "additional_tests"):43tests.append(module.additional_tests())4445if hasattr(module, '__path__'):46for file in resource_listdir(module.__name__, ''):47if file.endswith('.py') and file != '__init__.py':48submodule = module.__name__ + '.' + file[:-3]49else:50if resource_exists(module.__name__, file + '/__init__.py'):51submodule = module.__name__ + '.' + file52else:53continue54tests.append(self.loadTestsFromName(submodule))5556if len(tests) != 1:57return self.suiteClass(tests)58else:59return tests[0] # don't create a nested suite for only one return606162# adapted from jaraco.classes.properties:NonDataProperty63class NonDataProperty:64def __init__(self, fget):65self.fget = fget6667def __get__(self, obj, objtype=None):68if obj is None:69return self70return self.fget(obj)717273class test(Command):74"""Command to run unit tests after in-place build"""7576description = "run unit tests after in-place build (deprecated)"7778user_options = [79('test-module=', 'm', "Run 'test_suite' in specified module"),80('test-suite=', 's',81"Run single test, case or suite (e.g. 'module.test_suite')"),82('test-runner=', 'r', "Test runner to use"),83]8485def initialize_options(self):86self.test_suite = None87self.test_module = None88self.test_loader = None89self.test_runner = None9091def finalize_options(self):9293if self.test_suite and self.test_module:94msg = "You may specify a module or a suite, but not both"95raise DistutilsOptionError(msg)9697if self.test_suite is None:98if self.test_module is None:99self.test_suite = self.distribution.test_suite100else:101self.test_suite = self.test_module + ".test_suite"102103if self.test_loader is None:104self.test_loader = getattr(self.distribution, 'test_loader', None)105if self.test_loader is None:106self.test_loader = "setuptools.command.test:ScanningLoader"107if self.test_runner is None:108self.test_runner = getattr(self.distribution, 'test_runner', None)109110@NonDataProperty111def test_args(self):112return list(self._test_args())113114def _test_args(self):115if not self.test_suite and sys.version_info >= (2, 7):116yield 'discover'117if self.verbose:118yield '--verbose'119if self.test_suite:120yield self.test_suite121122def with_project_on_sys_path(self, func):123"""124Backward compatibility for project_on_sys_path context.125"""126with self.project_on_sys_path():127func()128129@contextlib.contextmanager130def project_on_sys_path(self, include_dists=[]):131with_2to3 = not six.PY2 and getattr(132self.distribution, 'use_2to3', False)133134if with_2to3:135# If we run 2to3 we can not do this inplace:136137# Ensure metadata is up-to-date138self.reinitialize_command('build_py', inplace=0)139self.run_command('build_py')140bpy_cmd = self.get_finalized_command("build_py")141build_path = normalize_path(bpy_cmd.build_lib)142143# Build extensions144self.reinitialize_command('egg_info', egg_base=build_path)145self.run_command('egg_info')146147self.reinitialize_command('build_ext', inplace=0)148self.run_command('build_ext')149else:150# Without 2to3 inplace works fine:151self.run_command('egg_info')152153# Build extensions in-place154self.reinitialize_command('build_ext', inplace=1)155self.run_command('build_ext')156157ei_cmd = self.get_finalized_command("egg_info")158159old_path = sys.path[:]160old_modules = sys.modules.copy()161162try:163project_path = normalize_path(ei_cmd.egg_base)164sys.path.insert(0, project_path)165working_set.__init__()166add_activation_listener(lambda dist: dist.activate())167require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))168with self.paths_on_pythonpath([project_path]):169yield170finally:171sys.path[:] = old_path172sys.modules.clear()173sys.modules.update(old_modules)174working_set.__init__()175176@staticmethod177@contextlib.contextmanager178def paths_on_pythonpath(paths):179"""180Add the indicated paths to the head of the PYTHONPATH environment181variable so that subprocesses will also see the packages at182these paths.183184Do this in a context that restores the value on exit.185"""186nothing = object()187orig_pythonpath = os.environ.get('PYTHONPATH', nothing)188current_pythonpath = os.environ.get('PYTHONPATH', '')189try:190prefix = os.pathsep.join(_unique_everseen(paths))191to_join = filter(None, [prefix, current_pythonpath])192new_path = os.pathsep.join(to_join)193if new_path:194os.environ['PYTHONPATH'] = new_path195yield196finally:197if orig_pythonpath is nothing:198os.environ.pop('PYTHONPATH', None)199else:200os.environ['PYTHONPATH'] = orig_pythonpath201202@staticmethod203def install_dists(dist):204"""205Install the requirements indicated by self.distribution and206return an iterable of the dists that were built.207"""208ir_d = dist.fetch_build_eggs(dist.install_requires)209tr_d = dist.fetch_build_eggs(dist.tests_require or [])210er_d = dist.fetch_build_eggs(211v for k, v in dist.extras_require.items()212if k.startswith(':') and evaluate_marker(k[1:])213)214return itertools.chain(ir_d, tr_d, er_d)215216def run(self):217self.announce(218"WARNING: Testing via this command is deprecated and will be "219"removed in a future version. Users looking for a generic test "220"entry point independent of test runner are encouraged to use "221"tox.",222log.WARN,223)224225installed_dists = self.install_dists(self.distribution)226227cmd = ' '.join(self._argv)228if self.dry_run:229self.announce('skipping "%s" (dry run)' % cmd)230return231232self.announce('running "%s"' % cmd)233234paths = map(operator.attrgetter('location'), installed_dists)235with self.paths_on_pythonpath(paths):236with self.project_on_sys_path():237self.run_tests()238239def run_tests(self):240# Purge modules under test from sys.modules. The test loader will241# re-import them from the build location. Required when 2to3 is used242# with namespace packages.243if not six.PY2 and getattr(self.distribution, 'use_2to3', False):244module = self.test_suite.split('.')[0]245if module in _namespace_packages:246del_modules = []247if module in sys.modules:248del_modules.append(module)249module += '.'250for name in sys.modules:251if name.startswith(module):252del_modules.append(name)253list(map(sys.modules.__delitem__, del_modules))254255test = unittest.main(256None, None, self._argv,257testLoader=self._resolve_as_ep(self.test_loader),258testRunner=self._resolve_as_ep(self.test_runner),259exit=False,260)261if not test.result.wasSuccessful():262msg = 'Test failed: %s' % test.result263self.announce(msg, log.ERROR)264raise DistutilsError(msg)265266@property267def _argv(self):268return ['unittest'] + self.test_args269270@staticmethod271def _resolve_as_ep(val):272"""273Load the indicated attribute value, called, as a as if it were274specified as an entry point.275"""276if val is None:277return278parsed = EntryPoint.parse("x=" + val)279return parsed.resolve()()280281282