Debian Codegraph @

tests/test_transmute.py

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