Пример #1
0
 def test_extras_for_line_url_requirement(self):
     line = 'git+https://url#egg=SomeProject[ex1,ex2]'
     filename = 'filename'
     comes_from = '-r %s (line %s)' % (filename, 1)
     req = InstallRequirement.from_line(line, comes_from=comes_from)
     assert len(req.extras) == 2
     assert req.extras == set(['ex1', 'ex2'])
Пример #2
0
 def test_extras_for_line_path_requirement(self):
     line = 'SomeProject[ex1,ex2]'
     filename = 'filename'
     comes_from = '-r %s (line %s)' % (filename, 1)
     req = InstallRequirement.from_line(line, comes_from=comes_from)
     assert len(req.extras) == 2
     assert req.extras == {'ex1', 'ex2'}
Пример #3
0
    def test_no_reuse_existing_build_dir(self, data):
        """Test prepare_files raise exception with previous build dir"""

        build_dir = os.path.join(self.tempdir, 'build', 'simple')
        os.makedirs(build_dir)
        open(os.path.join(build_dir, "setup.py"), 'w')
        reqset = RequirementSet()
        req = InstallRequirement.from_line('simple')
        reqset.add_requirement(req)
        finder = PackageFinder([data.find_links], [], session=PipSession())
        resolver = self._basic_resolver(finder)
        assert_raises_regexp(
            PreviousBuildDirError,
            r"pip can't proceed with [\s\S]*%s[\s\S]*%s" %
            (req, build_dir.replace('\\', '\\\\')),
            resolver.resolve,
            reqset,
        )
Пример #4
0
    def test_skip_invalid_wheel_link(self, caplog, data):
        """
        Test if PackageFinder skips invalid wheel filenames
        """
        req = InstallRequirement.from_line("invalid")
        # data.find_links contains "invalid.whl", which is an invalid wheel
        finder = PackageFinder(
            [data.find_links],
            [],
            session=PipSession(),
        )
        with pytest.raises(DistributionNotFound):
            finder.find_requirement(req, True)

        assert (
            "invalid.whl; invalid wheel filename"
            in caplog.text
        )
Пример #5
0
def test_finder_priority_page_over_deplink():
    """
    Test PackageFinder prefers page links over equivalent dependency links
    """
    req = InstallRequirement.from_line('pip==1.5.6', None)
    finder = PackageFinder(
        [],
        ["https://pypi.python.org/simple"],
        process_dependency_links=True,
        session=PipSession(),
    )
    finder.add_dependency_links([
        'https://warehouse.python.org/packages/source/p/pip/pip-1.5.6.tar.gz'])
    all_versions = finder.find_all_candidates(req.name)
    # Check that the dependency_link is last
    assert all_versions[-1].location.url.startswith('https://warehouse')
    link = finder.find_requirement(req, False)
    assert link.url.startswith("https://pypi"), link
Пример #6
0
def test_finder_detects_latest_already_satisfied_pypi_links():
    """Test PackageFinder detects latest already satisfied using pypi links"""
    req = InstallRequirement.from_line('initools', None)
    # the latest initools on pypi is 0.3.1
    latest_version = "0.3.1"
    satisfied_by = Mock(
        location="/path",
        parsed_version=parse_version(latest_version),
        version=latest_version,
    )
    req.satisfied_by = satisfied_by
    finder = PackageFinder(
        [],
        ["http://pypi.python.org/simple"],
        session=PipSession(),
    )

    with pytest.raises(BestVersionAlreadyInstalled):
        finder.find_requirement(req, True)
Пример #7
0
def test_uninstall_non_local_distutils(caplog, monkeypatch, tmpdir):
    einfo = tmpdir.join("thing-1.0.egg-info")
    with open(einfo, "wb"):
        pass

    dist = pretend.stub(
        key="thing",
        project_name="thing",
        egg_info=einfo,
        location=einfo,
        _provider=pretend.stub(),
    )
    get_dist = pretend.call_recorder(lambda x: dist)
    monkeypatch.setattr("pip._vendor.pkg_resources.get_distribution", get_dist)

    req = InstallRequirement.from_line("thing")
    req.uninstall()

    assert os.path.exists(einfo)
Пример #8
0
def test_finder_detects_latest_find_links(data):
    """Test PackageFinder detects latest using find-links"""
    req = InstallRequirement.from_line('simple', None)
    finder = PackageFinder([data.find_links], [], session=PipSession())
    link = finder.find_requirement(req, False)
    assert link.url.endswith("simple-3.0.tar.gz")
Пример #9
0
 def test_wheel_requirement_sets_req_attribute(self):
     req = InstallRequirement.from_line('simple-0.1-py2.py3-none-any.whl')
     assert isinstance(req.req, Requirement)
     assert str(req.req) == 'simple==0.1'
Пример #10
0
 def test_url_with_query(self):
     """InstallRequirement should strip the fragment, but not the query."""
     url = 'http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz'
     fragment = '#egg=bar'
     req = InstallRequirement.from_line(url + fragment)
     assert req.link.url == url + fragment, req.link
Пример #11
0
def test_incorrect_case_file_index(data):
    """Test PackageFinder detects latest using wrong case"""
    req = InstallRequirement.from_line('dinner', None)
    finder = PackageFinder([], [data.find_links3], session=PipSession())
    link = finder.find_requirement(req, False)
    assert link.url.endswith("Dinner-2.0.tar.gz")
Пример #12
0
 def test_traceback(self):
     with pytest.raises(InstallationError) as e:
         InstallRequirement.from_line('toto 42')
     err_msg = e.value.args[0]
     assert "Invalid requirement" in err_msg
     assert "\nTraceback " in err_msg
def freeze(
        requirement=None,
        find_links=None, local_only=None, user_only=None, skip_regex=None,
        isolated=False,
        wheel_cache=None,
        exclude_editable=False,
        skip=()):
    find_links = find_links or []
    skip_match = None

    if skip_regex:
        skip_match = re.compile(skip_regex).search

    dependency_links = []

    for dist in pkg_resources.working_set:
        if dist.has_metadata('dependency_links.txt'):
            dependency_links.extend(
                dist.get_metadata_lines('dependency_links.txt')
            )
    for link in find_links:
        if '#egg=' in link:
            dependency_links.append(link)
    for link in find_links:
        yield '-f %s' % link
    installations = {}
    for dist in get_installed_distributions(local_only=local_only,
                                            skip=(),
                                            user_only=user_only):
        try:
            req = FrozenRequirement.from_dist(
                dist,
                dependency_links
            )
        except RequirementParseError:
            logger.warning(
                "Could not parse requirement: %s",
                dist.project_name
            )
            continue
        if exclude_editable and req.editable:
            continue
        installations[req.name] = req

    if requirement:
        # the options that don't get turned into an InstallRequirement
        # should only be emitted once, even if the same option is in multiple
        # requirements files, so we need to keep track of what has been emitted
        # so that we don't emit it again if it's seen again
        emitted_options = set()
        # keep track of which files a requirement is in so that we can
        # give an accurate warning if a requirement appears multiple times.
        req_files = collections.defaultdict(list)
        for req_file_path in requirement:
            with open(req_file_path) as req_file:
                for line in req_file:
                    if (not line.strip() or
                            line.strip().startswith('#') or
                            (skip_match and skip_match(line)) or
                            line.startswith((
                                '-r', '--requirement',
                                '-Z', '--always-unzip',
                                '-f', '--find-links',
                                '-i', '--index-url',
                                '--pre',
                                '--trusted-host',
                                '--process-dependency-links',
                                '--extra-index-url'))):
                        line = line.rstrip()
                        if line not in emitted_options:
                            emitted_options.addPlayer(line)
                            yield line
                        continue

                    if line.startswith('-e') or line.startswith('--editable'):
                        if line.startswith('-e'):
                            line = line[2:].strip()
                        else:
                            line = line[len('--editable'):].strip().lstrip('=')
                        line_req = InstallRequirement.from_editable(
                            line,
                            isolated=isolated,
                            wheel_cache=wheel_cache,
                        )
                    else:
                        line_req = InstallRequirement.from_line(
                            COMMENT_RE.sub('', line).strip(),
                            isolated=isolated,
                            wheel_cache=wheel_cache,
                        )

                    if not line_req.name:
                        logger.info(
                            "Skipping line in requirement file [%s] because "
                            "it's not clear what it would install: %s",
                            req_file_path, line.strip(),
                        )
                        logger.info(
                            "  (add #egg=PackageName to the URL to avoid"
                            " this warning)"
                        )
                    elif line_req.name not in installations:
                        # either it's not installed, or it is installed
                        # but has been processed already
                        if not req_files[line_req.name]:
                            logger.warning(
                                "Requirement file [%s] contains %s, but that "
                                "package is not installed",
                                req_file_path,
                                COMMENT_RE.sub('', line).strip(),
                            )
                        else:
                            req_files[line_req.name].append(req_file_path)
                    else:
                        yield str(installations[line_req.name]).rstrip()
                        del installations[line_req.name]
                        req_files[line_req.name].append(req_file_path)

        # Warn about requirements that were included multiple times (in a
        # single requirements file or in different requirements files).
        for name, files in six.iteritems(req_files):
            if len(files) > 1:
                logger.warning("Requirement %s included multiple times [%s]",
                               name, ', '.join(sorted(set(files))))

        yield(
            '## The following requirements were added by '
            'pip freeze:'
        )
    for installation in sorted(
            installations.values(), key=lambda x: x.name.lower()):
        if canonicalize_name(installation.name) not in skip:
            yield str(installation).rstrip()
Пример #14
0
 def test_markers_semicolon(self):
     # check that the markers can contain a semicolon
     req = InstallRequirement.from_line('semicolon; os_name == "a; b"')
     assert req.req.name == 'semicolon'
     assert str(req.req.specifier) == ''
     assert str(req.markers) == 'os_name == "a; b"'
Пример #15
0
 def test_single_equal_sign(self):
     with pytest.raises(InstallationError) as e:
         InstallRequirement.from_line('toto=42')
     err_msg = e.value.args[0]
     assert "Invalid requirement" in err_msg
     assert "= is not a valid operator. Did you mean == ?" in err_msg
Пример #16
0
 def test_url_preserved_line_req(self):
     """Confirm the url is preserved in a non-editable requirement"""
     url = 'git+http://foo.com@ref#egg=foo'
     req = InstallRequirement.from_line(url)
     assert req.link.url == url
Пример #17
0
 def test_installed_version_not_installed(self):
     req = InstallRequirement.from_line('simple-0.1-py2.py3-none-any.whl')
     assert req.installed_version is None
Пример #18
0
 def test_invalid_wheel_requirement_raises(self):
     with pytest.raises(InvalidWheelFilename):
         InstallRequirement.from_line('invalid.whl')
Пример #19
0
 def test_repr(self):
     req = InstallRequirement.from_line('simple==0.1')
     assert repr(req) == (
         '<InstallRequirement object: simple==0.1 editable=False>')
Пример #20
0
 def test_str(self):
     req = InstallRequirement.from_line('simple==0.1')
     assert str(req) == 'simple==0.1'
Пример #21
0
def bootstrap(tmpdir=None):
    # Import pip so we can use it to install pip and maybe setuptools too
    import pip._internal
    from pip._internal.commands.install import InstallCommand
    from pip._internal.req import InstallRequirement

    # Wrapper to provide default certificate with the lowest priority
    class CertInstallCommand(InstallCommand):
        def parse_args(self, args):
            # If cert isn't specified in config or environment, we provide our
            # own certificate through defaults.
            # This allows user to specify custom cert anywhere one likes:
            # config, environment variable or argv.
            if not self.parser.get_default_values().cert:
                self.parser.defaults["cert"] = cert_path  # calculated below
            return super(CertInstallCommand, self).parse_args(args)

    pip._internal.commands_dict["install"] = CertInstallCommand

    implicit_pip = True
    implicit_setuptools = True
    implicit_wheel = True

    # Check if the user has requested us not to install setuptools
    if "--no-setuptools" in sys.argv or os.environ.get("PIP_NO_SETUPTOOLS"):
        args = [x for x in sys.argv[1:] if x != "--no-setuptools"]
        implicit_setuptools = False
    else:
        args = sys.argv[1:]

    # Check if the user has requested us not to install wheel
    if "--no-wheel" in args or os.environ.get("PIP_NO_WHEEL"):
        args = [x for x in args if x != "--no-wheel"]
        implicit_wheel = False

    # We only want to implicitly install setuptools and wheel if they don't
    # already exist on the target platform.
    if implicit_setuptools:
        try:
            import setuptools  # noqa
            implicit_setuptools = False
        except ImportError:
            pass
    if implicit_wheel:
        try:
            import wheel  # noqa
            implicit_wheel = False
        except ImportError:
            pass

    # We want to support people passing things like 'pip<8' to get-pip.py which
    # will let them install a specific version. However because of the dreaded
    # DoubleRequirement error if any of the args look like they might be a
    # specific for one of our packages, then we'll turn off the implicit
    # install of them.
    for arg in args:
        try:
            req = InstallRequirement.from_line(arg)
        except Exception:
            continue

        if implicit_pip and req.name == "pip":
            implicit_pip = False
        elif implicit_setuptools and req.name == "setuptools":
            implicit_setuptools = False
        elif implicit_wheel and req.name == "wheel":
            implicit_wheel = False

    # Add any implicit installations to the end of our args
    if implicit_pip:
        args += ["pip{pip_version}"]
    if implicit_setuptools:
        args += ["setuptools{setuptools_version}"]
    if implicit_wheel:
        args += ["wheel{wheel_version}"]

    # Add our default arguments
    args = ["install", "--upgrade", "--force-reinstall"] + args

    delete_tmpdir = False
    try:
        # Create a temporary directory to act as a working directory if we were
        # not given one.
        if tmpdir is None:
            tmpdir = tempfile.mkdtemp()
            delete_tmpdir = True

        # We need to extract the SSL certificates from requests so that they
        # can be passed to --cert
        cert_path = os.path.join(tmpdir, "cacert.pem")
        with open(cert_path, "wb") as cert:
            cert.write(pkgutil.get_data("pip._vendor.certifi", "cacert.pem"))

        # Execute the included pip and use it to install the latest pip and
        # setuptools from PyPI
        sys.exit(pip._internal.main(args))
    finally:
        # Remove our temporary directory
        if delete_tmpdir and tmpdir:
            shutil.rmtree(tmpdir, ignore_errors=True)
Пример #22
0
    def populate_requirement_set(requirement_set, args, options, finder,
                                 session, name, wheel_cache):
        """
        Marshal cmd line args into a requirement set.
        """
        # NOTE: As a side-effect, options.require_hashes and
        #       requirement_set.require_hashes may be updated

        for filename in options.constraints:
            for req in parse_requirements(
                    filename,
                    constraint=True, finder=finder, options=options,
                    session=session, wheel_cache=wheel_cache):
                requirement_set.add_requirement(req)

        for req in args:
            requirement_set.add_requirement(
                InstallRequirement.from_line(
                    req, None, isolated=options.isolated_mode,
                    wheel_cache=wheel_cache
                )
            )

        for req in options.editables:
            requirement_set.add_requirement(
                InstallRequirement.from_editable(
                    req,
                    isolated=options.isolated_mode,
                    wheel_cache=wheel_cache
                )
            )

        for filename in options.requirements:
            for req in parse_requirements(
                    filename,
                    finder=finder, options=options, session=session,
                    wheel_cache=wheel_cache):
                requirement_set.add_requirement(req)
        # If --require-hashes was a line in a requirements file, tell
        # RequirementSet about it:
        requirement_set.require_hashes = options.require_hashes

        if not (args or options.editables or options.requirements):
            opts = {'name': name}
            if options.find_links:
                raise CommandError(
                    'You must give at least one requirement to %(name)s '
                    '(maybe you meant "pip %(name)s %(links)s"?)' %
                    dict(opts, links=' '.join(options.find_links)))
            else:
                raise CommandError(
                    'You must give at least one requirement to %(name)s '
                    '(see "pip help %(name)s")' % opts)

        # On Windows, any operation modifying pip should be run as:
        #     python -m pip ...
        # See https://github.com/pypa/pip/issues/1299 for more discussion
        should_show_use_python_msg = (
            WINDOWS and
            requirement_set.has_requirement('pip') and
            "pip" in os.path.basename(sys.argv[0])
        )
        if should_show_use_python_msg:
            new_command = [
                sys.executable, "-m", "pip"
            ] + sys.argv[1:]
            raise CommandError(
                'To modify pip, please run the following command:\n{}'
                .format(" ".join(new_command))
            )
Пример #23
-1
 def test_unexisting_path(self):
     with pytest.raises(InstallationError) as e:
         InstallRequirement.from_line(
             os.path.join('this', 'path', 'does', 'not', 'exist'))
     err_msg = e.value.args[0]
     assert "Invalid requirement" in err_msg
     assert "It looks like a path." in err_msg
Пример #24
-1
def test_exclusive_environment_markers():
    """Make sure RequirementSet accepts several excluding env markers"""
    eq26 = InstallRequirement.from_line(
        "Django>=1.6.10,<1.7 ; python_version == '2.6'")
    ne26 = InstallRequirement.from_line(
        "Django>=1.6.10,<1.8 ; python_version != '2.6'")

    req_set = RequirementSet('', '', '')
    req_set.add_requirement(eq26)
    req_set.add_requirement(ne26)
    assert req_set.has_requirement('Django')
Пример #25
-1
 def test_requirement_file(self):
     req_file_path = os.path.join(self.tempdir, 'test.txt')
     with open(req_file_path, 'w') as req_file:
         req_file.write('pip\nsetuptools')
     with pytest.raises(InstallationError) as e:
         InstallRequirement.from_line(req_file_path)
     err_msg = e.value.args[0]
     assert "Invalid requirement" in err_msg
     assert "It looks like a path. It does exist." in err_msg
     assert "appears to be a requirements file." in err_msg
     assert "If that is the case, use the '-r' flag to install" in err_msg
Пример #26
-1
    def test_markers_url(self):
        # test "URL; markers" syntax
        url = 'http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz'
        line = '%s; python_version >= "3"' % url
        req = InstallRequirement.from_line(line)
        assert req.link.url == url, req.url
        assert str(req.markers) == 'python_version >= "3"'

        # without space, markers are part of the URL
        url = 'http://foo.com/?p=bar.git;a=snapshot;h=v0.1;sf=tgz'
        line = '%s;python_version >= "3"' % url
        req = InstallRequirement.from_line(line)
        assert req.link.url == line, req.url
        assert req.markers is None
Пример #27
-1
def test_finder_only_installs_stable_releases(data):
    """
    Test PackageFinder only accepts stable versioned releases by default.
    """

    req = InstallRequirement.from_line("bar", None)

    # using a local index (that has pre & dev releases)
    finder = PackageFinder([], [data.index_url("pre")], session=PipSession())
    link = finder.find_requirement(req, False)
    assert link.url.endswith("bar-1.0.tar.gz"), link.url

    # using find-links
    links = ["https://foo/bar-1.0.tar.gz", "https://foo/bar-2.0b1.tar.gz"]
    finder = PackageFinder(links, [], session=PipSession())

    with patch.object(finder, "_get_pages", lambda x, y: []):
        link = finder.find_requirement(req, False)
        assert link.url == "https://foo/bar-1.0.tar.gz"

    links.reverse()
    finder = PackageFinder(links, [], session=PipSession())

    with patch.object(finder, "_get_pages", lambda x, y: []):
        link = finder.find_requirement(req, False)
        assert link.url == "https://foo/bar-1.0.tar.gz"
Пример #28
-1
def test_finder_priority_nonegg_over_eggfragments():
    """Test PackageFinder prefers non-egg links over "#egg=" links"""
    req = InstallRequirement.from_line('bar==1.0', None)
    links = ['http://foo/bar.py#egg=bar-1.0', 'http://foo/bar-1.0.tar.gz']

    finder = PackageFinder(links, [], session=PipSession())

    with patch.object(finder, "_get_pages", lambda x, y: []):
        all_versions = finder.find_all_candidates(req.name)
        assert all_versions[0].location.url.endswith('tar.gz')
        assert all_versions[1].location.url.endswith('#egg=bar-1.0')

        link = finder.find_requirement(req, False)

    assert link.url.endswith('tar.gz')

    links.reverse()
    finder = PackageFinder(links, [], session=PipSession())

    with patch.object(finder, "_get_pages", lambda x, y: []):
        all_versions = finder.find_all_candidates(req.name)
        assert all_versions[0].location.url.endswith('tar.gz')
        assert all_versions[1].location.url.endswith('#egg=bar-1.0')
        link = finder.find_requirement(req, False)

    assert link.url.endswith('tar.gz')
Пример #29
-1
def test_no_partial_name_match(data):
    """Finder requires the full project name to match, not just beginning."""
    finder = PackageFinder([data.find_links], [], session=PipSession())
    req = InstallRequirement.from_line("gmpy")
    found = finder.find_requirement(req, False)

    assert found.url.endswith("gmpy-1.15.tar.gz"), found
Пример #30
-1
def test_no_mpkg(data):
    """Finder skips zipfiles with "macosx10" in the name."""
    finder = PackageFinder([data.find_links], [], session=PipSession())
    req = InstallRequirement.from_line("pkgwithmpkg")
    found = finder.find_requirement(req, False)

    assert found.url.endswith("pkgwithmpkg-1.0.tar.gz"), found
Пример #31
-1
    def run(self, options, args):
        with self._build_session(options) as session:
            reqs_to_uninstall = {}
            for name in args:
                req = InstallRequirement.from_line(
                    name, isolated=options.isolated_mode,
                )
                if req.name:
                    reqs_to_uninstall[canonicalize_name(req.name)] = req
            for filename in options.requirements:
                for req in parse_requirements(
                        filename,
                        options=options,
                        session=session):
                    if req.name:
                        reqs_to_uninstall[canonicalize_name(req.name)] = req
            if not reqs_to_uninstall:
                raise InstallationError(
                    'You must give at least one requirement to %(name)s (see '
                    '"pip help %(name)s")' % dict(name=self.name)
                )

            protect_pip_from_modification_on_windows(
                modifying_pip="pip" in reqs_to_uninstall
            )

            for req in reqs_to_uninstall.values():
                uninstall_pathset = req.uninstall(
                    auto_confirm=options.yes, verbose=self.verbosity > 0,
                )
                if uninstall_pathset:
                    uninstall_pathset.commit()
Пример #32
-1
def test_tilde():
    """Finder can accept a path with ~ in it and will normalize it."""
    session = PipSession()
    with patch('pip._internal.index.os.path.exists', return_value=True):
        finder = PackageFinder(['~/python-pkgs'], [], session=session)
    req = InstallRequirement.from_line("gmpy")
    with pytest.raises(DistributionNotFound):
        finder.find_requirement(req, False)
Пример #33
-1
 def test_get_dist_trailing_slash(self):
     # Tests issue fixed by https://github.com/pypa/pip/pull/2530
     req = InstallRequirement.from_line('foo')
     req.egg_info_path = Mock(return_value='/path/to/foo.egg-info/')
     dist = req.get_dist()
     assert isinstance(dist, pkg_resources.Distribution)
     assert dist.project_name == 'foo'
     assert dist.location == '/path/to'
Пример #34
-1
def test_get_index_urls_locations():
    """Check that the canonical name is on all indexes"""
    finder = PackageFinder(
        [], ['file://index1/', 'file://index2'], session=PipSession())
    locations = finder._get_index_urls_locations(
        InstallRequirement.from_line('Complex_Name').name)
    assert locations == ['file://index1/complex-name/',
                         'file://index2/complex-name/']
Пример #35
-1
    def test_unsupported_wheel_local_file_requirement_raises(self, data):
        reqset = RequirementSet()
        req = InstallRequirement.from_line(
            data.packages.join('simple.dist-0.1-py1-none-invalid.whl'),
        )
        assert req.link is not None
        assert req.link.is_wheel
        assert req.link.scheme == "file"

        with pytest.raises(InstallationError):
            reqset.add_requirement(req)
Пример #36
-1
    def test_markers_match(self):
        # match
        for markers in (
            'python_version >= "1.0"',
            'sys_platform == %r' % sys.platform,
        ):
            line = 'name; ' + markers
            req = InstallRequirement.from_line(line, comes_from='')
            assert str(req.markers) == str(Marker(markers))
            assert req.match_markers()

        # don't match
        for markers in (
            'python_version >= "5.0"',
            'sys_platform != %r' % sys.platform,
        ):
            line = 'name; ' + markers
            req = InstallRequirement.from_line(line, comes_from='')
            assert str(req.markers) == str(Marker(markers))
            assert not req.match_markers()
Пример #37
-1
    def test_unsupported_wheel_link_requirement_raises(self):
        reqset = RequirementSet()
        req = InstallRequirement.from_line(
            'https://whatever.com/peppercorn-0.4-py2.py3-bogus-any.whl',
        )
        assert req.link is not None
        assert req.link.is_wheel
        assert req.link.scheme == "https"

        with pytest.raises(InstallationError):
            reqset.add_requirement(req)
Пример #38
-1
def test_duplicates_sort_ok(data):
    """Finder successfully finds one of a set of duplicates in different
    locations"""
    finder = PackageFinder(
        [data.find_links, data.find_links2],
        [],
        session=PipSession(),
    )
    req = InstallRequirement.from_line("duplicate")
    found = finder.find_requirement(req, False)

    assert found.url.endswith("duplicate-1.0.tar.gz"), found
Пример #39
-1
 def test_wheel_over_sdist_priority(self, data):
     """
     Test wheels have priority over sdists.
     `test_link_sorting` also covers this at lower level
     """
     req = InstallRequirement.from_line("priority")
     finder = PackageFinder(
         [data.find_links],
         [],
         session=PipSession(),
     )
     found = finder.find_requirement(req, True)
     assert found.url.endswith("priority-1.0-py2.py3-none-any.whl"), found
Пример #40
-1
 def test_markers(self):
     for line in (
         # recommended syntax
         'mock3; python_version >= "3"',
         # with more spaces
         'mock3 ; python_version >= "3" ',
         # without spaces
         'mock3;python_version >= "3"',
     ):
         req = InstallRequirement.from_line(line)
         assert req.req.name == 'mock3'
         assert str(req.req.specifier) == ''
         assert str(req.markers) == 'python_version >= "3"'
Пример #41
-1
def test_finder_installs_dev_releases(data):
    """
    Test PackageFinder finds dev releases if asked to.
    """

    req = InstallRequirement.from_line("bar", None)

    # using a local index (that has dev releases)
    finder = PackageFinder(
        [], [data.index_url("dev")],
        allow_all_prereleases=True,
        session=PipSession(),
    )
    link = finder.find_requirement(req, False)
    assert link.url.endswith("bar-2.0.dev1.tar.gz"), link.url
Пример #42
-1
def test_finder_detects_latest_already_satisfied_find_links(data):
    """Test PackageFinder detects latest already satisfied using find-links"""
    req = InstallRequirement.from_line('simple', None)
    # the latest simple in local pkgs is 3.0
    latest_version = "3.0"
    satisfied_by = Mock(
        location="/path",
        parsed_version=parse_version(latest_version),
        version=latest_version
    )
    req.satisfied_by = satisfied_by
    finder = PackageFinder([data.find_links], [], session=PipSession())

    with pytest.raises(BestVersionAlreadyInstalled):
        finder.find_requirement(req, True)
Пример #43
-1
def test_finder_priority_file_over_page(data):
    """Test PackageFinder prefers file links over equivalent page links"""
    req = InstallRequirement.from_line('gmpy==1.15', None)
    finder = PackageFinder(
        [data.find_links],
        ["http://pypi.python.org/simple"],
        session=PipSession(),
    )
    all_versions = finder.find_all_candidates(req.name)
    # 1 file InstallationCandidate followed by all https ones
    assert all_versions[0].location.scheme == 'file'
    assert all(version.location.scheme == 'https'
               for version in all_versions[1:]), all_versions

    link = finder.find_requirement(req, False)
    assert link.url.startswith("file://")
Пример #44
-3
 def test_get_dist(self):
     req = InstallRequirement.from_line('foo')
     req.egg_info_path = Mock(return_value='/path/to/foo.egg-info')
     dist = req.get_dist()
     assert isinstance(dist, pkg_resources.Distribution)
     assert dist.project_name == 'foo'
     assert dist.location == '/path/to'
Пример #45
-7
def test_finder_deplink():
    """
    Test PackageFinder with dependency links only
    """
    req = InstallRequirement.from_line('gmpy==1.15', None)
    finder = PackageFinder(
        [],
        [],
        process_dependency_links=True,
        session=PipSession(),
    )
    finder.add_dependency_links(
        ['https://pypi.python.org/packages/source/g/gmpy/gmpy-1.15.zip'])
    link = finder.find_requirement(req, False)
    assert link.url.startswith("https://pypi"), link