| 1 | import shutil |
| 2 | import tempfile |
| 3 | import unittest |
| 4 | from io import BytesIO |
| 5 | from pathlib import Path |
| 6 | from secrets import token_bytes, token_urlsafe |
| 7 | |
| 8 | from backports.zstd import register_shutil, tarfile, zipfile |
| 9 | |
| 10 | |
| 11 | class TestShutil(unittest.TestCase): |
| 12 | def setUp(self): |
| 13 | register_shutil() |
| 14 | self.tmpdir = tempfile.TemporaryDirectory() |
| 15 | self.tmppath = Path(self.tmpdir.name) |
| 16 | (self.tmppath / "src").mkdir() |
| 17 | (self.tmppath / "src" / "foo").write_text("bar") |
| 18 | |
| 19 | def tearDown(self): |
| 20 | self.tmpdir.cleanup() |
| 21 | |
| 22 | def test_registration(self): |
| 23 | self.assertTrue(("zstdtar", "zstd'ed tar-file") in shutil.get_archive_formats()) |
| 24 | self.assertTrue(("zip", "ZIP file") in shutil.get_archive_formats()) |
| 25 | self.assertTrue( |
| 26 | ("zstdtar", [".tar.zst", ".tzst"], "zstd'ed tar-file") |
| 27 | in shutil.get_unpack_formats() |
| 28 | ) |
| 29 | self.assertTrue(("zip", [".zip"], "ZIP file") in shutil.get_unpack_formats()) |
| 30 | |
| 31 | def test_make_archive_tar(self): |
| 32 | shutil.make_archive((self.tmppath / "archive").as_posix(), "zstdtar", self.tmppath) |
| 33 | with (self.tmppath / "archive.tar.zst").open("rb") as f: |
| 34 | self.assertEqual(f.read(4), bytes.fromhex("28 b5 2f fd")) |
| 35 | |
| 36 | def test_unpack_archive_tar(self): |
| 37 | archive_path = self.tmppath / "test.tar.zst" |
| 38 | raw = token_bytes(1_000) |
| 39 | raw_name = token_urlsafe(10) |
| 40 | with tarfile.open(archive_path, "w:zst") as tf: |
| 41 | ti = tarfile.TarInfo(raw_name) |
| 42 | ti.size = len(raw) |
| 43 | tf.addfile(ti, BytesIO(raw)) |
| 44 | out_path = self.tmppath / "test_tar" |
| 45 | shutil.unpack_archive(archive_path, out_path) |
| 46 | self.assertEqual((out_path / raw_name).read_bytes(), raw) |
| 47 | |
| 48 | def test_unpack_archive_zip(self): |
| 49 | archive_path = self.tmppath / "test.zip" |
| 50 | raw = token_bytes(1_000) |
| 51 | raw_name = token_urlsafe(10) |
| 52 | with zipfile.ZipFile(archive_path, "w") as zf: |
| 53 | zf.writestr(raw_name, raw, zipfile.ZIP_ZSTANDARD) |
| 54 | out_path = self.tmppath / "test_zip" |
| 55 | shutil.unpack_archive(archive_path, out_path) |
| 56 | self.assertEqual((out_path / raw_name).read_bytes(), raw) |
| 57 | |
| 58 | |
| 59 | if __name__ == "__main__": |
| 60 | unittest.main() |