def isolate(create_tmpdir): """ Isolate our tests so that things like global configuration files and the like do not affect our test results. We use an autouse function scoped fixture because we want to ensure that every test has it's own isolated home directory. """ # Create a directory to use as our home location. home_dir = os.path.join(str(create_tmpdir()), "home") os.makedirs(home_dir) mkdir_p(os.path.join(home_dir, ".config", "git")) git_config_file = os.path.join(home_dir, ".config", "git", "config") with open(git_config_file, "wb") as fp: fp.write(b"[user]\n\tname = pipenv\n\temail = [email protected]\n") # os.environ["GIT_CONFIG"] = fs_str(git_config_file) os.environ["GIT_CONFIG_NOSYSTEM"] = fs_str("1") os.environ["GIT_AUTHOR_NAME"] = fs_str("pipenv") os.environ["GIT_AUTHOR_EMAIL"] = fs_str("*****@*****.**") os.environ["GIT_ASK_YESNO"] = fs_str("false") workon_home = create_tmpdir() os.environ["WORKON_HOME"] = fs_str(str(workon_home)) os.environ["HOME"] = os.path.abspath(home_dir) mkdir_p(os.path.join(home_dir, "projects")) # Ignore PIPENV_ACTIVE so that it works as under a bare environment. os.environ.pop("PIPENV_ACTIVE", None) os.environ.pop("VIRTUAL_ENV", None)
def pipenv(self, cmd, block=True): if self.pipfile_path and os.path.isfile(self.pipfile_path): os.environ['PIPENV_PIPFILE'] = fs_str(self.pipfile_path) # a bit of a hack to make sure the virtualenv is created with TemporaryDirectory(prefix='pipenv-', suffix='-cache') as tempdir: os.environ['PIPENV_CACHE_DIR'] = fs_str(tempdir.name) c = delegator.run('pipenv {0}'.format(cmd), block=block, cwd=os.path.abspath(self.path), env=os.environ.copy()) if 'PIPENV_CACHE_DIR' in os.environ: del os.environ['PIPENV_CACHE_DIR'] if 'PIPENV_PIPFILE' in os.environ: del os.environ['PIPENV_PIPFILE'] # Pretty output for failing tests. if block: print('$ pipenv {0}'.format(cmd)) print(c.out) print(c.err, file=sys.stderr) if c.return_code != 0: print("Command failed...") # Where the action happens. return c
def pipenv(self, cmd, block=True): if self.pipfile_path and os.path.isfile(self.pipfile_path): os.environ['PIPENV_PIPFILE'] = fs_str(self.pipfile_path) # a bit of a hack to make sure the virtualenv is created with TemporaryDirectory(prefix='pipenv-', suffix='-cache') as tempdir: cmd_args = shlex.split(cmd) env = {**self.env, **{'PIPENV_CACHE_DIR': tempdir.name}} self.capfd.readouterr() r = cli_runner.invoke(cli, cmd_args, env=env) r.returncode = r.exit_code # Pretty output for failing tests. out, err = self.capfd.readouterr() if out: r.stdout_bytes = r.stdout_bytes + out if err: r.stderr_bytes = r.stderr_bytes + err if block: print(f'$ pipenv {cmd}') print(r.stdout) print(r.stderr, file=sys.stderr) if r.exception: print(''.join(traceback.format_exception(*r.exc_info)), file=sys.stderr) if r.returncode != 0: print("Command failed...") # Where the action happens. return r
def PipenvInstance_NoPyPI(monkeypatch, pip_src_dir, pypi, capfdbinary): with temp_environ(), monkeypatch.context() as m: m.setattr(shutil, "rmtree", _rmtree_func) original_umask = os.umask(0o007) m.setenv("PIPENV_NOSPIN", fs_str("1")) m.setenv("CI", fs_str("1")) m.setenv('PIPENV_DONT_USE_PYENV', fs_str('1')) m.setenv("PIPENV_TEST_INDEX", f"{pypi.url}/simple") m.setenv("ARTIFACT_PYPI_URL", pypi.url) warnings.simplefilter("ignore", category=ResourceWarning) warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*<ssl.SSLSocket.*>") try: yield functools.partial(_PipenvInstance, capfd=capfdbinary) finally: os.umask(original_umask)
PIPENV_VENDOR = os.sep.join([PIPENV_ROOT, "vendor"]) PIPENV_PATCHED = os.sep.join([PIPENV_ROOT, "patched"]) # Inject vendored directory into system path. sys.path.insert(0, PIPENV_VENDOR) # Inject patched directory into system path. sys.path.insert(0, PIPENV_PATCHED) from pipenv.vendor.urllib3.exceptions import DependencyWarning from pipenv.vendor.vistir.compat import fs_str warnings.filterwarnings("ignore", category=DependencyWarning) warnings.filterwarnings("ignore", category=ResourceWarning) warnings.filterwarnings("ignore", category=UserWarning) # Load patched pip instead of system pip os.environ["PIP_SHIMS_BASE_MODULE"] = fs_str("pipenv.patched.notpip") os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = fs_str("1") # Hack to make things work better. try: if "concurrency" in sys.modules: del sys.modules["concurrency"] except Exception: pass if "urllib3" in sys.modules: del sys.modules["urllib3"] from pipenv.vendor.vistir.misc import get_text_stream stdout = get_text_stream("stdout") stderr = get_text_stream("stderr")
def finalize(): os.environ['PIP_SRC'] = fs_str(old_src_dir)
def __init__(self, pypi=None, pipfile=True, chdir=True, path=None, capfd=None, venv_root=None, ignore_virtualenvs=True, venv_in_project=True, name=None): self.index_url = os.getenv("PIPENV_TEST_INDEX") self.pypi = None self.env = {} self.capfd = capfd if pypi: self.pypi = pypi.url elif self.index_url is not None: self.pypi, _, _ = self.index_url.rpartition( "/") if self.index_url else "" self.index = os.getenv("PIPENV_PYPI_INDEX") self.env["PYTHONWARNINGS"] = "ignore:DEPRECATION" if ignore_virtualenvs: self.env["PIPENV_IGNORE_VIRTUALENVS"] = fs_str("1") if venv_root: self.env["VIRTUAL_ENV"] = venv_root if venv_in_project: self.env["PIPENV_VENV_IN_PROJECT"] = fs_str("1") else: self.env.pop("PIPENV_VENV_IN_PROJECT", None) self.original_dir = Path(__file__).parent.parent.parent path = path if path else os.environ.get("PIPENV_PROJECT_DIR", None) if name is not None: path = Path(os.environ["HOME"]) / "projects" / name path.mkdir(exist_ok=True) if not path: path = TemporaryDirectory(suffix='-project', prefix='pipenv-') if isinstance(path, TemporaryDirectory): self._path = path path = Path(self._path.name) try: self.path = str(path.resolve()) except OSError: self.path = str(path.absolute()) elif isinstance(path, Path): self._path = path try: self.path = str(path.resolve()) except OSError: self.path = str(path.absolute()) else: self._path = path self.path = path # set file creation perms self.pipfile_path = None self.chdir = chdir if self.pypi and "PIPENV_PYPI_URL" not in os.environ: self.env['PIPENV_PYPI_URL'] = fs_str(f'{self.pypi}') # os.environ['PIPENV_PYPI_URL'] = fs_str('{0}'.format(self.pypi.url)) # os.environ['PIPENV_TEST_INDEX'] = fs_str('{0}/simple'.format(self.pypi.url)) if pipfile: p_path = os.sep.join([self.path, 'Pipfile']) with open(p_path, 'a'): os.utime(p_path, None) self.chdir = False or chdir self.pipfile_path = p_path self._pipfile = _Pipfile(Path(p_path))
def finalize(): os.environ['TEMP'] = fs_str(old_temp) _rmtree_func(new_temp.as_posix())
def start_resolver(finder=None, session=None, wheel_cache=None): """Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pipenv.patched.notpip._internal.index.PackageFinder` :param :class:`~requests.Session` session: A session instance :param :class:`~pipenv.patched.notpip._internal.cache.WheelCache` wheel_cache: A pip WheelCache instance :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pipenv.patched.notpip._internal.operations.prepare.RequirementPreparer`, :class:`~pipenv.patched.notpip._internal.resolve.Resolver`) """ pip_command = get_pip_command() pip_options = get_pip_options(pip_command=pip_command) session = None if not finder: session, finder = get_finder(pip_command=pip_command, pip_options=pip_options) if not session: session = pip_command._build_session(pip_options) download_dir = PKGS_DOWNLOAD_DIR _ensure_dir(download_dir) _build_dir = create_tracked_tempdir(fs_str("build")) _source_dir = create_tracked_tempdir(fs_str("source")) try: with ExitStack() as ctx: ctx.enter_context(pip_shims.shims.global_tempdir_manager()) if not wheel_cache: wheel_cache = ctx.enter_context(_get_wheel_cache()) _ensure_dir(fs_str(os.path.join(wheel_cache.cache_dir, "wheels"))) preparer = ctx.enter_context( pip_shims.shims.make_preparer( options=pip_options, finder=finder, session=session, build_dir=_build_dir, src_dir=_source_dir, download_dir=download_dir, wheel_download_dir=WHEEL_DOWNLOAD_DIR, progress_bar="off", build_isolation=False, install_cmd=pip_command, )) resolver = pip_shims.shims.get_resolver( finder=finder, ignore_dependencies=False, ignore_requires_python=True, preparer=preparer, session=session, options=pip_options, install_cmd=pip_command, wheel_cache=wheel_cache, force_reinstall=True, ignore_installed=True, upgrade_strategy="to-satisfy-only", isolated=False, use_user_site=False, ) yield resolver finally: session.close()
from pipenv.vendor.pip_shims.shims import ( Command, InstallationCandidate, InstallRequirement, PackageFinder, ) TRequirement = TypeVar("TRequirement") RequirementType = TypeVar("RequirementType", covariant=True, bound=PackagingRequirement) MarkerType = TypeVar("MarkerType", covariant=True, bound=Marker) STRING_TYPE = Union[str, bytes, Text] S = TypeVar("S", bytes, str, Text) PKGS_DOWNLOAD_DIR = fs_str(os.path.join(CACHE_DIR, "pkgs")) WHEEL_DOWNLOAD_DIR = fs_str(os.path.join(CACHE_DIR, "wheels")) DEPENDENCY_CACHE = DependencyCache() @contextlib.contextmanager def _get_wheel_cache(): with pip_shims.shims.global_tempdir_manager(): yield pip_shims.shims.WheelCache( CACHE_DIR, pip_shims.shims.FormatControl(set(), set())) def _get_filtered_versions(ireq, versions, prereleases): return set(ireq.specifier.filter(versions, prereleases=prereleases))
PIPENV_VENDOR = os.sep.join([PIPENV_ROOT, "vendor"]) PIPENV_PATCHED = os.sep.join([PIPENV_ROOT, "patched"]) # Inject vendored directory into system path. sys.path.insert(0, PIPENV_VENDOR) # Inject patched directory into system path. sys.path.insert(0, PIPENV_PATCHED) from pipenv.vendor.urllib3.exceptions import DependencyWarning from pipenv.vendor.vistir.compat import ResourceWarning, fs_str warnings.filterwarnings("ignore", category=DependencyWarning) warnings.filterwarnings("ignore", category=ResourceWarning) warnings.filterwarnings("ignore", category=UserWarning) os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = fs_str("1") # Hack to make things work better. try: if "concurrency" in sys.modules: del sys.modules["concurrency"] except Exception: pass from pipenv.vendor.vistir.misc import get_text_stream stdout = get_text_stream("stdout") stderr = get_text_stream("stderr") if os.name == "nt": from pipenv.vendor.vistir.misc import _can_use_color, _wrap_for_color