summaryrefslogtreecommitdiff
path: root/tests/unit/test_finder.py
blob: 9638199fbf1a64e40000d76721f025ef0932d173 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
import logging
import sys
from unittest.mock import Mock, patch

import pytest
from pip._vendor.packaging.specifiers import SpecifierSet
from pip._vendor.packaging.tags import Tag
from pkg_resources import parse_version

import pip._internal.utils.compatibility_tags
from pip._internal.exceptions import BestVersionAlreadyInstalled, DistributionNotFound
from pip._internal.index.package_finder import (
    CandidateEvaluator,
    InstallationCandidate,
    Link,
    LinkEvaluator,
)
from pip._internal.models.target_python import TargetPython
from pip._internal.req.constructors import install_req_from_line
from tests.lib import make_test_finder


def make_no_network_finder(
    find_links,
    allow_all_prereleases=False,  # type: bool
):
    """
    Create and return a PackageFinder instance for test purposes that
    doesn't make any network requests when _get_pages() is called.
    """
    finder = make_test_finder(
        find_links=find_links,
        allow_all_prereleases=allow_all_prereleases,
    )
    # Replace the PackageFinder._link_collector's _get_pages() with a no-op.
    link_collector = finder._link_collector
    link_collector._get_pages = lambda locations: []

    return finder


def test_no_mpkg(data):
    """Finder skips zipfiles with "macosx10" in the name."""
    finder = make_test_finder(find_links=[data.find_links])
    req = install_req_from_line("pkgwithmpkg")
    found = finder.find_requirement(req, False)

    assert found.link.url.endswith("pkgwithmpkg-1.0.tar.gz"), found


def test_no_partial_name_match(data):
    """Finder requires the full project name to match, not just beginning."""
    finder = make_test_finder(find_links=[data.find_links])
    req = install_req_from_line("gmpy")
    found = finder.find_requirement(req, False)

    assert found.link.url.endswith("gmpy-1.15.tar.gz"), found


def test_tilde():
    """Finder can accept a path with ~ in it and will normalize it."""
    patched_exists = patch(
        'pip._internal.index.collector.os.path.exists', return_value=True
    )
    with patched_exists:
        finder = make_test_finder(find_links=['~/python-pkgs'])
    req = install_req_from_line("gmpy")
    with pytest.raises(DistributionNotFound):
        finder.find_requirement(req, False)


def test_duplicates_sort_ok(data):
    """Finder successfully finds one of a set of duplicates in different
    locations"""
    finder = make_test_finder(find_links=[data.find_links, data.find_links2])
    req = install_req_from_line("duplicate")
    found = finder.find_requirement(req, False)

    assert found.link.url.endswith("duplicate-1.0.tar.gz"), found


def test_finder_detects_latest_find_links(data):
    """Test PackageFinder detects latest using find-links"""
    req = install_req_from_line('simple', None)
    finder = make_test_finder(find_links=[data.find_links])
    found = finder.find_requirement(req, False)
    assert found.link.url.endswith("simple-3.0.tar.gz")


def test_incorrect_case_file_index(data):
    """Test PackageFinder detects latest using wrong case"""
    req = install_req_from_line('dinner', None)
    finder = make_test_finder(index_urls=[data.find_links3])
    found = finder.find_requirement(req, False)
    assert found.link.url.endswith("Dinner-2.0.tar.gz")


@pytest.mark.network
def test_finder_detects_latest_already_satisfied_find_links(data):
    """Test PackageFinder detects latest already satisfied using find-links"""
    req = install_req_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 = make_test_finder(find_links=[data.find_links])

    with pytest.raises(BestVersionAlreadyInstalled):
        finder.find_requirement(req, True)


@pytest.mark.network
def test_finder_detects_latest_already_satisfied_pypi_links():
    """Test PackageFinder detects latest already satisfied using pypi links"""
    req = install_req_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 = make_test_finder(index_urls=["http://pypi.org/simple/"])

    with pytest.raises(BestVersionAlreadyInstalled):
        finder.find_requirement(req, True)


class TestWheel:

    def test_skip_invalid_wheel_link(self, caplog, data):
        """
        Test if PackageFinder skips invalid wheel filenames
        """
        caplog.set_level(logging.DEBUG)

        req = install_req_from_line("invalid")
        # data.find_links contains "invalid.whl", which is an invalid wheel
        finder = make_test_finder(find_links=[data.find_links])
        with pytest.raises(DistributionNotFound):
            finder.find_requirement(req, True)

        assert 'Skipping link: invalid wheel filename:' in caplog.text

    def test_not_find_wheel_not_supported(self, data, monkeypatch):
        """
        Test not finding an unsupported wheel.
        """
        req = install_req_from_line("simple.dist")
        target_python = TargetPython()
        # Make sure no tags will match.
        target_python._valid_tags = []
        finder = make_test_finder(
            find_links=[data.find_links],
            target_python=target_python,
        )

        with pytest.raises(DistributionNotFound):
            finder.find_requirement(req, True)

    def test_find_wheel_supported(self, data, monkeypatch):
        """
        Test finding supported wheel.
        """
        monkeypatch.setattr(
            pip._internal.utils.compatibility_tags,
            "get_supported",
            lambda **kw: [('py2', 'none', 'any')],
        )

        req = install_req_from_line("simple.dist")
        finder = make_test_finder(find_links=[data.find_links])
        found = finder.find_requirement(req, True)
        assert (
            found.link.url.endswith("simple.dist-0.1-py2.py3-none-any.whl")
        ), found

    def test_wheel_over_sdist_priority(self, data):
        """
        Test wheels have priority over sdists.
        `test_link_sorting` also covers this at lower level
        """
        req = install_req_from_line("priority")
        finder = make_test_finder(find_links=[data.find_links])
        found = finder.find_requirement(req, True)
        assert found.link.url.endswith("priority-1.0-py2.py3-none-any.whl"), \
            found

    def test_existing_over_wheel_priority(self, data):
        """
        Test existing install has priority over wheels.
        `test_link_sorting` also covers this at a lower level
        """
        req = install_req_from_line('priority', None)
        latest_version = "1.0"
        satisfied_by = Mock(
            location="/path",
            parsed_version=parse_version(latest_version),
            version=latest_version,
        )
        req.satisfied_by = satisfied_by
        finder = make_test_finder(find_links=[data.find_links])

        with pytest.raises(BestVersionAlreadyInstalled):
            finder.find_requirement(req, True)


class TestCandidateEvaluator:
    def test_link_sorting(self):
        """
        Test link sorting
        """
        links = [
            InstallationCandidate("simple", "2.0", Link('simple-2.0.tar.gz')),
            InstallationCandidate(
                "simple",
                "1.0",
                Link('simple-1.0-pyT-none-TEST.whl'),
            ),
            InstallationCandidate(
                "simple",
                '1.0',
                Link('simple-1.0-pyT-TEST-any.whl'),
            ),
            InstallationCandidate(
                "simple",
                '1.0',
                Link('simple-1.0-pyT-none-any.whl'),
            ),
            InstallationCandidate(
                "simple",
                '1.0',
                Link('simple-1.0.tar.gz'),
            ),
        ]
        valid_tags = [
            Tag('pyT', 'none', 'TEST'),
            Tag('pyT', 'TEST', 'any'),
            Tag('pyT', 'none', 'any'),
        ]
        specifier = SpecifierSet()
        evaluator = CandidateEvaluator(
            'my-project', supported_tags=valid_tags, specifier=specifier,
        )
        sort_key = evaluator._sort_key
        results = sorted(links, key=sort_key, reverse=True)
        results2 = sorted(reversed(links), key=sort_key, reverse=True)

        assert links == results, results
        assert links == results2, results2

    def test_link_sorting_wheels_with_build_tags(self):
        """Verify build tags affect sorting."""
        links = [
            InstallationCandidate(
                "simplewheel",
                "2.0",
                Link("simplewheel-2.0-1-py2.py3-none-any.whl"),
            ),
            InstallationCandidate(
                "simplewheel",
                "2.0",
                Link("simplewheel-2.0-py2.py3-none-any.whl"),
            ),
            InstallationCandidate(
                "simplewheel",
                "1.0",
                Link("simplewheel-1.0-py2.py3-none-any.whl"),
            ),
        ]
        candidate_evaluator = CandidateEvaluator.create('my-project')
        sort_key = candidate_evaluator._sort_key
        results = sorted(links, key=sort_key, reverse=True)
        results2 = sorted(reversed(links), key=sort_key, reverse=True)

        assert links == results, results
        assert links == results2, results2

    def test_build_tag_is_less_important_than_other_tags(self):
        links = [
            InstallationCandidate(
                "simple",
                "1.0",
                Link('simple-1.0-1-py3-abi3-linux_x86_64.whl'),
            ),
            InstallationCandidate(
                "simple",
                '1.0',
                Link('simple-1.0-2-py3-abi3-linux_i386.whl'),
            ),
            InstallationCandidate(
                "simple",
                '1.0',
                Link('simple-1.0-2-py3-any-none.whl'),
            ),
            InstallationCandidate(
                "simple",
                '1.0',
                Link('simple-1.0.tar.gz'),
            ),
        ]
        valid_tags = [
            Tag('py3', 'abi3', 'linux_x86_64'),
            Tag('py3', 'abi3', 'linux_i386'),
            Tag('py3', 'any', 'none'),
        ]
        evaluator = CandidateEvaluator(
            'my-project', supported_tags=valid_tags, specifier=SpecifierSet(),
        )
        sort_key = evaluator._sort_key
        results = sorted(links, key=sort_key, reverse=True)
        results2 = sorted(reversed(links), key=sort_key, reverse=True)

        assert links == results, results
        assert links == results2, results2


def test_finder_priority_file_over_page(data):
    """Test PackageFinder prefers file links over equivalent page links"""
    req = install_req_from_line('gmpy==1.15', None)
    finder = make_test_finder(
        find_links=[data.find_links],
        index_urls=["http://pypi.org/simple/"],
    )
    all_versions = finder.find_all_candidates(req.name)
    # 1 file InstallationCandidate followed by all https ones
    assert all_versions[0].link.scheme == 'file'
    assert all(version.link.scheme == 'https'
               for version in all_versions[1:]), all_versions

    found = finder.find_requirement(req, False)
    assert found.link.url.startswith("file://")


def test_finder_priority_nonegg_over_eggfragments():
    """Test PackageFinder prefers non-egg links over "#egg=" links"""
    req = install_req_from_line('bar==1.0', None)
    links = ['http://foo/bar.py#egg=bar-1.0', 'http://foo/bar-1.0.tar.gz']

    finder = make_no_network_finder(links)
    all_versions = finder.find_all_candidates(req.name)
    assert all_versions[0].link.url.endswith('tar.gz')
    assert all_versions[1].link.url.endswith('#egg=bar-1.0')

    found = finder.find_requirement(req, False)

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

    links.reverse()

    finder = make_no_network_finder(links)
    all_versions = finder.find_all_candidates(req.name)
    assert all_versions[0].link.url.endswith('tar.gz')
    assert all_versions[1].link.url.endswith('#egg=bar-1.0')
    found = finder.find_requirement(req, False)

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


def test_finder_only_installs_stable_releases(data):
    """
    Test PackageFinder only accepts stable versioned releases by default.
    """

    req = install_req_from_line("bar", None)

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

    # using find-links
    links = ["https://foo/bar-1.0.tar.gz", "https://foo/bar-2.0b1.tar.gz"]

    finder = make_no_network_finder(links)
    found = finder.find_requirement(req, False)
    assert found.link.url == "https://foo/bar-1.0.tar.gz"

    links.reverse()

    finder = make_no_network_finder(links)
    found = finder.find_requirement(req, False)
    assert found.link.url == "https://foo/bar-1.0.tar.gz"


def test_finder_only_installs_data_require(data):
    """
    Test whether the PackageFinder understand data-python-requires

    This can optionally be exposed by a simple-repository to tell which
    distribution are compatible with which version of Python by adding a
    data-python-require to the anchor links.

    See pep 503 for more information.
    """

    # using a local index (that has pre & dev releases)
    finder = make_test_finder(index_urls=[data.index_url("datarequire")])
    links = finder.find_all_candidates("fakepackage")

    expected = ['1.0.0', '9.9.9']
    if (2, 7) < sys.version_info < (3,):
        expected.append('2.7.0')
    elif sys.version_info > (3, 3):
        expected.append('3.3.0')

    assert {str(v.version) for v in links} == set(expected)


def test_finder_installs_pre_releases(data):
    """
    Test PackageFinder finds pre-releases if asked to.
    """

    req = install_req_from_line("bar", None)

    # using a local index (that has pre & dev releases)
    finder = make_test_finder(
        index_urls=[data.index_url("pre")],
        allow_all_prereleases=True,
    )
    found = finder.find_requirement(req, False)
    assert found.link.url.endswith("bar-2.0b1.tar.gz"), found.link.url

    # using find-links
    links = ["https://foo/bar-1.0.tar.gz", "https://foo/bar-2.0b1.tar.gz"]

    finder = make_no_network_finder(links, allow_all_prereleases=True)
    found = finder.find_requirement(req, False)
    assert found.link.url == "https://foo/bar-2.0b1.tar.gz"

    links.reverse()

    finder = make_no_network_finder(links, allow_all_prereleases=True)
    found = finder.find_requirement(req, False)
    assert found.link.url == "https://foo/bar-2.0b1.tar.gz"


def test_finder_installs_dev_releases(data):
    """
    Test PackageFinder finds dev releases if asked to.
    """

    req = install_req_from_line("bar", None)

    # using a local index (that has dev releases)
    finder = make_test_finder(
        index_urls=[data.index_url("dev")],
        allow_all_prereleases=True,
    )
    found = finder.find_requirement(req, False)
    assert found.link.url.endswith("bar-2.0.dev1.tar.gz"), found.link.url


def test_finder_installs_pre_releases_with_version_spec():
    """
    Test PackageFinder only accepts stable versioned releases by default.
    """
    req = install_req_from_line("bar>=0.0.dev0", None)
    links = ["https://foo/bar-1.0.tar.gz", "https://foo/bar-2.0b1.tar.gz"]

    finder = make_no_network_finder(links)
    found = finder.find_requirement(req, False)
    assert found.link.url == "https://foo/bar-2.0b1.tar.gz"

    links.reverse()

    finder = make_no_network_finder(links)
    found = finder.find_requirement(req, False)
    assert found.link.url == "https://foo/bar-2.0b1.tar.gz"


class TestLinkEvaluator:

    def make_test_link_evaluator(self, formats):
        target_python = TargetPython()
        return LinkEvaluator(
            project_name='pytest',
            canonical_name='pytest',
            formats=formats,
            target_python=target_python,
            allow_yanked=True,
        )

    @pytest.mark.parametrize('url, expected_version', [
        ('http:/yo/pytest-1.0.tar.gz', '1.0'),
        ('http:/yo/pytest-1.0-py2.py3-none-any.whl', '1.0'),
    ])
    def test_evaluate_link__match(self, url, expected_version):
        """Test that 'pytest' archives match for 'pytest'"""
        link = Link(url)
        evaluator = self.make_test_link_evaluator(formats=['source', 'binary'])
        actual = evaluator.evaluate_link(link)
        assert actual == (True, expected_version)

    @pytest.mark.parametrize('url, expected_msg', [
        # TODO: Uncomment this test case when #1217 is fixed.
        # 'http:/yo/pytest-xdist-1.0.tar.gz',
        ('http:/yo/pytest2-1.0.tar.gz',
         'Missing project version for pytest'),
        ('http:/yo/pytest_xdist-1.0-py2.py3-none-any.whl',
         'wrong project name (not pytest)'),
    ])
    def test_evaluate_link__substring_fails(self, url, expected_msg):
        """Test that 'pytest<something> archives won't match for 'pytest'."""
        link = Link(url)
        evaluator = self.make_test_link_evaluator(formats=['source', 'binary'])
        actual = evaluator.evaluate_link(link)
        assert actual == (False, expected_msg)


def test_process_project_url(data):
    project_name = 'simple'
    index_url = data.index_url('simple')
    project_url = Link(f'{index_url}/{project_name}')
    finder = make_test_finder(index_urls=[index_url])
    link_evaluator = finder.make_link_evaluator(project_name)
    actual = finder.process_project_url(
        project_url, link_evaluator=link_evaluator,
    )

    assert len(actual) == 1
    package_link = actual[0]
    assert package_link.name == 'simple'
    assert str(package_link.version) == '1.0'


def test_find_all_candidates_nothing():
    """Find nothing without anything"""
    finder = make_test_finder()
    assert not finder.find_all_candidates('pip')


def test_find_all_candidates_find_links(data):
    finder = make_test_finder(find_links=[data.find_links])
    versions = finder.find_all_candidates('simple')
    assert [str(v.version) for v in versions] == ['3.0', '2.0', '1.0']


def test_find_all_candidates_index(data):
    finder = make_test_finder(index_urls=[data.index_url('simple')])
    versions = finder.find_all_candidates('simple')
    assert [str(v.version) for v in versions] == ['1.0']


def test_find_all_candidates_find_links_and_index(data):
    finder = make_test_finder(
        find_links=[data.find_links],
        index_urls=[data.index_url('simple')],
    )
    versions = finder.find_all_candidates('simple')
    # first the find-links versions then the page versions
    assert [str(v.version) for v in versions] == ['3.0', '2.0', '1.0', '1.0']