test_download.py 9.7 KB
Newer Older
1
import hashlib
2
import os
3
from io import BytesIO
4
from shutil import rmtree, copy
5 6
from tempfile import mkdtemp

D
Donald Stufft 已提交
7
from mock import Mock, patch
8 9
import pytest

10
import pip
11
from pip.compat import b, pathname2url
12
from pip.exceptions import HashMismatch
13 14 15 16
from pip.download import (
    PipSession, SafeFileCache, path_to_url, unpack_http_url, url_to_path,
    unpack_file_url,
)
17 18 19
from pip.index import Link


20
def test_unpack_http_url_with_urllib_response_without_content_type(data):
21 22 23
    """
    It should download and unpack files even if no Content-Type header exists
    """
D
Donald Stufft 已提交
24 25 26 27 28
    _real_session = PipSession()

    def _fake_session_get(*args, **kwargs):
        resp = _real_session.get(*args, **kwargs)
        del resp.headers["Content-Type"]
29 30
        return resp

D
Donald Stufft 已提交
31 32 33
    session = Mock()
    session.get = _fake_session_get

34
    uri = path_to_url(data.packages.join("simple-1.0.tar.gz"))
D
Donald Stufft 已提交
35 36 37
    link = Link(uri)
    temp_dir = mkdtemp()
    try:
38 39 40
        unpack_http_url(
            link,
            temp_dir,
D
Donald Stufft 已提交
41 42 43
            download_dir=None,
            session=session,
        )
44 45 46
        assert set(os.listdir(temp_dir)) == set([
            'PKG-INFO', 'setup.cfg', 'setup.py', 'simple', 'simple.egg-info'
        ])
D
Donald Stufft 已提交
47 48
    finally:
        rmtree(temp_dir)
49 50 51


def test_user_agent():
D
Donald Stufft 已提交
52
    PipSession().headers["User-Agent"].startswith("pip/%s" % pip.__version__)
C
Carl Meyer 已提交
53 54


55 56 57 58 59
def _write_file(fn, contents):
    with open(fn, 'w') as fh:
        fh.write(contents)


60
class FakeStream(object):
D
Donald Stufft 已提交
61

62 63 64
    def __init__(self, contents):
        self._io = BytesIO(contents)

65 66 67 68
    def read(self, size, decode_content=None):
        return self._io.read(size)

    def stream(self, size, decode_content=None):
D
Donald Stufft 已提交
69 70
        yield self._io.read(size)

71 72 73 74 75 76

class MockResponse(object):

    def __init__(self, contents):
        self.raw = FakeStream(contents)

D
Donald Stufft 已提交
77 78
    def raise_for_status(self):
        pass
79 80 81


@patch('pip.download.unpack_file')
D
Donald Stufft 已提交
82
def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file):
C
Carl Meyer 已提交
83 84 85
    """
    If already-downloaded file has bad checksum, re-download.
    """
86 87 88 89
    base_url = 'http://www.example.com/somepackage.tgz'
    contents = b('downloaded')
    download_hash = hashlib.new('sha1', contents)
    link = Link(base_url + '#sha1=' + download_hash.hexdigest())
D
Donald Stufft 已提交
90 91 92 93 94 95

    session = Mock()
    session.get = Mock()
    response = session.get.return_value = MockResponse(contents)
    response.headers = {'content-type': 'application/x-tar'}
    response.url = base_url
96 97 98 99 100 101

    download_dir = mkdtemp()
    try:
        downloaded_file = os.path.join(download_dir, 'somepackage.tgz')
        _write_file(downloaded_file, 'some contents')

102 103 104
        unpack_http_url(
            link,
            'location',
D
Donald Stufft 已提交
105 106 107
            download_dir=download_dir,
            session=session,
        )
108 109

        # despite existence of downloaded file with bad hash, downloaded again
D
Donald Stufft 已提交
110 111
        session.get.assert_called_once_with(
            'http://www.example.com/somepackage.tgz',
112
            headers={"Accept-Encoding": "identity"},
D
Donald Stufft 已提交
113 114
            stream=True,
        )
115 116 117 118 119 120
        # cached file is replaced with newly downloaded file
        with open(downloaded_file) as fh:
            assert fh.read() == 'downloaded'

    finally:
        rmtree(download_dir)
121 122 123 124 125 126


@pytest.mark.skipif("sys.platform == 'win32'")
def test_path_to_url_unix():
    assert path_to_url('/tmp/file') == 'file:///tmp/file'
    path = os.path.join(os.getcwd(), 'file')
M
Marcus Smith 已提交
127
    assert path_to_url('file') == 'file://' + pathname2url(path)
128 129 130 131 132 133 134 135 136 137 138 139


@pytest.mark.skipif("sys.platform == 'win32'")
def test_url_to_path_unix():
    assert url_to_path('file:///tmp/file') == '/tmp/file'


@pytest.mark.skipif("sys.platform != 'win32'")
def test_path_to_url_win():
    assert path_to_url('c:/tmp/file') == 'file:///c:/tmp/file'
    assert path_to_url('c:\\tmp\\file') == 'file:///c:/tmp/file'
    path = os.path.join(os.getcwd(), 'file')
M
Marcus Smith 已提交
140
    assert path_to_url('file') == 'file:' + pathname2url(path)
141 142 143 144 145


@pytest.mark.skipif("sys.platform != 'win32'")
def test_url_to_path_win():
    assert url_to_path('file:///c:/tmp/file') == 'c:/tmp/file'
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


class Test_unpack_file_url(object):

    def prep(self, tmpdir, data):
        self.build_dir = tmpdir.join('build')
        self.download_dir = tmpdir.join('download')
        os.mkdir(self.build_dir)
        os.mkdir(self.download_dir)
        self.dist_file = "simple-1.0.tar.gz"
        self.dist_file2 = "simple-2.0.tar.gz"
        self.dist_path = data.packages.join(self.dist_file)
        self.dist_path2 = data.packages.join(self.dist_file2)
        self.dist_url = Link(path_to_url(self.dist_path))
        self.dist_url2 = Link(path_to_url(self.dist_path2))

    def test_unpack_file_url_no_download(self, tmpdir, data):
        self.prep(tmpdir, data)
        unpack_file_url(self.dist_url, self.build_dir)
        assert os.path.isdir(os.path.join(self.build_dir, 'simple'))
        assert not os.path.isfile(
            os.path.join(self.download_dir, self.dist_file))

    def test_unpack_file_url_and_download(self, tmpdir, data):
        self.prep(tmpdir, data)
        unpack_file_url(self.dist_url, self.build_dir,
                        download_dir=self.download_dir)
        assert os.path.isdir(os.path.join(self.build_dir, 'simple'))
        assert os.path.isfile(os.path.join(self.download_dir, self.dist_file))

    def test_unpack_file_url_download_already_exists(self, tmpdir,
                                                     data, monkeypatch):
        self.prep(tmpdir, data)
        # add in previous download (copy simple-2.0 as simple-1.0)
        # so we can tell it didn't get overwritten
        dest_file = os.path.join(self.download_dir, self.dist_file)
        copy(self.dist_path2, dest_file)
        dist_path2_md5 = hashlib.md5(
            open(self.dist_path2, 'rb').read()).hexdigest()

        unpack_file_url(self.dist_url, self.build_dir,
                        download_dir=self.download_dir)
        # our hash should be the same, i.e. not overwritten by simple-1.0 hash
        assert dist_path2_md5 == hashlib.md5(
            open(dest_file, 'rb').read()).hexdigest()

192 193 194 195 196 197 198 199 200 201
    def test_unpack_file_url_bad_hash(self, tmpdir, data,
                                      monkeypatch):
        """
        Test when the file url hash fragment is wrong
        """
        self.prep(tmpdir, data)
        self.dist_url.url = "%s#md5=bogus" % self.dist_url.url
        with pytest.raises(HashMismatch):
            unpack_file_url(self.dist_url, self.build_dir)

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    def test_unpack_file_url_download_bad_hash(self, tmpdir, data,
                                               monkeypatch):
        """
        Test when existing download has different hash from the file url
        fragment
        """
        self.prep(tmpdir, data)

        # add in previous download (copy simple-2.0 as simple-1.0 so it's wrong
        # hash)
        dest_file = os.path.join(self.download_dir, self.dist_file)
        copy(self.dist_path2, dest_file)

        dist_path_md5 = hashlib.md5(
            open(self.dist_path, 'rb').read()).hexdigest()
        dist_path2_md5 = hashlib.md5(open(dest_file, 'rb').read()).hexdigest()

        assert dist_path_md5 != dist_path2_md5

        self.dist_url.url = "%s#md5=%s" % (
            self.dist_url.url,
            dist_path_md5
D
Donald Stufft 已提交
224
        )
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        unpack_file_url(self.dist_url, self.build_dir,
                        download_dir=self.download_dir)

        # confirm hash is for simple1-1.0
        # the previous bad download has been removed
        assert (hashlib.md5(open(dest_file, 'rb').read()).hexdigest()
                ==
                dist_path_md5
                ), hashlib.md5(open(dest_file, 'rb').read()).hexdigest()

    def test_unpack_file_url_thats_a_dir(self, tmpdir, data):
        self.prep(tmpdir, data)
        dist_path = data.packages.join("FSPkg")
        dist_url = Link(path_to_url(dist_path))
        unpack_file_url(dist_url, self.build_dir,
                        download_dir=self.download_dir)
        assert os.path.isdir(os.path.join(self.build_dir, 'fspkg'))
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


class TestSafeFileCache:

    def test_cache_roundtrip(self, tmpdir):
        cache_dir = tmpdir.join("test-cache")
        cache_dir.makedirs()

        cache = SafeFileCache(cache_dir)
        assert cache.get("test key") is None
        cache.set("test key", b"a test string")
        assert cache.get("test key") == b"a test string"
        cache.delete("test key")
        assert cache.get("test key") is None

    def test_safe_get_no_perms(self, tmpdir, monkeypatch):
        cache_dir = tmpdir.join("unreadable-cache")
        cache_dir.makedirs()
        os.chmod(cache_dir, 000)

        monkeypatch.setattr(os.path, "exists", lambda x: True)

        cache = SafeFileCache(cache_dir)
        cache.get("foo")

    def test_safe_set_no_perms(self, tmpdir):
        cache_dir = tmpdir.join("unreadable-cache")
        cache_dir.makedirs()
        os.chmod(cache_dir, 000)

        cache = SafeFileCache(cache_dir)
        cache.set("foo", "bar")

    def test_safe_delete_no_perms(self, tmpdir):
        cache_dir = tmpdir.join("unreadable-cache")
        cache_dir.makedirs()
        os.chmod(cache_dir, 000)

        cache = SafeFileCache(cache_dir)
        cache.delete("foo")


class TestPipSession:

    def test_cache_defaults_off(self):
        session = PipSession()

        assert not hasattr(session.adapters["http://"], "cache")
        assert not hasattr(session.adapters["https://"], "cache")

    def test_cache_is_enabled(self, tmpdir):
        session = PipSession(cache=tmpdir.join("test-cache"))

        assert hasattr(session.adapters["http://"], "cache")
        assert hasattr(session.adapters["https://"], "cache")

        assert (session.adapters["http://"].cache.directory
                == tmpdir.join("test-cache"))
        assert (session.adapters["https://"].cache.directory
                == tmpdir.join("test-cache"))