File size: 5,229 Bytes
0cfdea5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""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"]