test_utils.py 17.8 KB
Newer Older
1 2
# -*- coding: utf-8 -*-

3 4 5 6 7
"""
util tests

"""
import os
8
import stat
9
import sys
10
import time
11 12
import shutil
import tempfile
13

14 15
import pytest

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


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'
35 36 37 38 39 40 41 42
        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,
        )
43

44
        # patches
45 46 47 48 49
        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 = \
50
            Mock()
51 52 53 54
        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
55
        from os import path
56
        self.old_isfile = path.isfile
57 58
        self.mock_isfile = path.isfile = Mock()

59
    def teardown(self):
60 61 62 63 64
        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
65 66 67
        from os import path
        path.isfile = self.old_isfile

68 69
    def eggLinkInUserSite(self, egglink):
        return egglink == self.user_site_egglink
70

71 72
    def eggLinkInSitePackages(self, egglink):
        return egglink == self.site_packages_egglink
73

74 75 76
    # ####################### #
    # # egglink in usersite # #
    # ####################### #
77 78 79 80
    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
81
        assert egg_link_path(self.mock_dist) == self.user_site_egglink
82 83 84 85 86

    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
87
        assert egg_link_path(self.mock_dist) is None
88 89 90 91 92

    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
93
        assert egg_link_path(self.mock_dist) == self.user_site_egglink
94

95 96 97
    # ####################### #
    # # egglink in sitepkgs # #
    # ####################### #
98 99 100 101
    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
102
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
103 104 105 106 107

    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
108
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
109 110 111 112 113

    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
114
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
115

116 117 118
    # ################################## #
    # # egglink in usersite & sitepkgs # #
    # ################################## #
119 120 121 122
    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
123
        assert egg_link_path(self.mock_dist) == self.user_site_egglink
124 125 126 127 128

    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
129
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
130 131 132 133 134

    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
135
        assert egg_link_path(self.mock_dist) == self.site_packages_egglink
136

137 138 139
    # ############## #
    # # no egglink # #
    # ############## #
140 141 142 143
    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
144
        assert egg_link_path(self.mock_dist) is None
145 146 147 148 149

    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
150
        assert egg_link_path(self.mock_dist) is None
151 152 153 154 155

    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
156
        assert egg_link_path(self.mock_dist) is None
157

158

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

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

    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')
181
    ]
182 183 184 185 186

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

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

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

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

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

214
    @patch('pip._vendor.pkg_resources.working_set', workingset)
215 216 217
    def test_include_globals(self, mock_dist_is_editable,
                             mock_dist_is_local,
                             mock_dist_in_usersite):
218 219
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
220
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
221
        dists = get_installed_distributions(local_only=False)
222 223 224 225 226 227 228 229 230 231 232 233 234
        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"
235

236 237
    @pytest.mark.skipif("sys.version_info >= (2,7)")
    @patch('pip._vendor.pkg_resources.working_set', workingset_stdlib)
238 239 240
    def test_py26_excludes(self, mock_dist_is_editable,
                           mock_dist_is_local,
                           mock_dist_in_usersite):
241 242
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
243
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
244 245 246 247 248 249 250
        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,
251 252
                               mock_dist_is_local,
                               mock_dist_in_usersite):
253 254
        mock_dist_is_editable.side_effect = self.dist_is_editable
        mock_dist_is_local.side_effect = self.dist_is_local
255
        mock_dist_in_usersite.side_effect = self.dist_in_usersite
256 257 258 259
        dists = get_installed_distributions()
        assert len(dists) == 0

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

270

271 272
class TestUnpackArchives(object):
    """
273 274
    test_tar.tgz/test_tar.zip have content as follows engineered to confirm 3
    things:
275 276 277 278 279 280 281 282 283 284 285
     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
286

287
    """
288

289 290 291 292
    def setup(self):
        self.tempdir = tempfile.mkdtemp()
        self.old_mask = os.umask(0o022)
        self.symlink_expected_mode = None
293

294 295 296 297 298 299 300 301
    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):
302 303
        # expections based on 022 umask set above and the unpack logic that
        # sets execute permissions, not preservation
304
        for fname, expected_mode, test in [
305 306 307 308 309 310
                ('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 已提交
311
                (os.path.join('dir', 'dirfile'), 0o644, os.path.isfile)]:
312 313 314 315 316 317 318 319 320 321
            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)
322 323 324
            assert mode == expected_mode, (
                "mode: %s, expected mode: %s" % (mode, expected_mode)
            )
325

326
    def test_unpack_tgz(self, data):
327 328 329
        """
        Test unpacking a *.tgz, and setting execute permissions
        """
330
        test_file = data.packages.join("test_tar.tgz")
331 332
        untar_file(test_file, self.tempdir)
        self.confirm_files()
333 334 335 336
        # Check the timestamp of an extracted file
        file_txt_path = os.path.join(self.tempdir, 'file.txt')
        mtime = time.gmtime(os.stat(file_txt_path).st_mtime)
        assert mtime[0:6] == (2013, 8, 16, 5, 13, 37), mtime
337

338
    def test_unpack_zip(self, data):
339 340 341
        """
        Test unpacking a *.zip, and setting execute permissions
        """
342
        test_file = data.packages.join("test_zip.zip")
343 344
        unzip_file(test_file, self.tempdir)
        self.confirm_files()
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


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 已提交
372

T
Thomas Kluyver 已提交
373

T
Thomas Kluyver 已提交
374 375 376 377 378
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'")
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
    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)
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432


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):
433
            hashes.check_against_file(BytesIO(b'hello'))
434 435 436 437

    def test_missing_hashes(self):
        """MissingHashes should raise HashMissing when any check is done."""
        with pytest.raises(HashMissing):
438
            MissingHashes().check_against_file(BytesIO(b'hello'))
439 440 441 442 443 444

    def test_unknown_hash(self):
        """Hashes should raise InstallationError when it encounters an unknown
        hash."""
        hashes = Hashes({'badbad': ['dummy']})
        with pytest.raises(InstallationError):
445
            hashes.check_against_file(BytesIO(b'hello'))
446 447 448 449 450 451 452

    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({})
453 454 455 456 457 458 459 460 461 462 463 464


class TestEncoding(object):
    """Tests for pip.utils.encoding"""

    def test_auto_decode_utf16_le(self):
        data = (
            b'\xff\xfeD\x00j\x00a\x00n\x00g\x00o\x00=\x00'
            b'=\x001\x00.\x004\x00.\x002\x00'
        )
        assert auto_decode(data) == "Django==1.4.2"

X
Xavier Fernandez 已提交
465 466
    def test_auto_decode_no_bom(self):
        assert auto_decode(b'foobar') == u'foobar'
467 468 469 470

    def test_auto_decode_pep263_headers(self):
        latin1_req = u'# coding=latin1\n# Pas trop de café'
        assert auto_decode(latin1_req.encode('latin1')) == latin1_req