File: test_stac_api_io.py

package info (click to toggle)
pystac-client 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,416 kB
  • sloc: python: 4,652; sh: 74; makefile: 60
file content (291 lines) | stat: -rw-r--r-- 9,919 bytes parent folder | download | duplicates (2)
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import typing
from pathlib import Path
from urllib.parse import parse_qs, urlsplit

import pystac
import pytest
from pytest import MonkeyPatch
from requests_mock.mocker import Mocker

from pystac_client.exceptions import APIError
from pystac_client.stac_api_io import StacApiIO

from .helpers import STAC_URLS


class TestSTAC_IOOverride:
    @pytest.mark.vcr
    def test_request_input(self) -> None:
        stac_api_io = StacApiIO()
        response = stac_api_io.read_text(STAC_URLS["PLANETARY-COMPUTER"])
        assert isinstance(response, str)

    @pytest.mark.vcr
    def test_str_input(self) -> None:
        stac_api_io = StacApiIO()
        response = stac_api_io.read_text(STAC_URLS["PLANETARY-COMPUTER"])

        assert isinstance(response, str)

    @pytest.mark.vcr
    def test_http_error(self) -> None:
        stac_api_io = StacApiIO()
        # Attempt to access an authenticated endpoint
        with pytest.raises(APIError) as excinfo:
            stac_api_io.read_text(f"{STAC_URLS['MLHUB']}/search")

        assert isinstance(excinfo.value, APIError)

    def test_local_file(self, tmp_path: Path) -> None:
        stac_api_io = StacApiIO()
        test_file = tmp_path / "test.txt"
        with test_file.open("w") as dst:
            dst.write("Hi there!")

        response = stac_api_io.read_text(str(test_file))

        assert response == "Hi there!"

    def test_conformance_deprecated(self) -> None:
        with pytest.warns(FutureWarning, match="`conformance` option is deprecated"):
            stac_api_io = StacApiIO(conformance=[])
        assert not hasattr(stac_api_io, "conformance")

    def test_custom_headers(self, requests_mock: Mocker) -> None:
        """Checks that headers passed to the init method are added to requests."""
        header_name = "x-my-header"
        header_value = "Some Value"
        url = "https://some-url.com/some-file.json"
        stac_api_io = StacApiIO(headers={header_name: header_value})

        requests_mock.get(url, status_code=200, json={})

        stac_api_io.read_json(url)

        history = requests_mock.request_history
        assert len(history) == 1
        assert header_name in history[0].headers
        assert history[0].headers[header_name] == header_value

    def test_modifier(self, requests_mock: Mocker) -> None:
        """Verify the modifier is correctly called with a returned object."""
        header_name = "x-my-header"
        header_value = "Some Value"
        url = "https://some-url.com/some-file.json"

        def custom_modifier(request: typing.Any) -> typing.Any | None:
            request.headers["x-pirate-name"] = "yellowbeard"
            return request

        stac_api_io = StacApiIO(
            headers={header_name: header_value}, request_modifier=custom_modifier
        )

        requests_mock.get(url, status_code=200, json={})

        stac_api_io.read_json(url)

        history = requests_mock.request_history
        assert len(history) == 1
        assert header_name in history[0].headers
        assert history[0].headers["x-pirate-name"] == "yellowbeard"

    def test_modifier_noreturn(self, requests_mock: Mocker) -> None:
        """Verify the modifier is correctly called when None is returned."""
        header_name = "x-my-header"
        header_value = "Some Value"
        url = "https://some-url.com/some-file.json"

        def custom_modifier(request: typing.Any) -> typing.Any | None:
            request.headers["x-pirate-name"] = "yellowbeard"
            return None

        stac_api_io = StacApiIO(
            headers={header_name: header_value}, request_modifier=custom_modifier
        )

        requests_mock.get(url, status_code=200, json={})

        stac_api_io.read_json(url)

        history = requests_mock.request_history
        assert len(history) == 1
        assert header_name in history[0].headers
        assert history[0].headers["x-pirate-name"] == "yellowbeard"

    def test_custom_query_params(self, requests_mock: Mocker) -> None:
        """Checks that query params passed to the init method are added to requests."""
        init_qp_name = "my-param"
        init_qp_value = "something"
        url = "https://some-url.com/some-file.json"
        stac_api_io = StacApiIO(parameters={init_qp_name: init_qp_value})

        request_qp_name = "another-param"
        request_qp_value = "another_value"
        requests_mock.get(url, status_code=200, json={})

        stac_api_io.read_json(url, parameters={request_qp_name: request_qp_value})

        history = requests_mock.request_history
        assert len(history) == 1

        actual_qs = urlsplit(history[0].url).query
        actual_qp = parse_qs(actual_qs)

        # Check that the param from the init method is present
        assert init_qp_name in actual_qp
        assert len(actual_qp[init_qp_name]) == 1
        assert actual_qp[init_qp_name][0] == init_qp_value

        # Check that the param from the request is present
        assert request_qp_name in actual_qp
        assert len(actual_qp[request_qp_name]) == 1
        assert actual_qp[request_qp_name][0] == request_qp_value

    def test_write(self, tmp_path: Path) -> None:
        stac_api_io = StacApiIO()
        test_file = tmp_path / "test.txt"
        stac_api_io.write_text_to_href(str(test_file), "Hi there!")
        with open(test_file) as file:
            data = file.read()
        assert data == "Hi there!"

    @pytest.mark.parametrize(
        ("attribute", "endpoint"),
        (("features", "search"), ("collections", "collections")),
    )
    def test_stop_on_empty_page(
        self, requests_mock: Mocker, attribute: str, endpoint: str
    ) -> None:
        url = f"https://pystac-client.test/{endpoint}"
        requests_mock.get(
            url,
            status_code=200,
            json={
                attribute: [{"foo": "bar"}],
                "links": [
                    {
                        "rel": "next",
                        "href": url + "?token=baz",
                    }
                ],
            },
        )
        requests_mock.get(
            url + "?token=baz",
            status_code=200,
            json={
                attribute: [],
                "links": [
                    {
                        "rel": "next",
                        "href": url + "?token=bam",
                    }
                ],
            },
        )
        requests_mock.get(
            url + "?token=bam",
            status_code=500,
        )
        stac_api_io = StacApiIO()
        pages = list(stac_api_io.get_pages(url))
        assert len(pages) == 1
        assert pages[0][attribute][0]["foo"] == "bar"

    @pytest.mark.parametrize(
        ("attribute", "endpoint"),
        (("features", "search"), ("collections", "collections")),
    )
    def test_stop_on_attributeless_page(
        self, requests_mock: Mocker, attribute: str, endpoint: str
    ) -> None:
        url = f"https://pystac-client.test/{endpoint}"
        requests_mock.get(
            url,
            status_code=200,
            json={
                attribute: [{"foo": "bar"}],
                "links": [
                    {
                        "rel": "next",
                        "href": url + "?token=baz",
                    }
                ],
            },
        )
        requests_mock.get(
            url + "?token=baz",
            status_code=200,
            json={
                "links": [
                    {
                        "rel": "next",
                        "href": url + "?token=bam",
                    }
                ],
            },
        )
        requests_mock.get(
            url + "?token=bam",
            status_code=500,
        )
        stac_api_io = StacApiIO()
        pages = list(stac_api_io.get_pages(url))
        assert len(pages) == 1
        assert pages[0][attribute][0]["foo"] == "bar"

    @pytest.mark.parametrize(
        ("attribute", "endpoint"),
        (("features", "search"), ("collections", "collections")),
    )
    def test_stop_on_first_empty_page(
        self, requests_mock: Mocker, attribute: str, endpoint: str
    ) -> None:
        url = f"https://pystac-client.test/{endpoint}"
        requests_mock.get(
            url,
            status_code=200,
            json={
                attribute: [],
                "links": [
                    {
                        "rel": "next",
                        "href": url + "?token=bam",
                    }
                ],
            },
        )
        requests_mock.get(url + "?token=bam", status_code=500)
        stac_api_io = StacApiIO()
        pages = list(stac_api_io.get_pages(url))
        assert len(pages) == 0

    @pytest.mark.vcr
    def test_timeout_smoke_test(self) -> None:
        # Testing timeout behavior is hard, so we just have a simple smoke test to make
        # sure that providing a timeout doesn't break anything.
        stac_api_io = StacApiIO(timeout=42)
        response = stac_api_io.read_text(STAC_URLS["PLANETARY-COMPUTER"])
        assert isinstance(response, str)

    @pytest.mark.parametrize("name", ("REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"))
    def test_respect_env_for_certs(self, monkeypatch: MonkeyPatch, name: str) -> None:
        monkeypatch.setenv(name, "/not/a/real/file")
        stac_api_io = StacApiIO()
        with pytest.raises(APIError):
            stac_api_io.request("https://earth-search.aws.element84.com/v1/")


@pytest.mark.vcr
def test_stac_io_in_pystac() -> None:
    # https://github.com/stac-utils/pystac-client/issues/706
    collection = pystac.read_file(
        href="tests/data/planetary-computer-collection.json",
        stac_io=StacApiIO(timeout=42),
    )
    root = collection.get_root()
    assert root
    stac_io = root._stac_io
    assert isinstance(stac_io, StacApiIO)
    assert stac_io.timeout == 42