Debian Codegraph @

tests/test_url.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import io
2 import tempfile
3 from contextlib import closing, contextmanager
4 from pathlib import Path
5 from unittest.mock import MagicMock, patch
6 from zipfile import ZipFile
7
8 import pytest
9 from requests import HTTPError, Session
10
11 from conda_package_streaming import lazy_wheel
12 from conda_package_streaming.lazy_wheel import LazyConda
13 from conda_package_streaming.url import (
14 conda_reader_for_url,
15 extract_conda_info,
16 stream_conda_info,
17 )
18
19 LIMIT = 16
20
21
22 @pytest.fixture
23 def package_url(package_server):
24 """
25 Base url for all test packages.
26 """
27 host, port = package_server.server.server_address
28 return f"http://{host}:{port}/pkgs"
29
30
31 @pytest.fixture
32 def package_urls(package_server, package_url):
33 pkgs_dir = Path(package_server.app.pkgs_dir)
34 conda = []
35 tar_bz2 = []
36
37 for path in pkgs_dir.iterdir():
38 if len(conda) > LIMIT and len(tar_bz2) > LIMIT:
39 break
40 url = f"{package_url}/{path.name}"
41 if path.name.endswith(".tar.bz2") and len(tar_bz2) < LIMIT:
42 tar_bz2.append(url)
43 elif path.name.endswith(".conda") and len(conda) < LIMIT:
44 conda.append(url)
45 # interleave
46 urls = []
47 for pair in zip(conda, tar_bz2):
48 urls.extend(pair)
49 return urls
50
51
52 def test_stream_url(package_urls):
53 with pytest.raises(ValueError):
54 next(stream_conda_info("https://localhost/notaconda.rar"))
55
56 for url in package_urls:
57 with closing(stream_conda_info(url)) as members:
58 print("stream_url", url)
59 for tar, member in members:
60 if member.name == "info/index.json":
61 break
62 else:
63 pytest.fail("info/index.json not found")
64
65
66 def test_fetch_meta(package_urls):
67 for url in package_urls:
68 with tempfile.TemporaryDirectory() as destdir:
69 extract_conda_info(url, destdir)
70
71
72 def test_lazy_wheel(package_urls):
73 lazy_tests = 7
74 for url in package_urls:
75 if url.endswith(".conda"):
76 # API works with `.tar.bz2` but only returns LazyConda for `.conda`
77 filename, conda = conda_reader_for_url(url)
78 assert filename == url.rsplit("/")[-1]
79 with conda:
80 assert isinstance(conda, LazyConda)
81 assert conda.mode == "rb"
82 assert conda.readable()
83 assert not conda.writable()
84 assert not conda.closed
85
86 request_count = conda._request_count
87
88 # did we really prefetch the info?
89 zf = ZipFile(conda) # type: ignore
90 filename = filename[: -len(".conda")]
91 zf.open(f"info-{filename}.tar.zst").read()
92
93 assert conda._request_count == request_count, (
94 "info required extra GET request"
95 )
96 assert conda._request_count <= 3
97
98 conda.prefetch("not-appearing-in-archive.txt")
99
100 # zip will figure this out naturally; delete method?
101 conda._check_zip()
102
103 lazy_tests -= 1
104 if lazy_tests <= 0:
105 break
106 else:
107 raise LookupError(
108 f"not enough .conda packages found {lazy_tests} {package_urls}"
109 )
110
111 with pytest.raises(HTTPError):
112 conda_reader_for_url(package_urls[0] + ".404.conda")
113
114 class Session200(Session):
115 def get(self, *args, **kwargs):
116 response = super().get(*args, **kwargs)
117 response.status_code = 200
118 return response
119
120 with pytest.raises(lazy_wheel.HTTPRangeRequestUnsupported):
121 LazyConda(package_urls[0], Session200())
122
123 for url in package_urls:
124 if url.endswith(".tar.bz2"):
125 LazyConda(url, Session())._check_zip()
126 break
127 else:
128 raise LookupError("no .tar.bz2 packages found")
129
130
131 @pytest.mark.parametrize("fall_back_to_full_download", [True, False])
132 @patch("conda_package_streaming.url.LazyConda")
133 def test_conda_reader_for_url_passes_to_lazy_conda_correctly(
134 lazy_conda_mock: MagicMock, fall_back_to_full_download: bool
135 ):
136 url = "https://example.com/package.conda"
137 session = Session()
138
139 filename, conda = conda_reader_for_url(
140 url, session, fall_back_to_full_download=fall_back_to_full_download
141 )
142
143 assert filename == "package.conda"
144 lazy_conda_mock.assert_called_once_with(
145 url,
146 session,
147 fall_back_to_full_download=fall_back_to_full_download,
148 )
149
150
151 def test_no_file_after_info():
152 """
153 If info is the last file, LazyConda must fetch (start of info file .. start
154 of zip directory) instead of to the next file in the zip.
155 """
156
157 class MockBytesIO(io.BytesIO):
158 prefetch = LazyConda.prefetch
159
160 @contextmanager
161 def _stay(self):
162 yield
163
164 zip = MockBytesIO()
165 zf = ZipFile(zip, "w")
166 zf.writestr("info-test.tar.zst", b"00000000") # a short file
167 zf.close()
168
169 zip.prefetch("test")
170
171
172 @pytest.mark.skip()
173 def test_obsolete_lazy_wheel_selftest():
174 import logging
175
176 import requests
177
178 logging.basicConfig(level=logging.DEBUG)
179
180 session = requests.Session()
181
182 lzoh = lazy_wheel.LazyZipOverHTTP(
183 "https://repodata.fly.dev/repo.anaconda.com/pkgs/main/win-32/current_repodata.jlap",
184 session,
185 )
186
187 lzoh.seek(1024)
188 lzoh.read(768)
189 lzoh.seek(0)
190
191 # compare against regular fetch
192 with open("outfile.txt", "wb+") as out:
193 buf = b" "
194 while buf:
195 buf = lzoh.read(1024 * 10)
196 print(list(zip(lzoh._left, lzoh._right)), lzoh._length)
197 if not buf:
198 break
199 out.write(buf)