test_utils.py 17.0 KB
Newer Older
1 2 3 4 5
"""
util tests

"""
import os
6
import stat
7
import sys
8
import time
9 10
import shutil
import tempfile
11

12 13
import pytest

14
from mock import Mock, patch
15
from pip.exceptions import HashMismatch, HashMissing, InstallationError
16
from pip.utils import (egg_link_path, get_installed_distributions,
T
Thomas Kluyver 已提交
17
                       untar_file, unzip_file, rmtree, normalize_path)
18
from pip.utils.hashes import Hashes, MissingHashes
19
from pip.operations.freeze import freeze_excludes
20
from pip._vendor.six import BytesIO
21 22 23 24 25 26 27 28 29 30 31 32


class Tests_EgglinkPath:
    "util.egg_link_path() tests"

    def setup(self):

        project = 'foo'

        self.mock_dist = Mock(project_name=project)
        self.site_packages = 'SITE_PACKAGES'
        self.user_site = 'USER_SITE'
33 34 35 36 37 38 39 40
        self.user_site_egglink = os.path.join(
            self.user_site,
            '%s.egg-link' % project
        )
        self.site_packages_egglink = os.path.join(
            self.site_packages,
            '%s.egg-link' % project,
        )
41

42
        # patches
43 44 45 46 47
        from pip import utils
        self.old_site_packages = utils.site_packages
        self.mock_site_packages = utils.site_packages = 'SITE_PACKAGES'
        self.old_running_under_virtualenv = utils.running_under_virtualenv
        self.mock_running_under_virtualenv = utils.running_under_virtualenv = \
48
            Mock()
49 50 51 52
        self.old_virtualenv_no_global = utils.virtualenv_no_global
        self.mock_virtualenv_no_global = utils.virtualenv_no_global = Mock()
        self.old_user_site = utils.user_site
        self.mock_user_site = utils.user_site = self.user_site
53
        from os import path
54
        self.old_isfile = path.isfile
55 56
        self.mock_isfile = path.isfile = Mock()

57
    def teardown(self):
58 59 60 61 62
        from pip import utils
        utils.site_packages = self.old_site_packages
        utils.running_under_virtualenv = self.old_running_under_virtualenv
        utils.virtualenv_no_global = self.old_virtualenv_no_global
        utils.user_site = self.old_user_site
63 64 65
        from os import path
        path.isfile = self.old_isfile

66 67
    def eggLinkInUserSite(self, egglink):
        return egglink == self.user_site_egglink
68

69 70
    def eggLinkInSitePackages(self, egglink):
        return egglink == self.site_packages_egglink
71

72 73 74
    # ####################### #
    # # egglink in usersite # #
    # ####################### #
75 76 77 78
    def test_egglink_in_usersite_notvenv(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = False
        self.mock_isfile.side_effect = self.eggLinkInUserSite
79
        assert egg_link_path(self.mock_dist) == self.user_site_egglink
80 81 82 83 84

    def test_egglink_in_usersite_venv_noglobal(self):
        self.mock_virtualenv_no_global.return_value = True
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.side_effect = self.eggLinkInUserSite
85
        assert egg_link_path(self.mock_dist) is None
86 87 88 89 90

    def test_egglink_in_usersite_venv_global(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.side_effect = self.eggLinkInUserSite
91
        assert egg_link_path(self.mock_dist) == self.user_site_egglink
92

93 94 95
    # ####################### #
    # # egglink in sitepkgs # #
    # ####################### #
96 97 98 99
    def test_egglink_in_sitepkgs_notvenv(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = False
        self.mock_isfile.side_effect = self.eggLinkInSitePackages
100
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
101 102 103 104 105

    def test_egglink_in_sitepkgs_venv_noglobal(self):
        self.mock_virtualenv_no_global.return_value = True
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.side_effect = self.eggLinkInSitePackages
106
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
107 108 109 110 111

    def test_egglink_in_sitepkgs_venv_global(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.side_effect = self.eggLinkInSitePackages
112
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
113

114 115 116
    # ################################## #
    # # egglink in usersite & sitepkgs # #
    # ################################## #
117 118 119 120
    def test_egglink_in_both_notvenv(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = False
        self.mock_isfile.return_value = True
121
        assert egg_link_path(self.mock_dist) == self.user_site_egglink
122 123 124 125 126

    def test_egglink_in_both_venv_noglobal(self):
        self.mock_virtualenv_no_global.return_value = True
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.return_value = True
127
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
128 129 130 131 132

    def test_egglink_in_both_venv_global(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.return_value = True
133
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
134

135 136 137
    # ############## #
    # # no egglink # #
    # ############## #
138 139 140 141
    def test_noegglink_in_sitepkgs_notvenv(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = False
        self.mock_isfile.return_value = False
142
        assert egg_link_path(self.mock_dist) is None
143 144 145 146 147

    def test_noegglink_in_sitepkgs_venv_noglobal(self):
        self.mock_virtualenv_no_global.return_value = True
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.return_value = False
148
        assert egg_link_path(self.mock_dist) is None
149 150 151 152 153

    def test_noegglink_in_sitepkgs_venv_global(self):
        self.mock_virtualenv_no_global.return_value = False
        self.mock_running_under_virtualenv.return_value = True
        self.mock_isfile.return_value = False
154
        assert egg_link_path(self.mock_dist) is None
155

156

157
@patch('pip.utils.dist_in_usersite')
158 159
@patch('pip.utils.dist_is_local')
@patch('pip.utils.dist_is_editable')
160 161 162 163
class Tests_get_installed_distributions:
    """test util.get_installed_distributions"""

    workingset = [
164 165
        Mock(test_name="global"),
        Mock(test_name="editable"),
166
        Mock(test_name="normal"),
167
        Mock(test_name="user"),
168 169 170 171 172 173 174 175 176 177 178
    ]

    workingset_stdlib = [
        Mock(test_name='normal', key='argparse'),
        Mock(test_name='normal', key='wsgiref')
    ]

    workingset_freeze = [
        Mock(test_name='normal', key='pip'),
        Mock(test_name='normal', key='setuptools'),
        Mock(test_name='normal', key='distribute')
179
    ]
180 181 182 183 184

    def dist_is_editable(self, dist):
        return dist.test_name == "editable"

    def dist_is_local(self, dist):
185 186 187 188
        return dist.test_name != "global" and dist.test_name != 'user'

    def dist_in_usersite(self, dist):
        return dist.test_name == "user"
189

190
    @patch('pip._vendor.pkg_resources.working_set', workingset)
191 192 193
    def test_editables_only(self, mock_dist_is_editable,
                            mock_dist_is_local,
                            mock_dist_in_usersite):
194 195
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
196
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
197 198 199 200
        dists = get_installed_distributions(editables_only=True)
        assert len(dists) == 1, dists
        assert dists[0].test_name == "editable"

201
    @patch('pip._vendor.pkg_resources.working_set', workingset)
202 203 204
    def test_exclude_editables(self, mock_dist_is_editable,
                               mock_dist_is_local,
                               mock_dist_in_usersite):
205 206
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
207
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
208 209 210 211
        dists = get_installed_distributions(include_editables=False)
        assert len(dists) == 1
        assert dists[0].test_name == "normal"

212
    @patch('pip._vendor.pkg_resources.working_set', workingset)
213 214 215
    def test_include_globals(self, mock_dist_is_editable,
                             mock_dist_is_local,
                             mock_dist_in_usersite):
216 217
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
218
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
219
        dists = get_installed_distributions(local_only=False)
220 221 222 223 224 225 226 227 228 229 230 231 232
        assert len(dists) == 4

    @patch('pip._vendor.pkg_resources.working_set', workingset)
    def test_user_only(self, mock_dist_is_editable,
                       mock_dist_is_local,
                       mock_dist_in_usersite):
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
        dists = get_installed_distributions(local_only=False,
                                            user_only=True)
        assert len(dists) == 1
        assert dists[0].test_name == "user"
233

234 235
    @pytest.mark.skipif("sys.version_info >= (2,7)")
    @patch('pip._vendor.pkg_resources.working_set', workingset_stdlib)
236 237 238
    def test_py26_excludes(self, mock_dist_is_editable,
                           mock_dist_is_local,
                           mock_dist_in_usersite):
239 240
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
241
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
242 243 244 245 246 247 248
        dists = get_installed_distributions()
        assert len(dists) == 1
        assert dists[0].key == 'argparse'

    @pytest.mark.skipif("sys.version_info < (2,7)")
    @patch('pip._vendor.pkg_resources.working_set', workingset_stdlib)
    def test_gte_py27_excludes(self, mock_dist_is_editable,
249 250
                               mock_dist_is_local,
                               mock_dist_in_usersite):
251 252
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
253
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
254 255 256 257
        dists = get_installed_distributions()
        assert len(dists) == 0

    @patch('pip._vendor.pkg_resources.working_set', workingset_freeze)
258 259 260
    def test_freeze_excludes(self, mock_dist_is_editable,
                             mock_dist_is_local,
                             mock_dist_in_usersite):
261 262
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
263
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
264 265 266
        dists = get_installed_distributions(skip=freeze_excludes)
        assert len(dists) == 0

267

268 269
class TestUnpackArchives(object):
    """
270 271
    test_tar.tgz/test_tar.zip have content as follows engineered to confirm 3
    things:
272 273 274 275 276 277 278 279 280 281 282
     1) confirm that reg files, dirs, and symlinks get unpacked
     2) permissions are not preserved (and go by the 022 umask)
     3) reg files with *any* execute perms, get chmod +x

       file.txt         600 regular file
       symlink.txt      777 symlink to file.txt
       script_owner.sh  700 script where owner can execute
       script_group.sh  610 script where group can execute
       script_world.sh  601 script where world can execute
       dir              744 directory
       dir/dirfile      622 regular file
283

284
    """
285

286 287 288 289
    def setup(self):
        self.tempdir = tempfile.mkdtemp()
        self.old_mask = os.umask(0o022)
        self.symlink_expected_mode = None
290

291 292 293 294 295 296 297 298
    def teardown(self):
        os.umask(self.old_mask)
        shutil.rmtree(self.tempdir, ignore_errors=True)

    def mode(self, path):
        return stat.S_IMODE(os.stat(path).st_mode)

    def confirm_files(self):
299 300
        # expections based on 022 umask set above and the unpack logic that
        # sets execute permissions, not preservation
301
        for fname, expected_mode, test in [
302 303 304 305 306 307
                ('file.txt', 0o644, os.path.isfile),
                ('symlink.txt', 0o644, os.path.isfile),
                ('script_owner.sh', 0o755, os.path.isfile),
                ('script_group.sh', 0o755, os.path.isfile),
                ('script_world.sh', 0o755, os.path.isfile),
                ('dir', 0o755, os.path.isdir),
D
Donald Stufft 已提交
308
                (os.path.join('dir', 'dirfile'), 0o644, os.path.isfile)]:
309 310 311 312 313 314 315 316 317 318
            path = os.path.join(self.tempdir, fname)
            if path.endswith('symlink.txt') and sys.platform == 'win32':
                # no symlinks created on windows
                continue
            assert test(path), path
            if sys.platform == 'win32':
                # the permissions tests below don't apply in windows
                # due to os.chmod being a noop
                continue
            mode = self.mode(path)
319 320 321
            assert mode == expected_mode, (
                "mode: %s, expected mode: %s" % (mode, expected_mode)
            )
322

323
    def test_unpack_tgz(self, data):
324 325 326
        """
        Test unpacking a *.tgz, and setting execute permissions
        """
327
        test_file = data.packages.join("test_tar.tgz")
328 329 330
        untar_file(test_file, self.tempdir)
        self.confirm_files()

331
    def test_unpack_zip(self, data):
332 333 334
        """
        Test unpacking a *.zip, and setting execute permissions
        """
335
        test_file = data.packages.join("test_zip.zip")
336 337
        unzip_file(test_file, self.tempdir)
        self.confirm_files()
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


class Failer:
    def __init__(self, duration=1):
        self.succeed_after = time.time() + duration

    def call(self, *args, **kw):
        """Fail with OSError self.max_fails times"""
        if time.time() < self.succeed_after:
            raise OSError("Failed")


def test_rmtree_retries(tmpdir, monkeypatch):
    """
    Test pip.utils.rmtree will retry failures
    """
    monkeypatch.setattr(shutil, 'rmtree', Failer(duration=1).call)
    rmtree('foo')


def test_rmtree_retries_for_3sec(tmpdir, monkeypatch):
    """
    Test pip.utils.rmtree will retry failures for no more than 3 sec
    """
    monkeypatch.setattr(shutil, 'rmtree', Failer(duration=5).call)
    with pytest.raises(OSError):
        rmtree('foo')
T
Thomas Kluyver 已提交
365

T
Thomas Kluyver 已提交
366

T
Thomas Kluyver 已提交
367 368 369 370 371
class Test_normalize_path(object):
    # Technically, symlinks are possible on Windows, but you need a special
    # permission bit to create them, and Python 2 doesn't support it anyway, so
    # it's easiest just to skip this test on Windows altogether.
    @pytest.mark.skipif("sys.platform == 'win32'")
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
    def test_resolve_symlinks(self, tmpdir):
        print(type(tmpdir))
        print(dir(tmpdir))
        orig_working_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            d = os.path.join('foo', 'bar')
            f = os.path.join(d, 'file1')
            os.makedirs(d)
            with open(f, 'w'):  # Create the file
                pass

            os.symlink(d, 'dir_link')
            os.symlink(f, 'file_link')

            assert normalize_path(
                'dir_link/file1', resolve_symlinks=True
            ) == os.path.join(tmpdir, f)
            assert normalize_path(
                'dir_link/file1', resolve_symlinks=False
            ) == os.path.join(tmpdir, 'dir_link', 'file1')

            assert normalize_path(
                'file_link', resolve_symlinks=True
            ) == os.path.join(tmpdir, f)
            assert normalize_path(
                'file_link', resolve_symlinks=False
            ) == os.path.join(tmpdir, 'file_link')
        finally:
            os.chdir(orig_working_dir)
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425


class TestHashes(object):
    """Tests for pip.utils.hashes"""

    def test_success(self, tmpdir):
        """Make sure no error is raised when at least one hash matches.

        Test check_against_path because it calls everything else.

        """
        file = tmpdir / 'to_hash'
        file.write('hello')
        hashes = Hashes({
            'sha256': ['2cf24dba5fb0a30e26e83b2ac5b9e29e'
                       '1b161e5c1fa7425e73043362938b9824'],
            'sha224': ['wrongwrong'],
            'md5': ['5d41402abc4b2a76b9719d911017c592']})
        hashes.check_against_path(file)

    def test_failure(self):
        """Hashes should raise HashMismatch when no hashes match."""
        hashes = Hashes({'sha256': ['wrongwrong']})
        with pytest.raises(HashMismatch):
426
            hashes.check_against_file(BytesIO(b'hello'))
427 428 429 430

    def test_missing_hashes(self):
        """MissingHashes should raise HashMissing when any check is done."""
        with pytest.raises(HashMissing):
431
            MissingHashes().check_against_file(BytesIO(b'hello'))
432 433 434 435 436 437

    def test_unknown_hash(self):
        """Hashes should raise InstallationError when it encounters an unknown
        hash."""
        hashes = Hashes({'badbad': ['dummy']})
        with pytest.raises(InstallationError):
438
            hashes.check_against_file(BytesIO(b'hello'))
439 440 441 442 443 444 445

    def test_non_zero(self):
        """Test that truthiness tests tell whether any known-good hashes
        exist."""
        assert Hashes({'sha256': 'dummy'})
        assert not Hashes()
        assert not Hashes({})