Debian Codegraph @

tests/test_transmute.py

raw ◀ ▶
1 Debian patch touch this file
1 import contextlib
2 import io
3 import itertools
4 import os
5 import tarfile
6 import time
7 from pathlib import Path
8 from zipfile import ZipFile
9
10 import pytest
11 from conda_package_handling.validate import validate_converted_files_match_streaming
12
13 try:
14 import compression.zstd as zstd
15 except ImportError:
16 import backports.zstd as zstd
17
18 from conda_package_streaming.create import anonymize
19 from conda_package_streaming.package_streaming import (
20 CondaComponent,
21 stream_conda_component,
22 )
23 from conda_package_streaming.transmute import (
24 transmute,
25 transmute_stream,
26 transmute_tar_bz2,
27 )
28
29
30 @pytest.fixture
31 def testtar_bytes():
32 buffer = io.BytesIO()
33 with tarfile.open("test.tar.bz2", "w:bz2", fileobj=buffer) as tar:
34 symlink = tarfile.TarInfo(name="symlink")
35 symlink.type = tarfile.LNKTYPE
36 symlink.linkname = "target"
37 tar.addfile(symlink)
38
39 expected = tarfile.TarInfo(name="info/expected")
40 tar.addfile(expected, io.BytesIO())
41 unexpected = tarfile.TarInfo(name="info/unexpected")
42 tar.addfile(unexpected, io.BytesIO())
43 return buffer.getbuffer()
44
45
46 @contextlib.contextmanager
47 def timeme(message: str = ""):
48 begin = time.time()
49 yield
50 end = time.time()
51 print(f"{message}{end - begin:0.2f}s")
52
53
•54 @pytest.mark.skip(reason="Conda is not yet available for Debian")
55 def test_transmute(conda_paths: list[Path], tmpdir):
56 tarbz_packages = []
57 for path in conda_paths:
58 path = str(path)
59 if path.endswith(".tar.bz2") and (1 << 20 < os.stat(path).st_size < 1 << 22):
60 tarbz_packages = [path]
61 conda_packages = [] # not supported
62
63 assert tarbz_packages, "no medium-sized .tar.bz2 packages found"
64
65 metadata_checks = 0
66
67 for packages in (conda_packages, tarbz_packages):
68 for package in packages:
69 with timeme(f"{package} took "):
70 out = transmute(package, tmpdir)
71 _, missing, mismatched = validate_converted_files_match_streaming(
72 out, package, strict=True
73 )
74 assert missing == mismatched == []
75 if out.name.endswith(".conda"):
76 with ZipFile(out) as zf:
77 metadata_checks += 1
78 assert "metadata.json" in zf.namelist()
79
80 assert metadata_checks > 0
81
82
83 def test_transmute_symlink(tmpdir, testtar_bytes):
84 testtar = Path(tmpdir, "test.tar.bz2")
85 testtar.write_bytes(testtar_bytes)
86
87 out = transmute(str(testtar), tmpdir)
88 _, missing, mismatched = validate_converted_files_match_streaming(
89 out, testtar, strict=True
90 )
91 assert missing == mismatched == []
92
93
94 def test_transmute_info_filter(tmpdir, testtar_bytes):
95 testtar = Path(tmpdir, "test.tar.bz2")
96 testtar.write_bytes(testtar_bytes)
97
98 transmute(
99 str(testtar), tmpdir, is_info=lambda filename: filename == "info/expected"
100 )
101
102 with open(Path(tmpdir, "test.conda"), "rb") as fileobj:
103 for component, expected in (
104 (CondaComponent.info, {"info/expected"}),
105 (
106 CondaComponent.pkg,
107 {
108 "info/unexpected",
109 "symlink",
110 },
111 ),
112 ):
113 items = stream_conda_component("test.conda", fileobj, component)
114 assert {member.name for tar, member in items} == expected, items
115
•116 @pytest.mark.skip(reason="Conda is not yet available for Debian")
117 def test_transmute_backwards(tmpdir, conda_paths):
118 tarbz_packages = []
119 for path in conda_paths:
120 path = str(path)
121 if path.endswith(".conda") and (1 << 20 < os.stat(path).st_size < 1 << 22):
122 tarbz_packages = [path]
123 conda_packages = [] # not supported
124
125 assert tarbz_packages, "no medium-sized .conda packages found"
126
127 for packages in (conda_packages, tarbz_packages):
128 for package in packages:
129 with timeme(f"{package} took "):
130 out = transmute_tar_bz2(package, tmpdir)
131 _, missing, mismatched = validate_converted_files_match_streaming(
132 out, package, strict=True
133 )
134 assert missing == mismatched == []
135
136
137 def test_transmute_tarbz2_to_tarbz2(tmpdir, testtar_bytes):
138 testtar = Path(tmpdir, "test.tar.bz2")
139 testtar.write_bytes(testtar_bytes)
140 outdir = Path(tmpdir, "output")
141 outdir.mkdir()
142 out = transmute_tar_bz2(str(testtar), outdir)
143 _, missing, mismatched = validate_converted_files_match_streaming(
144 out, testtar, strict=True
145 )
146 assert missing == mismatched == []
147
148
149 def test_transmute_conditional_zip64(tmp_path, monkeypatch):
150 """
151 Test that zip64 is used in transmute after a threshold.
152 """
153
154 LIMIT = 16384
155
156 for test_size, extra_expected in (LIMIT // 2, False), (LIMIT * 2, True):
157 monkeypatch.setattr("conda_package_streaming.create.CONDA_ZIP64_LIMIT", LIMIT)
158 monkeypatch.setattr("zipfile.ZIP64_LIMIT", LIMIT)
159
160 tmp_tar = tmp_path / f"{test_size}.tar.bz2"
161 with tarfile.open(tmp_tar, "w:bz2") as tar:
162 pkg = tarfile.TarInfo(name="packagedata")
163 data = io.BytesIO(os.urandom(test_size))
164 pkg.size = len(data.getbuffer())
165 tar.addfile(pkg, data)
166
167 info = tarfile.TarInfo(name="info/data")
168 data = io.BytesIO(os.urandom(test_size))
169 info.size = len(data.getbuffer())
170 tar.addfile(info, data)
171
172 out = transmute(str(tmp_tar), tmp_path)
173
174 with ZipFile(out) as e:
175 assert e.filelist[0].extra == b""
176 # when zip64 extension is used, extra contains zip64 headers
177 assert bool(e.filelist[1].extra) == extra_expected
178 assert bool(e.filelist[2].extra) == extra_expected
179
180
•181 @pytest.mark.skip(reason="Conda is not yet available for Debian")
182 def test_transmute_stream(tmpdir, conda_paths):
183 """
184 Test example from transmute_stream documentation. Recompress .conda using
185 transmute_stream()
186 """
187 conda_packages = []
188 for path in conda_paths:
189 if path.name.endswith(".conda") and (1 << 20 < os.stat(path).st_size < 1 << 22):
190 conda_packages.append(path)
191
192 for package in conda_packages[:3]:
193 file_id = package.stem
194
195 # also testing usage of LegacyCompressor here
196 class LegacyCompressor:
197 def stream_writer(self, writer, *, size, closefd):
198 return zstd.open(writer, mode="wb")
199
200 transmute_stream(
201 file_id,
202 tmpdir,
203 compressor=LegacyCompressor(),
204 package_stream=itertools.chain(
205 stream_conda_component(package, component=CondaComponent.pkg),
206 stream_conda_component(package, component=CondaComponent.info),
207 ),
208 )
209
210 _, missing, mismatched = validate_converted_files_match_streaming(
211 tmpdir / package.name, package, strict=True
212 )
213 assert missing == mismatched == []
214
215
216 def test_anonymize_helper():
217 ti = tarfile.TarInfo(name="info")
218 ti.uid = ti.gid = 500
219 ti.uname = ti.gname = "somebody"
220 anon = anonymize(ti)
221 assert anon.name == ti.name # they are also the same object
222 assert anon.uid == anon.gid == 0
223 assert anon.uname == anon.gname == ""
224
225
226 def test_compression_params_mutual_exclusivity_level(tmpdir, testtar_bytes):
227 """Test for error if compressor= and level options are passed."""
228 testtar = Path(tmpdir, "test.tar.bz2")
229 testtar.write_bytes(testtar_bytes)
230
231 class LegacyCompressor:
232 def stream_writer(self, writer, *, size, closefd):
233 return zstd.open(writer, mode="wb")
234
235 with pytest.raises(
236 ValueError,
237 match="`compressor` overrides `compression_level` and `compression_threads`",
238 ):
239 transmute_stream(
240 "test",
241 tmpdir,
242 compressor=LegacyCompressor(),
243 compression_level=19,
244 package_stream=stream_conda_component(testtar),
245 )
246
247
248 def test_compression_params_mutual_exclusivity_threads(tmpdir, testtar_bytes):
249 """Test for error if compressor= and threads options are passed."""
250 testtar = Path(tmpdir, "test.tar.bz2")
251 testtar.write_bytes(testtar_bytes)
252
253 class LegacyCompressor:
254 def stream_writer(self, writer, *, size, closefd):
255 return zstd.open(writer, mode="wb")
256
257 with pytest.raises(
258 ValueError,
259 match="`compressor`",
260 ):
261 transmute_stream(
262 "test",
263 tmpdir,
264 compressor=LegacyCompressor(),
265 compression_threads=4,
266 package_stream=stream_conda_component(testtar),
267 )
268
269
270 def test_compression_params_mutual_exclusivity_both(tmpdir, testtar_bytes):
271 """Test that compressor is mutually exclusive with both compression parameters"""
272 testtar = Path(tmpdir, "test.tar.bz2")
273 testtar.write_bytes(testtar_bytes)
274
275 class LegacyCompressor:
276 def stream_writer(self, writer, *, size, closefd):
277 return zstd.open(writer, mode="wb")
278
279 with pytest.raises(
280 ValueError,
281 match="`compressor`",
282 ):
283 transmute_stream(
284 "test",
285 tmpdir,
286 compressor=LegacyCompressor(),
287 compression_level=19,
288 compression_threads=4,
289 package_stream=stream_conda_component(testtar),
290 )
291
292
293 def test_compressor_missing_stream_writer(tmpdir, testtar_bytes):
294 """Test that compressor must have stream_writer method"""
295 testtar = Path(tmpdir, "test.tar.bz2")
296 testtar.write_bytes(testtar_bytes)
297
298 class BadCompressor:
299 """Compressor without stream_writer method"""
300
301 pass
302
303 with pytest.raises(
304 TypeError,
305 match="compressor must provide stream_writer",
306 ):
307 transmute_stream(
308 "test",
309 tmpdir,
310 compressor=BadCompressor(),
311 package_stream=stream_conda_component(testtar),
312 )
313
314
315 def test_compression_level_thread_defaults(tmpdir, testtar_bytes):
316 """Test that compression_level and compression_threads use defaults when None"""
317 testtar = Path(tmpdir, "test.tar.bz2")
318 testtar.write_bytes(testtar_bytes)
319
320 # Transmute with None values should use defaults (ZSTD_COMPRESS_LEVEL=19,
321 # ZSTD_COMPRESS_THREADS=1)
322 #
323 # This test verifies that the defaults are applied and the .conda file is
324 # created successfully
325 out = transmute_stream(
326 "test",
327 tmpdir,
328 compression_level=None,
329 compression_threads=None,
330 package_stream=stream_conda_component(testtar),
331 )
332
333 assert out.exists()
334 assert out.name == "test.conda"
335 _, missing, mismatched = validate_converted_files_match_streaming(
336 out, testtar, strict=True
337 )
338 assert missing == mismatched == []
339
340
341 def test_compression_explicit_values(tmpdir, testtar_bytes):
342 """Test that explicit compression parameters are used"""
343 testtar = Path(tmpdir, "test.tar.bz2")
344 testtar.write_bytes(testtar_bytes)
345
346 # Use explicit compression values
347 out = transmute_stream(
348 "test",
349 tmpdir,
350 compression_level=10,
351 compression_threads=2,
352 package_stream=stream_conda_component(testtar),
353 )
354
355 assert out.exists()
356 assert out.name == "test.conda"
357 _, missing, mismatched = validate_converted_files_match_streaming(
358 out, testtar, strict=True
359 )
360 assert missing == mismatched == []