|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import tarfile |
|
|
import tempfile |
|
|
from pathlib import Path |
|
|
|
|
|
import pytest |
|
|
|
|
|
from nemo.export.tarutils import TarPath |
|
|
|
|
|
|
|
|
@pytest.fixture |
|
|
def sample_tar(): |
|
|
|
|
|
with tempfile.TemporaryDirectory() as temp_dir: |
|
|
|
|
|
test_dir = Path(temp_dir) / "test_dir" |
|
|
test_dir.mkdir() |
|
|
|
|
|
(test_dir / "file1.txt").write_text("content1") |
|
|
(test_dir / "file2.txt").write_text("content2") |
|
|
(test_dir / "subdir").mkdir() |
|
|
(test_dir / "subdir" / "file3.txt").write_text("content3") |
|
|
|
|
|
|
|
|
tar_path = Path(temp_dir) / "test.tar" |
|
|
with tarfile.open(tar_path, "w") as tar: |
|
|
tar.add(test_dir, arcname=".") |
|
|
|
|
|
yield str(tar_path) |
|
|
|
|
|
|
|
|
def test_tar_path_initialization(sample_tar): |
|
|
|
|
|
with TarPath(sample_tar) as path: |
|
|
assert isinstance(path, TarPath) |
|
|
assert path.exists() |
|
|
|
|
|
|
|
|
with tarfile.open(sample_tar, "r") as tar: |
|
|
path = TarPath(tar) |
|
|
assert isinstance(path, TarPath) |
|
|
assert path.exists() |
|
|
|
|
|
|
|
|
def test_path_operations(sample_tar): |
|
|
with TarPath(sample_tar) as root: |
|
|
|
|
|
file_path = root / "file1.txt" |
|
|
assert str(file_path) == f"{sample_tar}/file1.txt" |
|
|
|
|
|
|
|
|
subdir_path = root / "subdir" / "file3.txt" |
|
|
assert str(subdir_path) == f"{sample_tar}/subdir/file3.txt" |
|
|
|
|
|
|
|
|
assert file_path.name == "file1.txt" |
|
|
assert subdir_path.name == "file3.txt" |
|
|
|
|
|
|
|
|
assert file_path.suffix == ".txt" |
|
|
assert (root / "subdir").suffix == "" |
|
|
|
|
|
|
|
|
def test_file_operations(sample_tar): |
|
|
with TarPath(sample_tar) as root: |
|
|
|
|
|
assert (root / "file1.txt").exists() |
|
|
assert (root / "file1.txt").is_file() |
|
|
|
|
|
|
|
|
assert (root / "subdir").exists() |
|
|
assert (root / "subdir").is_dir() |
|
|
|
|
|
|
|
|
assert not (root / "nonexistent.txt").exists() |
|
|
|
|
|
|
|
|
with (root / "file1.txt").open("r") as f: |
|
|
content = f.read() |
|
|
assert content == b"content1" |
|
|
|
|
|
|
|
|
def test_directory_operations(sample_tar): |
|
|
with TarPath(sample_tar) as root: |
|
|
|
|
|
entries = list(root.iterdir()) |
|
|
assert len(entries) == 5 |
|
|
|
|
|
|
|
|
txt_files = list(root.glob("*.txt")) |
|
|
assert len(txt_files) == 3 |
|
|
assert all(f.suffix == ".txt" for f in txt_files) |
|
|
|
|
|
|
|
|
all_txt_files = list(root.rglob("*.txt")) |
|
|
assert len(all_txt_files) == 3 |
|
|
assert all(f.suffix == ".txt" for f in all_txt_files) |
|
|
|
|
|
|
|
|
def test_error_handling(sample_tar): |
|
|
with TarPath(sample_tar) as root: |
|
|
|
|
|
with pytest.raises(FileNotFoundError): |
|
|
(root / "nonexistent.txt").open("r") |
|
|
|
|
|
|
|
|
with pytest.raises(NotImplementedError): |
|
|
(root / "file1.txt").open("w") |
|
|
|
|
|
|
|
|
with pytest.raises(ValueError): |
|
|
TarPath(123) |
|
|
|