File: test_timestamps.py

package info (click to toggle)
pystac 1.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 19,904 kB
  • sloc: python: 24,370; makefile: 124; sh: 7
file content (333 lines) | stat: -rw-r--r-- 10,865 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import json
from datetime import datetime

import pytest

import pystac
from pystac import Collection, ExtensionTypeError, Item
from pystac.extensions.timestamps import TimestampsExtension
from pystac.summaries import RangeSummary
from pystac.utils import datetime_to_str, get_opt, str_to_datetime
from tests.utils import TestCases, assert_to_from_dict

EXAMPLE_URI = TestCases.get_path("data-files/timestamps/example-landsat8.json")
SAMPLE_DATETIME_STR = "2020-01-01T00:00:00Z"


@pytest.fixture
def item() -> Item:
    return Item.from_file(EXAMPLE_URI)


@pytest.fixture
def sample_datetime() -> datetime:
    return str_to_datetime(SAMPLE_DATETIME_STR)


def test_to_from_dict() -> None:
    with open(EXAMPLE_URI) as f:
        item_dict = json.load(f)
    assert_to_from_dict(pystac.Item, item_dict)


def test_apply() -> None:
    item = next(TestCases.case_2().get_items(recursive=True))
    assert not TimestampsExtension.has_extension(item)

    TimestampsExtension.add_to(item)
    assert TimestampsExtension.has_extension(item)
    TimestampsExtension.ext(item).apply(
        published=str_to_datetime("2020-01-03T06:45:55Z"),
        expires=str_to_datetime("2020-02-03T06:45:55Z"),
        unpublished=str_to_datetime("2020-03-03T06:45:55Z"),
    )

    for d in [
        TimestampsExtension.ext(item).published,
        TimestampsExtension.ext(item).expires,
        TimestampsExtension.ext(item).unpublished,
    ]:
        assert isinstance(d, datetime)

    for p in ("published", "expires", "unpublished"):
        assert isinstance(item.properties[p], str)

    published_str = "2020-04-03T06:45:55Z"
    TimestampsExtension.ext(item).apply(published=str_to_datetime(published_str))
    assert isinstance(TimestampsExtension.ext(item).published, datetime)
    assert item.properties["published"] == published_str

    for d in [
        TimestampsExtension.ext(item).expires,
        TimestampsExtension.ext(item).unpublished,
    ]:
        assert d is None

    for p in ("expires", "unpublished"):
        assert p not in item.properties


@pytest.mark.vcr()
def test_validate_timestamps(item: Item) -> None:
    item.validate()


@pytest.mark.vcr()
def test_expires(item: Item, sample_datetime: datetime) -> None:
    # Get
    assert "expires" in item.properties
    timestamps_expires = TimestampsExtension.ext(item).expires
    assert isinstance(timestamps_expires, datetime)
    assert datetime_to_str(get_opt(timestamps_expires)) == item.properties["expires"]

    # Set
    TimestampsExtension.ext(item).expires = sample_datetime
    assert SAMPLE_DATETIME_STR == item.properties["expires"]

    # Get from Asset
    asset_no_prop = item.assets["red"]
    asset_prop = item.assets["blue"]
    assert (
        TimestampsExtension.ext(asset_no_prop).expires
        == TimestampsExtension.ext(item).expires
    )
    assert TimestampsExtension.ext(asset_prop).expires == str_to_datetime(
        "2018-12-02T00:00:00Z"
    )

    # # Set to Asset
    asset_value = str_to_datetime("2019-02-02T00:00:00Z")
    TimestampsExtension.ext(asset_no_prop).expires = asset_value
    assert (
        TimestampsExtension.ext(asset_no_prop).expires
        != TimestampsExtension.ext(item).expires
    )
    assert TimestampsExtension.ext(asset_no_prop).expires == asset_value

    # Validate
    item.validate()


@pytest.mark.vcr()
def test_published(item: Item, sample_datetime: datetime) -> None:
    # Get
    assert "published" in item.properties
    timestamps_published = TimestampsExtension.ext(item).published
    assert isinstance(timestamps_published, datetime)
    assert (
        datetime_to_str(get_opt(timestamps_published)) == item.properties["published"]
    )

    # Set
    TimestampsExtension.ext(item).published = sample_datetime
    assert SAMPLE_DATETIME_STR == item.properties["published"]

    # Get from Asset
    asset_no_prop = item.assets["red"]
    asset_prop = item.assets["blue"]
    assert (
        TimestampsExtension.ext(asset_no_prop).published
        == TimestampsExtension.ext(item).published
    )
    assert TimestampsExtension.ext(asset_prop).published == str_to_datetime(
        "2018-11-02T00:00:00Z"
    )

    # # Set to Asset
    asset_value = str_to_datetime("2019-02-02T00:00:00Z")
    TimestampsExtension.ext(asset_no_prop).published = asset_value
    assert (
        TimestampsExtension.ext(asset_no_prop).published
        != TimestampsExtension.ext(item).published
    )
    assert TimestampsExtension.ext(asset_no_prop).published == asset_value

    # Validate
    item.validate()


@pytest.mark.vcr()
def test_unpublished(item: Item, sample_datetime: datetime) -> None:
    # Get
    assert "unpublished" not in item.properties
    timestamps_unpublished = TimestampsExtension.ext(item).unpublished
    assert timestamps_unpublished is None

    # Set
    TimestampsExtension.ext(item).unpublished = sample_datetime
    assert SAMPLE_DATETIME_STR == item.properties["unpublished"]

    # Get from Asset
    asset_no_prop = item.assets["red"]
    asset_prop = item.assets["blue"]
    assert (
        TimestampsExtension.ext(asset_no_prop).unpublished
        == TimestampsExtension.ext(item).unpublished
    )
    assert TimestampsExtension.ext(asset_prop).unpublished == str_to_datetime(
        "2019-01-02T00:00:00Z"
    )

    # Set to Asset
    asset_value = str_to_datetime("2019-02-02T00:00:00Z")
    TimestampsExtension.ext(asset_no_prop).unpublished = asset_value
    assert (
        TimestampsExtension.ext(asset_no_prop).unpublished
        != TimestampsExtension.ext(item).unpublished
    )
    assert TimestampsExtension.ext(asset_no_prop).unpublished == asset_value

    # Validate
    item.validate()


def test_extension_not_implemented(item: Item) -> None:
    # Should raise exception if Item does not include extension URI
    item.stac_extensions.remove(TimestampsExtension.get_schema_uri())

    with pytest.raises(pystac.ExtensionNotImplemented):
        _ = TimestampsExtension.ext(item)

    # Should raise exception if owning Item does not include extension URI
    asset = item.assets["blue"]

    with pytest.raises(pystac.ExtensionNotImplemented):
        _ = TimestampsExtension.ext(asset)

    # Should succeed if Asset has no owner
    ownerless_asset = pystac.Asset.from_dict(asset.to_dict())
    _ = TimestampsExtension.ext(ownerless_asset)


def test_item_ext_add_to(item: Item) -> None:
    item.stac_extensions.remove(TimestampsExtension.get_schema_uri())
    assert TimestampsExtension.get_schema_uri() not in item.stac_extensions

    _ = TimestampsExtension.ext(item, add_if_missing=True)

    assert TimestampsExtension.get_schema_uri() in item.stac_extensions


def test_asset_ext_add_to(item: Item) -> None:
    item.stac_extensions.remove(TimestampsExtension.get_schema_uri())
    assert TimestampsExtension.get_schema_uri() not in item.stac_extensions
    asset = item.assets["blue"]

    _ = TimestampsExtension.ext(asset, add_if_missing=True)

    assert TimestampsExtension.get_schema_uri() in item.stac_extensions


def test_should_raise_exception_when_passing_invalid_extension_object() -> None:
    with pytest.raises(
        ExtensionTypeError,
        match=r"^TimestampsExtension does not apply to type 'object'$",
    ):
        # calling it wrong on purpose --------------v
        TimestampsExtension.ext(object())  # type: ignore


def test_item_repr(item: Item) -> None:
    assert (
        TimestampsExtension.ext(item).__repr__()
        == f"<ItemTimestampsExtension Item id={item.id}>"
    )


def test_asset_repr(item: Item) -> None:
    asset = item.assets["blue"]
    assert (
        TimestampsExtension.ext(asset).__repr__()
        == f"<AssetTimestampsExtension Asset href={asset.href}>"
    )


def test_summaries_published(multi_extent_collection: Collection) -> None:
    summaries_ext = TimestampsExtension.summaries(multi_extent_collection, True)
    published_range = RangeSummary(
        str_to_datetime("2020-01-01T00:00:00.000Z"),
        str_to_datetime("2020-01-02T00:00:00.000Z"),
    )

    summaries_ext.published = published_range

    assert summaries_ext.published == published_range

    summaries_dict = multi_extent_collection.to_dict()["summaries"]

    assert summaries_dict["published"] == {
        "minimum": datetime_to_str(published_range.minimum),
        "maximum": datetime_to_str(published_range.maximum),
    }


def test_summaries_expires(multi_extent_collection: Collection) -> None:
    summaries_ext = TimestampsExtension.summaries(multi_extent_collection, True)
    expires_range = RangeSummary(
        str_to_datetime("2020-01-01T00:00:00.000Z"),
        str_to_datetime("2020-01-02T00:00:00.000Z"),
    )

    summaries_ext.expires = expires_range

    assert summaries_ext.expires == expires_range

    summaries_dict = multi_extent_collection.to_dict()["summaries"]

    assert summaries_dict["expires"] == {
        "minimum": datetime_to_str(expires_range.minimum),
        "maximum": datetime_to_str(expires_range.maximum),
    }


def test_summaries_unpublished(multi_extent_collection: Collection) -> None:
    summaries_ext = TimestampsExtension.summaries(multi_extent_collection, True)
    unpublished_range = RangeSummary(
        str_to_datetime("2020-01-01T00:00:00.000Z"),
        str_to_datetime("2020-01-02T00:00:00.000Z"),
    )

    summaries_ext.unpublished = unpublished_range

    assert summaries_ext.unpublished == unpublished_range

    summaries_dict = multi_extent_collection.to_dict()["summaries"]

    assert summaries_dict["unpublished"] == {
        "minimum": datetime_to_str(unpublished_range.minimum),
        "maximum": datetime_to_str(unpublished_range.maximum),
    }


def test_summaries_adds_uri(multi_extent_collection: Collection) -> None:
    multi_extent_collection.stac_extensions = []
    with pytest.raises(
        pystac.ExtensionNotImplemented,
        match="Extension 'timestamps' is not implemented",
    ):
        TimestampsExtension.summaries(multi_extent_collection, add_if_missing=False)

    _ = TimestampsExtension.summaries(multi_extent_collection, True)

    assert (
        TimestampsExtension.get_schema_uri() in multi_extent_collection.stac_extensions
    )

    TimestampsExtension.remove_from(multi_extent_collection)
    assert (
        TimestampsExtension.get_schema_uri()
        not in multi_extent_collection.stac_extensions
    )


@pytest.mark.parametrize(
    "schema_uri",
    ("https://stac-extensions.github.io/timestamps/v1.0.0/schema.json",),
)
def test_migrate(schema_uri: str, item: Item) -> None:
    item_dict = item.to_dict(include_self_link=False, transform_hrefs=False)
    item_dict["stac_extensions"] = [schema_uri]
    item = Item.from_dict(item_dict, migrate=True)
    assert item.stac_extensions == [
        "https://stac-extensions.github.io/timestamps/v1.1.0/schema.json"
    ]