Debian Codegraph @

tests/test_api.py

raw ◀ ▶
1 Debian patch touch this file
1 from __future__ import annotations
2
3 import json
4 import os
5 import platform
6 import shutil
7 import sys
8 import tarfile
9 import time
10 import zipfile
11 from tempfile import TemporaryDirectory
12 from pathlib import Path
13
14 import pytest
15
16 import conda_package_handling
17 import conda_package_handling.tarball
18 from conda_package_handling import api, exceptions
19
20
21 this_dir = os.path.dirname(__file__)
22 data_dir = os.path.join(this_dir, "data")
23 version_file = Path(this_dir).parent / "src" / "conda_package_handling" / "__init__.py"
24 test_package_name = "mock-2.0.0-py37_1000"
25 test_package_name_2 = "cph_test_data-0.0.1-0"
26
27
28 def _write_package_dir(prefix: Path | str, files: dict[str, str]):
29 """Write a package directory tree under ``prefix``.
30
31 ``files`` maps archive-relative paths to file contents. Parent directories
32 are created as needed.
33 """
34 root = Path(prefix)
35 for relpath, content in files.items():
36 path = root / relpath
37 path.parent.mkdir(parents=True, exist_ok=True)
38 path.write_text(content, encoding="utf-8")
39
40
41 def _component_member_paths(
42 extract_dir: Path, conda_path: Path | str, component: str
43 ) -> set[str]:
44 """Return member paths from one .conda inner tarball.
45
46 Extracts only ``component`` (``"info"`` or ``"pkg"``) from ``conda_path``
47 into ``extract_dir`` and returns archive-relative paths of regular files.
48 """
49 api.extract(str(conda_path), extract_dir, components=component)
50 return {
51 path.relative_to(extract_dir).as_posix()
52 for path in extract_dir.rglob("*")
53 if path.is_file()
54 }
55
56
57 @pytest.mark.skipif(
58 bool(os.environ.get("GITHUB_ACTIONS", False)), reason="Fails on GitHub Actions"
59 )
60 @pytest.mark.skipif(not version_file.exists(), reason=f"Could not find {version_file}")
61 def test_correct_version():
62 """
63 Prevent accidentally running tests against a globally installed different version.
64 """
65 assert conda_package_handling.__version__ in version_file.read_text()
66
67
68 def test_api_extract_tarball_implicit_path(testing_workdir):
69 tarfile = os.path.join(data_dir, test_package_name + ".tar.bz2")
70 local_tarfile = os.path.join(testing_workdir, os.path.basename(tarfile))
71 shutil.copy2(tarfile, local_tarfile)
72 api.extract(local_tarfile)
73 assert os.path.isfile(os.path.join(testing_workdir, test_package_name, "info", "index.json"))
74
75
76 def test_api_tarball_details(testing_workdir):
77 tarfile = os.path.join(data_dir, test_package_name + ".tar.bz2")
78 results = api.get_pkg_details(tarfile)
79 assert results["size"] == 106576
80 assert results["md5"] == "0f9cce120a73803a70abb14bd4d4900b"
81 assert results["sha256"] == "34c659b0fdc53d28ae721fd5717446fb8abebb1016794bd61e25937853f4c29c"
82
83
84 def test_api_conda_v2_details(testing_workdir):
85 condafile = os.path.join(data_dir, test_package_name + ".conda")
86 results = api.get_pkg_details(condafile)
87 assert results["size"] == 113421
88 assert results["sha256"] == "181ec44eb7b06ebb833eae845bcc466ad96474be1f33ee55cab7ac1b0fdbbfa3"
89 assert results["md5"] == "23c226430e35a3bd994db6c36b9ac8ae"
90
91
92 def test_api_extract_tarball_explicit_path(testing_workdir):
93 tarfile = os.path.join(data_dir, test_package_name + ".tar.bz2")
94 local_tarfile = os.path.join(testing_workdir, os.path.basename(tarfile))
95 shutil.copy2(tarfile, local_tarfile)
96
97 api.extract(local_tarfile, "manual_path")
98 assert os.path.isfile(os.path.join(testing_workdir, "manual_path", "info", "index.json"))
99
100
101 def test_api_extract_conda_v2_implicit_path(testing_workdir):
102 condafile = os.path.join(data_dir, test_package_name + ".conda")
103 local_condafile = os.path.join(testing_workdir, os.path.basename(condafile))
104 shutil.copy2(condafile, local_condafile)
105 api.extract(local_condafile)
106 assert os.path.isfile(os.path.join(testing_workdir, test_package_name, "info", "index.json"))
107
108
109 def test_api_extract_conda_v2_no_destdir_relative_path(testing_workdir):
110 cwd = os.getcwd()
111 os.chdir(testing_workdir)
112 try:
113 condafile = os.path.join(data_dir, test_package_name + ".conda")
114 local_condafile = os.path.join(testing_workdir, os.path.basename(condafile))
115 shutil.copy2(condafile, local_condafile)
116
117 condafile = os.path.basename(local_condafile)
118 assert os.path.exists(condafile)
119 # cli passes dest=None, prefix=None
120 api.extract(condafile, None, prefix=None)
121 finally:
122 os.chdir(cwd)
123
124
125 def test_api_extract_conda_v2_explicit_path(testing_workdir):
126 condafile = os.path.join(data_dir, test_package_name + ".conda")
127 local_condafile = os.path.join(testing_workdir, os.path.basename(condafile))
128 shutil.copy2(condafile, local_condafile)
129
130 api.extract(condafile, "manual_path")
131 assert os.path.isfile(os.path.join(testing_workdir, "manual_path", "info", "index.json"))
132
133
134 def test_api_extract_conda_v2_explicit_path_prefix(testing_workdir):
135 tarfile = os.path.join(data_dir, test_package_name + ".conda")
136 api.extract(tarfile, prefix=os.path.join(testing_workdir, "folder"))
137 assert os.path.isfile(
138 os.path.join(testing_workdir, "folder", test_package_name, "info", "index.json")
139 )
140
141 api.extract(tarfile, dest_dir="steve", prefix=os.path.join(testing_workdir, "folder"))
142 assert os.path.isfile(os.path.join(testing_workdir, "folder", "steve", "info", "index.json"))
143
144
145 def test_api_extract_dest_dir_and_prefix_both_abs_raises():
146 tarfile = os.path.join(data_dir, test_package_name + ".conda")
147 with pytest.raises(ValueError):
148 api.extract(tarfile, prefix=os.path.dirname(tarfile), dest_dir=os.path.dirname(tarfile))
149
150
151 def test_api_extract_info_conda_v2(testing_workdir):
152 condafile = os.path.join(data_dir, test_package_name + ".conda")
153 local_condafile = os.path.join(testing_workdir, os.path.basename(condafile))
154 shutil.copy2(condafile, local_condafile)
155 api.extract(local_condafile, "manual_path", components="info")
156 assert os.path.isfile(os.path.join(testing_workdir, "manual_path", "info", "index.json"))
157 assert not os.path.isdir(os.path.join(testing_workdir, "manual_path", "lib"))
158
159
160 def check_conda_v2_metadata(condafile):
161 with zipfile.ZipFile(condafile) as zf:
162 d = json.loads(zf.read("metadata.json"))
163 assert d["conda_pkg_format_version"] == 2
164
165
166 def test_api_transmute_tarball_to_conda_v2(testing_workdir):
167 tarfile = os.path.join(data_dir, test_package_name + ".tar.bz2")
168 # lower compress level makes the test run much faster, even 15 is much
169 # better than 22
170 errors = api.transmute(tarfile, ".conda", testing_workdir, zstd_compress_level=3)
171 assert not errors
172 condafile = os.path.join(testing_workdir, test_package_name + ".conda")
173 assert os.path.isfile(condafile)
174 check_conda_v2_metadata(condafile)
175
176
177 def test_api_transmute_tarball_info_sorts_first(testing_workdir):
178 test_packages = [test_package_name]
179 test_packages_with_symlinks = [test_package_name_2]
180 if sys.platform != "win32":
181 test_packages += test_packages_with_symlinks
182 for test_package in test_packages:
183 test_file = os.path.join(data_dir, test_package + ".tar.bz2")
184
185 # transmute/convert doesn't re-sort files; extract to folder.
186 api.extract(test_file, testing_workdir)
187 out_fn = os.path.join(testing_workdir, test_package + ".tar.bz2")
188 out = api.create(testing_workdir, None, out_fn)
189 assert out == out_fn
190
191 # info must be first
192 with tarfile.open(out_fn, "r:bz2") as repacked:
193 info_seen = False
194 not_info_seen = False
195 for member in repacked:
196 if member.name.startswith("info"):
197 assert not_info_seen is False, (
198 f"{test_package} package info/ must sort first, "
199 )
200 f"but {[m.name for m in repacked.getmembers()]}"
201 info_seen = True
202 else:
203 not_info_seen = True
204 assert info_seen, "package had no info/ files"
205
206
207 @pytest.mark.skipif(sys.platform == "win32", reason="windows and symlinks are not great")
208 def test_api_transmute_to_conda_v2_contents(testing_workdir):
209 def _walk(path):
210 for entry in os.scandir(path):
211 if entry.is_dir(follow_symlinks=False):
212 yield from _walk(entry.path)
213 continue
214 yield entry
215
216 tar_path = os.path.join(data_dir, test_package_name_2 + ".tar.bz2")
217 conda_path = os.path.join(testing_workdir, test_package_name_2 + ".conda")
218 api.transmute(tar_path, ".conda", testing_workdir, zstd_compress_level=3)
219
220 # Verify original contents were all put in the right place
221 pkg_tarbz2 = tarfile.open(tar_path, mode="r:bz2")
222 info_items = [item for item in pkg_tarbz2.getmembers() if item.path.startswith("info/")]
223 pkg_items = [item for item in pkg_tarbz2.getmembers() if not item.path.startswith("info/")]
224
225 errors = []
226 for component, expected in (("info", info_items), ("pkg", pkg_items)):
227 with TemporaryDirectory() as root:
228 api.extract(conda_path, root, components=component)
229
230 contents = {
231 os.path.relpath(entry.path, root): {
232 "is_symlink": entry.is_symlink(),
233 "target": os.readlink(entry.path) if entry.is_symlink() else None,
234 }
235 for entry in _walk(root)
236 }
237
238 for item in expected:
239 if item.path not in contents:
240 errors.append(f"'{item.path}' not found in {component} contents")
241 continue
242
243 ct = contents.pop(item.path)
244 if item.issym():
245 if not ct["is_symlink"] or ct["target"] != item.linkname:
246 errors.append(
247 f"{item.name} -> {item.linkname} incorrect in {component} contents"
248 )
249 elif not item.isfile():
250 # Raise an exception rather than appending to `errors`
251 # because getting to this point is an indication that our
252 # test data (i.e., .tar.bz2 package) is corrupt, rather
253 # than the `.transmute` function having problems (which is
254 # what `errors` is meant to track). For context, conda
255 # packages should only contain regular files and symlinks.
256 raise ValueError(f"unexpected item '{item.path}' in test .tar.bz2")
257 if contents:
258 errors.append(f"extra files [{', '.join(contents)}] in {component} contents")
259 assert not errors
260
261
262 @pytest.mark.parametrize("via", ["create", "transmute"])
263 def test_api_cep35_info_placement(tmp_path: Path, via):
264 package_name = "cep35-test-1.0.0-0"
265 prefix = tmp_path / "prefix"
266 files = {
267 "info/licenses/LICENSE": "MIT License\n",
268 "bin/cep35-test": "#!/bin/sh\n",
269 "info/index.json": json.dumps(
270 {
271 "arch": "x86_64",
272 "build": "0",
273 "build_number": 0,
274 "name": "cep35-test",
275 "platform": "linux",
276 "version": "1.0.0",
277 }
278 ),
279 }
280 _write_package_dir(prefix, files)
281
282 if via == "create":
283 conda_path = tmp_path / f"{package_name}.conda"
284 api.create(str(prefix), None, f"{package_name}.conda", out_folder=str(tmp_path))
285 else:
286 tar_path = tmp_path / f"{package_name}.tar.bz2"
287 api.create(str(prefix), None, f"{package_name}.tar.bz2", out_folder=str(tmp_path))
288 errors = api.transmute(str(tar_path), ".conda", str(tmp_path), zstd_compress_level=3)
289 assert not errors
290 conda_path = tmp_path / f"{package_name}.conda"
291
292 info_paths = _component_member_paths(tmp_path / "info", conda_path, "info")
293 pkg_paths = _component_member_paths(tmp_path / "pkg", conda_path, "pkg")
294
295 errors = []
296 for path in files:
297 if path.startswith("info/"):
298 if path in pkg_paths:
299 errors.append(f"{path} incorrectly placed in pkg-*")
300 elif path not in info_paths:
301 errors.append(f"{path} missing from info-*")
302 elif path in info_paths:
303 errors.append(f"{path} incorrectly placed in info-*")
304 elif path not in pkg_paths:
305 errors.append(f"{path} missing from pkg-*")
306
307 assert not errors, "CEP 35 component split failed:\n" + "\n".join(errors)
308
309
310 def test_api_transmute_conda_v2_to_tarball(testing_workdir):
311 condafile = os.path.join(data_dir, test_package_name + ".conda")
312 outfile = Path(testing_workdir, test_package_name + ".tar.bz2")
313 # one quiet=True in the test suite for coverage
314 api.transmute(condafile, ".tar.bz2", testing_workdir, quiet=True)
315 assert outfile.is_file()
316
317 # test that no-force keeps file, and force overwrites file
318 for force in False, True:
319 mtime = outfile.stat().st_mtime
320 time.sleep(2 if platform.platform() == "Windows" else 0)
321 api.transmute(condafile, ".tar.bz2", testing_workdir, force=force)
322 mtime2 = outfile.stat().st_mtime
323 assert (mtime2 == mtime) != force
324
325
326 def test_warning_when_bundling_no_metadata(testing_workdir):
327 pass
328
329
330 @pytest.mark.skipif(sys.platform == "win32", reason="windows and symlinks are not great")
331 def test_create_package_with_uncommon_conditions_captures_all_content(testing_workdir):
332 os.makedirs("src/a_folder")
333 os.makedirs("src/empty_folder")
334 os.makedirs("src/symlink_stuff")
335 with open("src/a_folder/text_file", "w") as f:
336 f.write("weee")
337 open("src/empty_file", "w").close()
338 os.link("src/a_folder/text_file", "src/a_folder/hardlink_to_text_file")
339 os.symlink("../a_folder", "src/symlink_stuff/symlink_to_a")
340 os.symlink("../empty_file", "src/symlink_stuff/symlink_to_empty_file")
341 os.symlink("../a_folder/text_file", "src/symlink_stuff/symlink_to_text_file")
342
343 with tarfile.open("pinkie.tar.bz2", "w:bz2") as tf:
344
345 def add(source, target):
346 tf.add(source, target, recursive=False)
347
348 add("src/empty_folder", "empty_folder")
349 add("src/empty_file", "empty_file")
350 add("src/a_folder", "a_folder")
351 add("src/a_folder/text_file", "a_folder/text_file")
352 add("src/a_folder/hardlink_to_text_file", "a_folder/hardlink_to_text_file")
353 add("src/symlink_stuff/symlink_to_a", "symlink_stuff/symlink_to_a")
354 add(
355 "src/symlink_stuff/symlink_to_empty_file",
356 "symlink_stuff/symlink_to_empty_file",
357 )
358 add(
359 "src/symlink_stuff/symlink_to_text_file",
360 "symlink_stuff/symlink_to_text_file",
361 )
362
363 api.create("src", None, "thebrain.tar.bz2")
364
365 # test against both archives created manually and those created by cph.
366 # They should be equal in all ways.
367 for fn in ("pinkie.tar.bz2", "thebrain.tar.bz2"):
368 api.extract(fn)
369 target_dir = fn[:-8]
370 flist = [
371 "empty_folder",
372 "empty_file",
373 "a_folder/text_file",
374 "a_folder/hardlink_to_text_file",
375 "symlink_stuff/symlink_to_a",
376 "symlink_stuff/symlink_to_text_file",
377 "symlink_stuff/symlink_to_empty_file",
378 ]
379
380 # no symlinks on windows
381 if sys.platform != "win32":
382 # not directly included but checked symlink
383 flist.append("symlink_stuff/symlink_to_a/text_file")
384
385 missing_content = []
386 for f in flist:
387 path_that_should_be_there = os.path.join(testing_workdir, target_dir, f)
388 if not (
389 os.path.exists(path_that_should_be_there)
390 or os.path.lexists(path_that_should_be_there) # noqa
391 ):
392 missing_content.append(f)
393 if missing_content:
394 print("missing files in output package")
395 print(missing_content)
396 sys.exit(1)
397
398 # hardlinks should be preserved, but they're currently not with libarchive
399 # hardlinked_file = os.path.join(testing_workdir, target_dir, 'a_folder/text_file')
400 # stat = os.stat(hardlinked_file)
401 # assert stat.st_nlink == 2
402
403 hardlinked_file = os.path.join(testing_workdir, target_dir, "empty_file")
404 stat = os.stat(hardlinked_file)
405 if sys.platform != "win32":
406 assert stat.st_nlink == 1
407
408
•409 @pytest.mark.skipif(reason="Don't understand why this doesn't behave. Punt.")
410 def test_secure_refusal_to_extract_abs_paths(testing_workdir):
411 with tarfile.open("pinkie.tar.bz2", "w:bz2") as tf:
412 open("thebrain", "w").close()
413 tf.add(os.path.join(testing_workdir, "thebrain"), "/naughty/abs_path")
414 try:
415 tf.getmember("/naughty/abs_path")
416 except KeyError:
417 pytest.skip("Tar implementation does not generate unsafe paths in archive.")
418
419 with pytest.raises(api.InvalidArchiveError):
420 api.extract("pinkie.tar.bz2")
421
422
423 def tests_secure_refusal_to_extract_dotdot(testing_workdir):
424 with tarfile.open("pinkie.tar.bz2", "w:bz2") as tf:
425 open("thebrain", "w").close()
426 tf.add(os.path.join(testing_workdir, "thebrain"), "../naughty/abs_path")
427
428 with pytest.raises(api.InvalidArchiveError):
429 api.extract("pinkie.tar.bz2")
430
431
432 def test_api_bad_filename(testing_workdir):
433 with pytest.raises(ValueError):
434 api.extract("pinkie.rar", testing_workdir)
435
436
437 def test_details_bad_extension():
438 with pytest.raises(ValueError):
439 # TODO this function should not exist
440 api.get_pkg_details("pinkie.rar")
441
442
443 def test_convert_bad_extension(testing_workdir):
444 api._convert("pinkie.rar", ".conda", testing_workdir)
445
446
447 def test_convert_keyerror(tmpdir, mocker):
448 tarfile = os.path.join(data_dir, test_package_name + ".tar.bz2")
449
450 mocker.patch(
451 "conda_package_streaming.transmute.transmute",
452 side_effect=KeyboardInterrupt(),
453 )
454
455 # interrupted before ".conda" was created
456 with pytest.raises(KeyboardInterrupt):
457 api._convert(tarfile, ".conda", tmpdir)
458
459 def create_file_and_raise(*args, **kwargs):
460 out_fn = Path(tmpdir, Path(tarfile[: -len(".tar.bz2")] + ".conda").name)
461 print("out fn", out_fn)
462 out_fn.write_text("")
463 raise KeyboardInterrupt()
464
465 mocker.patch("conda_package_streaming.transmute.transmute", side_effect=create_file_and_raise)
466
467 # interrupted after ".conda" was created
468 with pytest.raises(KeyboardInterrupt):
469 api._convert(tarfile, ".conda", tmpdir)
470
471
472 def test_create_filelist(tmpdir, mocker):
473 # another bad API, tested for coverage
474 filelist = Path(tmpdir, "filelist.txt")
475 filelist.write_text("\n".join(["filelist.txt", "anotherfile"]))
476
477 # when looking for filelist-not-found.txt
478 with pytest.raises(FileNotFoundError):
479 api.create(str(tmpdir), "filelist-not-found.txt", str(tmpdir / "newconda.conda"))
480
481 # when adding anotherfile
482 with pytest.raises(FileNotFoundError):
483 api.create(str(tmpdir), str(filelist), str(tmpdir / "newconda.conda"))
484
485 # unrecognized target extension
486 with pytest.raises(ValueError):
487 api.create(str(tmpdir), str(filelist), str(tmpdir / "newpackage.rar"))
488
489 def create_file_and_raise(prefix, file_list, out_fn, *args, **kwargs):
490 Path(prefix, out_fn).write_text("")
491 raise KeyboardInterrupt()
492
493 mocker.patch(
494 "conda_package_handling.conda_fmt.CondaFormat_v2.create",
495 side_effect=create_file_and_raise,
496 )
497
498 # failure inside inner create()
499 with pytest.raises(KeyboardInterrupt):
500 api.create(str(tmpdir), str(filelist), str(tmpdir / "newpackage.conda"))
501
502
503 def test_api_transmute_fail_validation(tmpdir, mocker):
504 package = os.path.join(data_dir, test_package_name + ".conda")
505
506 # this code is only called for .conda -> .tar.bz2; a streaming validate for
507 # .tar.bz2 -> .conda would be a good idea.
508 mocker.patch(
509 "conda_package_handling.validate.validate_converted_files_match_streaming",
510 return_value=(str(package), {"missing-file.txt"}, {"mismatched-size.txt"}),
511 )
512
513 errors = api.transmute(package, ".tar.bz2", tmpdir)
514 assert errors
515
516
517 def test_api_transmute_fail_validation_to_conda(tmpdir, mocker):
518 package = os.path.join(data_dir, test_package_name + ".tar.bz2")
519
520 mocker.patch(
521 "conda_package_handling.validate.validate_converted_files_match_streaming",
522 return_value=(str(package), {"missing-file.txt"}, {"mismatched-size.txt"}),
523 )
524
525 errors = api.transmute(package, ".conda", tmpdir, zstd_compress_level=3)
526 assert errors
527
528
529 def test_api_transmute_fail_validation_2(tmpdir, mocker):
530 package = os.path.join(data_dir, test_package_name + ".conda")
531 tmptarfile = tmpdir / Path(package).name
532 shutil.copy(package, tmptarfile)
533
534 mocker.patch(
535 "conda_package_handling.validate.validate_converted_files_match_streaming",
536 side_effect=Exception("not today"),
537 )
538
539 # run with out_folder=None
540 errors = api.transmute(str(tmptarfile), ".tar.bz2")
541 assert errors
542
543
544 def test_api_translates_exception(mocker, tmpdir):
545 from conda_package_streaming.extract import exceptions as cps_exceptions
546
547 tarfile = os.path.join(data_dir, test_package_name + ".tar.bz2")
548
549 # translates their exception to our exception of the same name
550 mocker.patch(
551 "conda_package_streaming.package_streaming.stream_conda_component",
552 side_effect=cps_exceptions.CaseInsensitiveFileSystemError(),
553 )
554
555 # should this be exported from the api or inherit from InvalidArchiveError?
556 with pytest.raises(exceptions.CaseInsensitiveFileSystemError):
557 api.extract(tarfile, tmpdir)
558
559
560 def test_zstd_pledged_size(testing_workdir):
561 try:
562 import compression.zstd as zstd
563 except ImportError:
564 import backports.zstd as zstd
565
566 pkg_dir = Path(testing_workdir) / "test_pkg"
567 _write_package_dir(
568 pkg_dir,
569 {
570 "info/index.json": json.dumps({"name": "test", "version": "1.0"}),
571 "info/files": "",
572 "pkg/test.txt": "test content",
573 },
574 )
575
576 output_conda = Path(testing_workdir) / "test-1.0-0.conda"
577 api.create(
578 pkg_dir,
579 None,
580 str(output_conda),
581 out_folder=testing_workdir,
582 )
583
584 with zipfile.ZipFile(output_conda) as conda_zip:
585 components = [
586 name
587 for name in conda_zip.namelist()
588 if name.endswith(".tar.zst")
589 ]
590 assert len(components) == 2
591
592 for component in components:
593 compressed = conda_zip.read(component)
594 frame_info = zstd.get_frame_info(compressed)
595 assert frame_info.decompressed_size == len(zstd.decompress(compressed))