-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathtest_catalog.py
2026 lines (1700 loc) · 73.9 KB
/
test_catalog.py
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import os
import posixpath
import tempfile
from collections import defaultdict
from collections.abc import Iterator
from copy import deepcopy
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, cast
import pytest
import pystac
from pystac import (
HIERARCHICAL_LINKS,
Asset,
Catalog,
CatalogType,
Collection,
Item,
MediaType,
)
from pystac.errors import STACError
from pystac.layout import (
APILayoutStrategy,
BestPracticesLayoutStrategy,
HrefLayoutStrategy,
TemplateLayoutStrategy,
)
from pystac.utils import (
is_absolute_href,
make_absolute_href,
make_posix_style,
make_relative_href,
)
from tests.utils import (
ARBITRARY_BBOX,
ARBITRARY_EXTENT,
ARBITRARY_GEOM,
MockStacIO,
TestCases,
)
class TestCatalogType:
def test_determine_type_for_absolute_published(self) -> None:
cat = TestCases.case_1()
with tempfile.TemporaryDirectory() as tmp_dir:
cat.normalize_and_save(tmp_dir, catalog_type=CatalogType.ABSOLUTE_PUBLISHED)
cat_json = pystac.StacIO.default().read_json(
os.path.join(tmp_dir, "catalog.json")
)
catalog_type = CatalogType.determine_type(cat_json)
assert catalog_type == CatalogType.ABSOLUTE_PUBLISHED
def test_determine_type_for_relative_published(self) -> None:
cat = TestCases.case_2()
with tempfile.TemporaryDirectory() as tmp_dir:
cat.normalize_and_save(tmp_dir, catalog_type=CatalogType.RELATIVE_PUBLISHED)
cat_json = pystac.StacIO.default().read_json(
os.path.join(tmp_dir, "catalog.json")
)
catalog_type = CatalogType.determine_type(cat_json)
assert catalog_type == CatalogType.RELATIVE_PUBLISHED
def test_determine_type_for_self_contained(self) -> None:
cat_json = pystac.StacIO.default().read_json(
TestCases.get_path("data-files/catalogs/test-case-1/catalog.json")
)
catalog_type = CatalogType.determine_type(cat_json)
assert catalog_type == CatalogType.SELF_CONTAINED
def test_determine_type_for_unknown(self) -> None:
catalog = Catalog(id="test", description="test desc")
subcat = Catalog(id="subcat", description="subcat desc")
catalog.add_child(subcat)
catalog.normalize_hrefs("http://example.com")
d = catalog.to_dict(include_self_link=False)
assert CatalogType.determine_type(d) is None
class TestCatalog:
def test_create_and_read(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
cat_dir = os.path.join(tmp_dir, "catalog")
catalog = TestCases.case_1()
catalog.normalize_and_save(
cat_dir, catalog_type=CatalogType.ABSOLUTE_PUBLISHED
)
read_catalog = Catalog.from_file(f"{cat_dir}/catalog.json")
collections = catalog.get_children()
assert len(list(collections)) == 2
items = read_catalog.get_items(recursive=True)
assert len(list(items)) == 8
def test_from_dict_preserves_dict(self) -> None:
catalog_dict = TestCases.case_1().to_dict()
param_dict = deepcopy(catalog_dict)
# test that the parameter is preserved
_ = Catalog.from_dict(param_dict)
assert param_dict == catalog_dict
# assert that the parameter is not preserved with
# non-default parameter
_ = Catalog.from_dict(param_dict, preserve_dict=False, migrate=False)
assert param_dict != catalog_dict
def test_from_file_bad_catalog(self) -> None:
with pytest.raises(pystac.errors.STACTypeError) as ctx:
_ = Catalog.from_file(TestCases.get_path(TestCases.bad_catalog_case))
assert "(id = broken_cat) does not represent a STACObject" in ctx.value.args[0]
assert "is Catalog" in ctx.value.args[0]
def test_from_dict_set_root(self) -> None:
path = TestCases.get_path("data-files/catalogs/test-case-1/catalog.json")
with open(path) as f:
cat_dict = json.load(f)
root_cat = pystac.Catalog(id="test", description="test desc")
collection = Catalog.from_dict(cat_dict, root=root_cat)
assert collection.get_root() is root_cat
@pytest.mark.vcr()
def test_read_remote(self) -> None:
catalog_url = (
"https://raw.githubusercontent.com/stac-extensions/label/main/"
"examples/multidataset/catalog.json"
)
cat = Catalog.from_file(catalog_url)
zanzibar = cat.get_child("zanzibar-collection")
assert zanzibar is not None
assert len(list(zanzibar.get_items())) == 2
def test_clear_items_removes_from_cache(self) -> None:
catalog = Catalog(id="test", description="test")
subcat = Catalog(id="subcat", description="test")
catalog.add_child(subcat)
item = Item(
id="test-item",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties={"key": "one"},
)
subcat.add_item(item)
items = list(catalog.get_items(recursive=True))
assert len(items) == 1
assert items[0].properties["key"] == "one"
subcat.clear_items()
item = Item(
id="test-item",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties={"key": "two"},
)
subcat.add_item(item)
items = list(catalog.get_items(recursive=True))
assert len(items) == 1
assert items[0].properties["key"] == "two"
subcat.remove_item("test-item")
item = Item(
id="test-item",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties={"key": "three"},
)
subcat.add_item(item)
items = list(catalog.get_items(recursive=True))
assert len(items) == 1
assert items[0].properties["key"] == "three"
def test_clear_children_removes_from_cache(self) -> None:
catalog = Catalog(id="test", description="test")
subcat = Catalog(id="subcat", description="test")
catalog.add_child(subcat)
children = list(catalog.get_children())
assert len(children) == 1
assert children[0].description == "test"
catalog.clear_children()
subcat = Catalog(id="subcat", description="test2")
catalog.add_child(subcat)
children = list(catalog.get_children())
assert len(children) == 1
assert children[0].description == "test2"
catalog.remove_child("subcat")
subcat = Catalog(id="subcat", description="test3")
catalog.add_child(subcat)
children = list(catalog.get_children())
assert len(children) == 1
assert children[0].description == "test3"
def test_clear_children_sets_parent_and_root_to_None(self) -> None:
catalog = Catalog(id="test", description="test")
subcat1 = Catalog(id="subcat", description="test")
subcat2 = Catalog(id="subcat2", description="test2")
catalog.add_children([subcat1, subcat2])
assert subcat1.get_parent() is not None
assert subcat2.get_parent() is not None
assert subcat1.get_root() is not None
assert subcat2.get_root() is not None
children = list(catalog.get_children())
assert len(children) == 2
catalog.clear_children()
assert subcat1.get_parent() is None
assert subcat2.get_parent() is None
assert subcat1.get_root() is None
assert subcat2.get_root() is None
def test_add_child_throws_if_item(self) -> None:
cat = TestCases.case_1()
item = next(cat.get_items(recursive=True))
with pytest.raises(pystac.STACError):
cat.add_child(item) # type:ignore
def test_add_child_returns_link(self) -> None:
parent = Catalog(id="parent", description="test")
child = Catalog(id="child", description="test")
link = parent.add_child(child)
assert isinstance(link, pystac.Link)
link.extra_fields["foo"] = "bar"
link2 = parent.get_single_link("child")
assert link2 is not None
assert link2.extra_fields["foo"] == "bar"
def test_add_children_returns_links(self) -> None:
parent = Catalog(id="parent", description="test")
child1 = Catalog(id="child", description="test")
child2 = Catalog(id="child2", description="test")
links = parent.add_children([child1, child2])
assert isinstance(links, list)
assert len(links) == 2
assert isinstance(links[0], pystac.Link)
assert isinstance(links[1], pystac.Link)
links2 = parent.get_links("child")
assert links[0] in links2
assert links[1] in links2
def test_add_child_override_parent(self) -> None:
parent1 = Catalog(id="parent1", description="test1")
parent2 = Catalog(id="parent2", description="test2")
child = Catalog(id="child", description="test3")
assert child.get_parent() is None
parent1.add_child(child)
assert child.get_parent() is parent1
parent2.add_child(child)
assert child.get_parent() is parent2
def test_add_child_set_parent_false(self) -> None:
parent1 = Catalog(id="parent1", description="test1")
parent2 = Catalog(id="parent2", description="test2")
child = Catalog(id="child", description="test3")
assert child.get_parent() is None
parent1.add_child(child, set_parent=False)
assert child.get_parent() is not parent1
parent1.add_child(child)
parent2.add_child(child, set_parent=False)
assert child.get_parent() is parent1
def test_add_item_override_parent(self) -> None:
parent1 = Catalog(id="parent1", description="test1")
parent2 = Catalog(id="parent2", description="test2")
child = Item(
id="child",
geometry=None,
bbox=None,
datetime=datetime.now(),
properties={},
)
assert child.get_parent() is None
parent1.add_item(child)
assert child.get_parent() is parent1
parent2.add_item(child)
assert child.get_parent() is parent2
def test_add_item_set_parent_false(self) -> None:
parent1 = Catalog(id="parent1", description="test1")
parent2 = Catalog(id="parent2", description="test2")
child = Item(
id="child",
geometry=None,
bbox=None,
datetime=datetime.now(),
properties={},
)
assert child.get_parent() is None
parent1.add_item(child, set_parent=False)
assert child.get_parent() is not parent1
parent1.add_item(child)
parent2.add_item(child, set_parent=False)
assert child.get_parent() is parent1
def test_add_item_throws_if_child(self) -> None:
cat = TestCases.case_1()
child = next(iter(cat.get_children()))
with pytest.raises(pystac.STACError):
cat.add_item(child) # type:ignore
def test_add_item_returns_link(self) -> None:
parent = Catalog(id="parent", description="test")
child = Item(
id="child",
geometry=None,
bbox=None,
datetime=datetime.now(),
properties={},
)
link = parent.add_item(child)
assert isinstance(link, pystac.Link)
link.extra_fields["foo"] = "bar"
link2 = parent.get_single_link("item")
assert link2 is not None
assert link2.extra_fields["foo"] == "bar"
def test_add_items_returns_links(self) -> None:
parent = Catalog(id="parent", description="test")
child1 = Item(
id="child1",
geometry=None,
bbox=None,
datetime=datetime.now(),
properties={},
)
child2 = Item(
id="child2",
geometry=None,
bbox=None,
datetime=datetime.now(),
properties={},
)
links = parent.add_items([child1, child2])
assert isinstance(links, list)
assert len(links) == 2
assert isinstance(links[0], pystac.Link)
assert isinstance(links[1], pystac.Link)
links2 = parent.get_links("item")
assert links[0] in links2
assert links[1] in links2
def test_get_child_returns_none_if_not_found(self) -> None:
cat = TestCases.case_1()
child = cat.get_child("thisshouldnotbeachildid", recursive=True)
assert child is None
def test_get_item_is_deprecated_but_still_works(self) -> None:
cat = TestCases.case_1()
with pytest.warns(DeprecationWarning):
item = cat.get_item("area-2-1-imagery", recursive=True)
assert item is not None
def test_get_item_returns_none_if_not_found(self) -> None:
cat = TestCases.case_1()
with pytest.warns(DeprecationWarning):
item = cat.get_item("thisshouldnotbeanitemid", recursive=True)
assert item is None
def test_get_all_items_is_deprecated_but_still_works(self) -> None:
cat = TestCases.case_1()
with pytest.warns(DeprecationWarning):
all_items = cat.get_all_items()
items = cat.get_items(recursive=True)
assert all(a == i for a, i in zip(all_items, items))
def test_get_items_returns_empty_generator_if_not_found(self) -> None:
cat = TestCases.case_1()
items = cat.get_items("thisshouldnotbeanitemid", recursive=True)
assert next(items, None) is None
def test_sets_catalog_type(self) -> None:
cat = TestCases.case_1()
assert cat.catalog_type == CatalogType.SELF_CONTAINED
@pytest.mark.parametrize("catalog", TestCases.all_test_catalogs())
def test_walk_iterates_correctly(self, catalog: Catalog) -> None:
def test_catalog(cat: Catalog) -> None:
expected_catalog_iterations = 1
actual_catalog_iterations = 0
for root, children, items in cat.walk():
actual_catalog_iterations += 1
expected_catalog_iterations += len(list(root.get_children()))
assert {c.id for c in root.get_children()} == {
c.id for c in children
}, "Children unequal"
assert {c.id for c in root.get_items()} == {c.id for c in items}, (
"Items unequal"
)
assert actual_catalog_iterations == expected_catalog_iterations
test_catalog(catalog)
@pytest.mark.parametrize("catalog", TestCases.all_test_catalogs())
def test_clone_generates_correct_links(self, catalog: Catalog) -> None:
expected_link_types_to_counts: Any = {}
actual_link_types_to_counts: Any = {}
for root, _, items in catalog.walk():
expected_link_types_to_counts[root.id] = defaultdict(int)
actual_link_types_to_counts[root.id] = defaultdict(int)
for link in root.get_links():
expected_link_types_to_counts[root.id][link.rel] += 1
for link in root.clone().get_links():
actual_link_types_to_counts[root.id][link.rel] += 1
for item in items:
expected_link_types_to_counts[item.id] = defaultdict(int)
actual_link_types_to_counts[item.id] = defaultdict(int)
for link in item.get_links():
expected_link_types_to_counts[item.id][link.rel] += 1
for link in item.get_links():
actual_link_types_to_counts[item.id][link.rel] += 1
assert set(expected_link_types_to_counts.keys()) == set(
actual_link_types_to_counts.keys()
)
for obj_id in actual_link_types_to_counts:
expected_counts = expected_link_types_to_counts[obj_id]
actual_counts = actual_link_types_to_counts[obj_id]
assert set(expected_counts.keys()) == set(actual_counts.keys())
for rel in expected_counts:
assert actual_counts[rel] == expected_counts[rel], (
"Clone of {} has {} {} links, original has {}".format(
obj_id, actual_counts[rel], rel, expected_counts[rel]
)
)
def test_save_uses_previous_catalog_type(self) -> None:
catalog = TestCases.case_1()
assert catalog.catalog_type == CatalogType.SELF_CONTAINED
with tempfile.TemporaryDirectory() as tmp_dir:
catalog.normalize_hrefs(tmp_dir)
href = catalog.self_href
catalog.save()
cat2 = pystac.Catalog.from_file(href)
assert cat2.catalog_type == CatalogType.SELF_CONTAINED
def test_save_to_provided_href(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.case_1()
href = "https://stac.test"
folder = os.path.join(tmp_dir, "cat")
catalog.normalize_hrefs(href)
catalog.save(catalog_type=CatalogType.ABSOLUTE_PUBLISHED, dest_href=folder)
catalog_path = os.path.join(folder, "catalog.json")
assert os.path.exists(catalog_path)
result_cat = Catalog.from_file(catalog_path)
for link in result_cat.get_child_links():
assert cast(str, link.target).startswith(href)
def test_save_relative_published_no_self_links(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.case_1()
href = "https://stac.test"
folder = os.path.join(tmp_dir, "cat")
catalog.normalize_hrefs(href)
catalog.save(catalog_type=CatalogType.RELATIVE_PUBLISHED, dest_href=folder)
catalog_path = os.path.join(folder, "catalog.json")
assert os.path.exists(catalog_path)
result_cat = Catalog.from_file(catalog_path)
# Check that Items do not have a self link
# Since Item.from_dict automatically adds a self link, we need to look at
# the JSON files themselves.
stac_io = pystac.StacIO.default()
for current_cat, _, __ in result_cat.walk():
for item_link in current_cat.get_item_links():
item_dict = stac_io.read_json(item_link)
self_link = next(
(
link
for link in item_dict.get("links", [])
if link["rel"] == "self"
),
None,
)
assert self_link is None
def test_save_with_different_stac_io(self) -> None:
catalog = Catalog.from_file(
TestCases.get_path("data-files/catalogs/test-case-1/catalog.json")
)
stac_io = MockStacIO()
with tempfile.TemporaryDirectory() as tmp_dir:
catalog.normalize_hrefs(tmp_dir)
catalog.save(
catalog_type=CatalogType.ABSOLUTE_PUBLISHED,
dest_href=tmp_dir,
stac_io=stac_io,
)
hrefs = []
for root, _, items in catalog.walk():
hrefs.append(root.get_self_href())
for item in items:
hrefs.append(item.get_self_href())
assert len(hrefs) == stac_io.mock.write_text.call_count
for call_args_list in stac_io.mock.write_text.call_args_list:
assert call_args_list[0][0] in hrefs
def test_subcatalogs_saved_to_correct_path(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.case_1()
href = "https://stac.test"
catalog.normalize_hrefs(href)
catalog.save(catalog_type=CatalogType.ABSOLUTE_PUBLISHED, dest_href=tmp_dir)
# Check the root catalog path
expected_root_catalog_path = os.path.join(tmp_dir, "catalog.json")
assert os.path.exists(expected_root_catalog_path), (
f"{expected_root_catalog_path} does not exist."
)
assert os.path.isfile(expected_root_catalog_path), (
f"{expected_root_catalog_path} is not a file."
)
# Check each child catalog
for child_catalog in catalog.get_children():
relative_path = make_relative_href(
child_catalog.self_href, catalog.self_href, start_is_dir=False
)
expected_child_path = make_absolute_href(
relative_path,
expected_root_catalog_path,
start_is_dir=False,
)
assert os.path.exists(expected_child_path), (
f"{expected_child_path} does not exist."
)
assert os.path.isfile(expected_child_path), (
f"{expected_child_path} is not a file."
)
# Check each item
for item in catalog.get_items(recursive=True):
relative_path = make_relative_href(
item.self_href, catalog.self_href, start_is_dir=False
)
expected_item_path = make_absolute_href(
relative_path,
expected_root_catalog_path,
start_is_dir=False,
)
assert os.path.exists(expected_item_path), (
f"{expected_item_path} does not exist."
)
assert os.path.isfile(expected_item_path), (
f"{expected_item_path} is not a file."
)
def test_clone_uses_previous_catalog_type(self) -> None:
catalog = TestCases.case_1()
assert catalog.catalog_type == CatalogType.SELF_CONTAINED
clone = catalog.clone()
assert clone.catalog_type == CatalogType.SELF_CONTAINED
def test_normalize_hrefs_sets_all_hrefs(self) -> None:
catalog = TestCases.case_1()
catalog.normalize_hrefs("http://example.com")
for root, _, items in catalog.walk():
self_href = root.get_self_href()
assert self_href is not None
assert self_href.startswith("http://example.com")
for link in root.links:
if link.is_resolved():
target_href = cast(pystac.STACObject, link.target).self_href
else:
target_href = link.absolute_href
assert "http://example.com" in target_href, (
'[{}] {} does not contain "{}"'.format(
link.rel, target_href, "http://example.com"
)
)
for item in items:
assert "http://example.com" in item.self_href
def test_normalize_hrefs_makes_absolute_href(self) -> None:
catalog = TestCases.case_1()
catalog.normalize_hrefs("./relativepath")
abspath = make_posix_style(os.path.abspath("./relativepath"))
self_href = catalog.get_self_href()
assert self_href is not None
assert self_href.startswith(abspath)
def test_normalize_hrefs_skip_unresolved(self) -> None:
catalog = TestCases.case_1()
catalog.normalize_hrefs("http://example.com", skip_unresolved=True)
assert catalog.self_href.startswith("http://example.com")
for link in catalog.links:
if link.rel == "child" or link.rel == "item":
assert not link.is_resolved()
item = Item(
"an-id",
geometry=None,
bbox=None,
datetime=datetime.now(),
properties={},
)
catalog.add_item(item, title="This is the test item")
catalog.normalize_hrefs("http://example.com", skip_unresolved=True)
for link in catalog.links:
if link.title == "This is the test item":
assert link.is_resolved()
assert isinstance(link.target, pystac.STACObject)
assert link.target.self_href.startswith("http://example.com")
elif link.rel == "child" or link.rel == "item":
assert not link.is_resolved()
def test_save_unresolved(self) -> None:
catalog = Catalog("an-id", "a description")
item = Item(
"an-id",
geometry=None,
bbox=None,
datetime=datetime.now(),
properties={},
)
catalog.add_item(item)
catalog.add_link(pystac.Link("child", "/not/a/real/path/catalog.json"))
with tempfile.TemporaryDirectory() as temporary_directory:
catalog.set_self_href(os.path.join(temporary_directory, "catalog.json"))
item.set_self_href(os.path.join(temporary_directory, "item.json"))
catalog.save()
assert len(os.listdir(temporary_directory)) == 2
with tempfile.TemporaryDirectory() as temporary_directory:
catalog.normalize_and_save(temporary_directory, skip_unresolved=True)
assert len(os.listdir(temporary_directory)) == 2
with tempfile.TemporaryDirectory() as temporary_directory:
with pytest.raises(STACError, match="does not resolve to a STAC object"):
catalog.normalize_and_save(temporary_directory, skip_unresolved=False)
def test_generate_subcatalogs_works_with_custom_properties(self) -> None:
catalog = TestCases.case_8()
defaults = {"pl:item_type": "PlanetScope"}
catalog.generate_subcatalogs(
"${year}/${month}/${pl:item_type}", defaults=defaults
)
month_cat = catalog.get_child("8", recursive=True)
assert month_cat is not None
type_cats = {cat.id for cat in month_cat.get_children()}
assert type_cats == {"PSScene4Band", "SkySatScene", "PlanetScope"}
def test_generate_subcatalogs_does_not_change_item_count(self) -> None:
catalog = TestCases.case_7()
item_counts = {
cat.id: len(list(cat.get_items(recursive=True)))
for cat in catalog.get_children()
}
catalog.generate_subcatalogs("${year}/${day}")
with tempfile.TemporaryDirectory() as tmp_dir:
catalog.normalize_hrefs(tmp_dir)
catalog.save(pystac.CatalogType.SELF_CONTAINED)
cat2 = pystac.Catalog.from_file(os.path.join(tmp_dir, "catalog.json"))
for child in cat2.get_children():
actual = len(list(child.get_items(recursive=True)))
expected = item_counts[child.id]
assert actual == expected, f" for child '{child.id}'"
def test_generate_subcatalogs_merge_template_elements(self) -> None:
catalog = Catalog(id="test", description="Test")
item_properties = [
dict(property1=p1, property2=p2) for p1 in ("A", "B") for p2 in (1, 2)
]
for ni, properties in enumerate(item_properties):
catalog.add_item(
Item(
id=f"item{ni}",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties=properties,
)
)
result = catalog.generate_subcatalogs("${property1}_${property2}")
actual_subcats = {cat.id for cat in result}
expected_subcats = {
"{}_{}".format(d["property1"], d["property2"]) for d in item_properties
}
assert len(result) == len(expected_subcats)
assert actual_subcats == expected_subcats
def test_generate_subcatalogs_can_be_applied_multiple_times(self) -> None:
catalog = TestCases.case_8()
_ = catalog.generate_subcatalogs("${year}/${month}")
catalog.normalize_hrefs("/tmp")
expected_hrefs = {
item.id: item.get_self_href() for item in catalog.get_items(recursive=True)
}
result = catalog.generate_subcatalogs("${year}/${month}")
assert len(result) == 0
catalog.normalize_hrefs("/tmp")
for item in catalog.get_items(recursive=True):
assert item.get_self_href() == expected_hrefs[item.id], (
f" for item '{item.id}'"
)
def test_generate_subcatalogs_works_after_adding_more_items(self) -> None:
catalog = Catalog(id="test", description="Test")
properties = dict(property1="A", property2=1)
catalog.add_item(
Item(
id="item1",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties=properties,
)
)
catalog.generate_subcatalogs("${property1}/${property2}")
catalog.add_item(
Item(
id="item2",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties=properties,
)
)
catalog.generate_subcatalogs("${property1}/${property2}")
catalog.normalize_hrefs("/tmp")
item1 = next(catalog.get_items("item1", recursive=True))
item1_parent = item1.get_parent()
assert item1_parent is not None
item2 = next(catalog.get_items("item2", recursive=True))
item2_parent = item2.get_parent()
assert item2_parent is not None
assert item1_parent.get_self_href() == item2_parent.get_self_href()
def test_generate_subcatalogs_works_for_branched_subcatalogs(self) -> None:
catalog = Catalog(id="test", description="Test")
item_properties = [
dict(property1="A", property2=1, property3="i"), # add 3 subcats
dict(property1="A", property2=1, property3="j"), # add 1 more
dict(property1="A", property2=2, property3="i"), # add 2 more
dict(property1="B", property2=1, property3="i"), # add 3 more
]
for ni, properties in enumerate(item_properties):
catalog.add_item(
Item(
id=f"item{ni}",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties=properties,
)
)
result = catalog.generate_subcatalogs("${property1}/${property2}/${property3}")
assert len(result) == 9
actual_subcats = {cat.id for cat in result}
expected_subcats = {"A", "B", "1", "2", "i", "j"}
assert actual_subcats == expected_subcats
def test_generate_subcatalogs_works_for_subcatalogs_with_same_ids(self) -> None:
catalog = Catalog(id="test", description="Test")
item_properties = [
dict(property1=1, property2=1), # add 2 subcats
dict(property1=1, property2=2), # add 1 more
dict(property1=2, property2=1), # add 2 more
dict(property1=2, property2=2), # add 1 more
]
for ni, properties in enumerate(item_properties):
catalog.add_item(
Item(
id=f"item{ni}",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties=properties,
)
)
result = catalog.generate_subcatalogs("${property1}/${property2}")
assert len(result) == 6
catalog.normalize_hrefs("/")
for item in catalog.get_items(recursive=True):
item_parent = item.get_parent()
assert item_parent is not None
parent_href = item_parent.self_href
path_to_parent, _ = os.path.split(parent_href)
subcats = list(
Path(path_to_parent).parts[1:]
) # Skip drive letter if present (Windows)
assert len(subcats) == 2, f" for item '{item.id}'"
def test_map_items(self) -> None:
def item_mapper(item: pystac.Item) -> pystac.Item:
item.properties["ITEM_MAPPER"] = "YEP"
return item
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.case_1()
new_cat = catalog.map_items(item_mapper)
new_cat.normalize_hrefs(os.path.join(tmp_dir, "cat"))
new_cat.save(catalog_type=CatalogType.ABSOLUTE_PUBLISHED)
result_cat = Catalog.from_file(os.path.join(tmp_dir, "cat", "catalog.json"))
for item in result_cat.get_items(recursive=True):
assert "ITEM_MAPPER" in item.properties
for item in catalog.get_items(recursive=True):
assert "ITEM_MAPPER" not in item.properties
def test_map_items_multiple(self) -> None:
def item_mapper(item: pystac.Item) -> list[pystac.Item]:
item2 = item.clone()
item2.id = item2.id + "_2"
item.properties["ITEM_MAPPER_1"] = "YEP"
item2.properties["ITEM_MAPPER_2"] = "YEP"
return [item, item2]
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.case_1()
catalog_items = list(catalog.get_items(recursive=True))
new_cat = catalog.map_items(item_mapper)
new_cat.normalize_hrefs(os.path.join(tmp_dir, "cat"))
new_cat.save(catalog_type=CatalogType.ABSOLUTE_PUBLISHED)
result_cat = Catalog.from_file(os.path.join(tmp_dir, "cat", "catalog.json"))
result_items = list(result_cat.get_items(recursive=True))
assert len(catalog_items) * 2 == len(result_items)
ones, twos = 0, 0
for item in result_items:
assert ("ITEM_MAPPER_1" in item.properties) or (
"ITEM_MAPPER_2" in item.properties
)
if "ITEM_MAPPER_1" in item.properties:
ones += 1
if "ITEM_MAPPER_2" in item.properties:
twos += 1
assert ones == twos
for item in catalog.get_items(recursive=True):
assert ("ITEM_MAPPER_1" not in item.properties) and (
"ITEM_MAPPER_2" not in item.properties
)
def test_map_items_multiple_2(self) -> None:
catalog = Catalog(id="test-1", description="Test1")
item1 = Item(
id="item1",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties={},
)
item1.add_asset("ortho", Asset(href="/some/ortho.tif"))
catalog.add_item(item1)
kitten = Catalog(id="test-kitten", description="A cuter version of catalog")
catalog.add_child(kitten)
item2 = Item(
id="item2",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.now(timezone.utc),
properties={},
)
item2.add_asset("ortho", Asset(href="/some/other/ortho.tif"))
kitten.add_item(item2)
def modify_item_title(item: pystac.Item) -> pystac.Item:
item.properties["title"] = "Some title"
return item
def duplicate_item(item: pystac.Item) -> list[pystac.Item]:
duplicated_item = item.clone()
duplicated_item.id += "-duplicated"
return [item, duplicated_item]
c = catalog.map_items(modify_item_title)
c = c.map_items(duplicate_item)
new_catalog = c
items = new_catalog.get_items(recursive=True)
assert len(list(items)) == 4
def test_map_assets_single(self) -> None:
changed_asset = "d43bead8-e3f8-4c51-95d6-e24e750a402b"
def asset_mapper(key: str, asset: pystac.Asset) -> pystac.Asset:
if key == changed_asset:
asset.title = "NEW TITLE"
return asset
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.case_2()
new_cat = catalog.map_assets(asset_mapper)
new_cat.normalize_hrefs(os.path.join(tmp_dir, "cat"))
new_cat.save(catalog_type=CatalogType.ABSOLUTE_PUBLISHED)
result_cat = Catalog.from_file(os.path.join(tmp_dir, "cat", "catalog.json"))
found = False
for item in result_cat.get_items(recursive=True):
for key, asset in item.assets.items():
if key == changed_asset:
found = True
assert asset.title == "NEW TITLE"
else:
assert asset.title != "NEW TITLE"
assert found
def test_map_assets_tup(self) -> None:
changed_assets: list[str] = []
def asset_mapper(
key: str, asset: pystac.Asset
) -> pystac.Asset | tuple[str, pystac.Asset]:
if asset.media_type and "geotiff" in asset.media_type:
asset.title = "NEW TITLE"
changed_assets.append(key)
return (f"{key}-modified", asset)
else:
return asset
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.case_2()
new_cat = catalog.map_assets(asset_mapper)
new_cat.normalize_hrefs(os.path.join(tmp_dir, "cat"))
new_cat.save(catalog_type=CatalogType.ABSOLUTE_PUBLISHED)
result_cat = Catalog.from_file(os.path.join(tmp_dir, "cat", "catalog.json"))
found = False