Debian Codegraph @

tests/test_api.py

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