"""Tests for immutable filesystem-backed source storage.""" from io import BytesIO from pathlib import Path import pytest from ekp_object_storage import ( InvalidStorageKeyError, LocalObjectStorage, ObjectAlreadyExistsError, ObjectNotFoundError, ) class FailingSource(BytesIO): """Binary stream that simulates an interrupted upload.""" def read(self, size: int | None = -1) -> bytes: raise OSError("simulated source failure") def test_put_open_exists_and_delete(tmp_path: Path) -> None: storage = LocalObjectStorage(tmp_path / "objects") stored = storage.put("documents/source.txt", BytesIO(b"source bytes")) assert stored.key == "documents/source.txt" assert stored.size_bytes == 12 assert storage.exists(stored.key) with storage.open(stored.key) as source: assert source.read() == b"source bytes" storage.delete(stored.key) assert not storage.exists(stored.key) def test_put_never_overwrites_immutable_source(tmp_path: Path) -> None: storage = LocalObjectStorage(tmp_path) storage.put("document.txt", BytesIO(b"original")) with pytest.raises(ObjectAlreadyExistsError): storage.put("document.txt", BytesIO(b"replacement")) with storage.open("document.txt") as source: assert source.read() == b"original" def test_put_removes_partial_file_after_stream_failure(tmp_path: Path) -> None: storage = LocalObjectStorage(tmp_path) with pytest.raises(OSError, match="simulated source failure"): storage.put("interrupted.bin", FailingSource()) assert not storage.exists("interrupted.bin") def test_missing_local_object_uses_provider_neutral_error(tmp_path: Path) -> None: storage = LocalObjectStorage(tmp_path) with pytest.raises(ObjectNotFoundError): storage.open("missing.bin") with pytest.raises(ObjectNotFoundError): storage.delete("missing.bin") @pytest.mark.parametrize( "key", ["", "/absolute.txt", "../escape.txt", "nested/../escape.txt", "bad\\key.txt"], ) def test_storage_rejects_unsafe_keys(tmp_path: Path, key: str) -> None: storage = LocalObjectStorage(tmp_path) with pytest.raises(InvalidStorageKeyError): storage.put(key, BytesIO(b"unsafe")) def test_storage_rejects_symlink_escape(tmp_path: Path) -> None: root = tmp_path / "root" outside = tmp_path / "outside" root.mkdir() outside.mkdir() (root / "linked").symlink_to(outside, target_is_directory=True) storage = LocalObjectStorage(root) with pytest.raises(InvalidStorageKeyError): storage.put("linked/escape.txt", BytesIO(b"unsafe"))