"""Regression tests for the Neon Object Storage boundary.""" from __future__ import annotations from typing import Any import pytest from infrastructure import object_storage class _Body: """Minimal streaming body test double.""" def __init__(self, content: bytes) -> None: self.content = content self.closed = False def read(self) -> bytes: """Return configured content.""" return self.content def close(self) -> None: """Record that the response stream was closed.""" self.closed = True class _S3Client: """Minimal S3 client test double.""" def __init__(self) -> None: self.calls: list[tuple[str, dict[str, Any]]] = [] self.body = _Body(b"stored document") def put_object(self, **kwargs: Any) -> None: """Record an object upload.""" self.calls.append(("put_object", kwargs)) def get_object(self, **kwargs: Any) -> dict[str, Any]: """Return the configured streaming body.""" self.calls.append(("get_object", kwargs)) return {"Body": self.body} def head_bucket(self, **kwargs: Any) -> None: """Record a bucket check.""" self.calls.append(("head_bucket", kwargs)) def test_client_uses_neon_endpoint_and_path_style( monkeypatch: pytest.MonkeyPatch, ) -> None: """The boto3 client uses Neon's branch endpoint and SigV4 path addressing.""" settings = { "AWS_ACCESS_KEY_ID": "access-key", "AWS_SECRET_ACCESS_KEY": "secret-key", "AWS_ENDPOINT_URL_S3": "https://branch.storage.example", "AWS_REGION": "us-east-2", } for name, value in settings.items(): monkeypatch.setenv(name, value) captured: dict[str, Any] = {} def client(service: str, **kwargs: Any) -> object: captured.update({"service": service, **kwargs}) return object() monkeypatch.setattr(object_storage.boto3, "client", client) object_storage._client() assert captured["service"] == "s3" assert captured["endpoint_url"] == settings["AWS_ENDPOINT_URL_S3"] assert captured["region_name"] == settings["AWS_REGION"] assert captured["aws_access_key_id"] == settings["AWS_ACCESS_KEY_ID"] assert captured["aws_secret_access_key"] == settings["AWS_SECRET_ACCESS_KEY"] assert captured["config"].signature_version == "s3v4" assert captured["config"].s3["addressing_style"] == "path" def test_missing_storage_configuration_is_actionable( monkeypatch: pytest.MonkeyPatch, ) -> None: """Missing credentials fail before boto3 attempts a request.""" for name in object_storage._REQUIRED_SETTINGS: monkeypatch.delenv(name, raising=False) with pytest.raises( object_storage.ObjectStorageConfigurationError, match="AWS_ACCESS_KEY_ID", ): object_storage._settings() def test_put_and_get_use_documents_bucket(monkeypatch: pytest.MonkeyPatch) -> None: """Original uploads are written to and read from the documents bucket.""" client = _S3Client() monkeypatch.setattr(object_storage, "_client", lambda: client) key = object_storage.put_document_object(8, b"original", "application/pdf") content = object_storage.get_document_object(key) assert key.startswith("8/") assert client.calls[0] == ( "put_object", { "Bucket": "documents", "Key": key, "Body": b"original", "ContentType": "application/pdf", "Metadata": {"doc-id": "8"}, }, ) assert client.calls[1] == ( "get_object", {"Bucket": "documents", "Key": key}, ) assert content == b"stored document" assert client.body.closed is True def test_delete_all_objects_handles_multiple_pages( monkeypatch: pytest.MonkeyPatch, ) -> None: """A reset paginates and deletes every object from the documents bucket.""" class Client: def __init__(self) -> None: self.pages = [ { "Contents": [{"Key": "1/a"}, {"Key": "2/b"}], "IsTruncated": True, "NextContinuationToken": "next", }, {"Contents": [{"Key": "3/c"}], "IsTruncated": False}, ] self.list_requests: list[dict[str, Any]] = [] self.delete_requests: list[dict[str, Any]] = [] def list_objects_v2(self, **kwargs: Any) -> dict[str, Any]: self.list_requests.append(kwargs) return self.pages.pop(0) def delete_objects(self, **kwargs: Any) -> dict[str, Any]: self.delete_requests.append(kwargs) return {} client = Client() monkeypatch.setattr(object_storage, "_client", lambda: client) deleted = object_storage.delete_all_document_objects() assert deleted == 3 assert client.list_requests == [ {"Bucket": "documents", "MaxKeys": 1000}, { "Bucket": "documents", "MaxKeys": 1000, "ContinuationToken": "next", }, ] assert [ item["Key"] for request in client.delete_requests for item in request["Delete"]["Objects"] ] == ["1/a", "2/b", "3/c"]