forked from stac-utils/pystac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_catalog.py
1422 lines (1183 loc) · 54.6 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 copy import deepcopy
import os
import json
import tempfile
from typing import Any, Dict, List, Tuple, Union, cast
import unittest
from datetime import datetime
from collections import defaultdict
import pystac
from pystac import (
Catalog,
Collection,
CatalogType,
Item,
Asset,
MediaType,
HIERARCHICAL_LINKS,
)
from pystac.extensions.label import LabelClasses, LabelExtension, LabelType
from pystac.utils import (
is_absolute_href,
join_path_or_url,
JoinType,
make_absolute_href,
make_relative_href,
)
from tests.utils import (
TestCases,
ARBITRARY_GEOM,
ARBITRARY_BBOX,
MockStacIO,
)
class CatalogTypeTest(unittest.TestCase):
def test_determine_type_for_absolute_published(self) -> None:
cat = TestCases.test_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)
self.assertEqual(catalog_type, CatalogType.ABSOLUTE_PUBLISHED)
def test_determine_type_for_relative_published(self) -> None:
cat = TestCases.test_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)
self.assertEqual(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)
self.assertEqual(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)
self.assertIsNone(CatalogType.determine_type(d))
class CatalogTest(unittest.TestCase):
def test_create_and_read(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
cat_dir = os.path.join(tmp_dir, "catalog")
catalog = TestCases.test_case_1()
catalog.normalize_and_save(
cat_dir, catalog_type=CatalogType.ABSOLUTE_PUBLISHED
)
read_catalog = Catalog.from_file("{}/catalog.json".format(cat_dir))
collections = catalog.get_children()
self.assertEqual(len(list(collections)), 2)
items = read_catalog.get_all_items()
self.assertEqual(len(list(items)), 8)
def test_from_dict_preserves_dict(self) -> None:
catalog_dict = TestCases.test_case_1().to_dict()
param_dict = deepcopy(catalog_dict)
# test that the parameter is preserved
_ = Catalog.from_dict(param_dict)
self.assertEqual(param_dict, catalog_dict)
# assert that the parameter is not preserved with
# non-default parameter
_ = Catalog.from_dict(param_dict, preserve_dict=False)
self.assertNotEqual(param_dict, catalog_dict)
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)
self.assertIs(collection.get_root(), root_cat)
def test_read_remote(self) -> None:
# TODO: Move this URL to the main stac-spec repo once the example JSON is fixed.
catalog_url = (
"https://raw.githubusercontent.com/lossyrob/stac-spec/"
"0.9.0/pystac-upgrade-fixes"
"/extensions/label/examples/multidataset/catalog.json"
)
cat = Catalog.from_file(catalog_url)
zanzibar = cat.get_child("zanzibar-collection")
assert zanzibar is not None
self.assertEqual(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.utcnow(),
properties={"key": "one"},
)
subcat.add_item(item)
items = list(catalog.get_all_items())
self.assertEqual(len(items), 1)
self.assertEqual(items[0].properties["key"], "one")
subcat.clear_items()
item = Item(
id="test-item",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.utcnow(),
properties={"key": "two"},
)
subcat.add_item(item)
items = list(catalog.get_all_items())
self.assertEqual(len(items), 1)
self.assertEqual(items[0].properties["key"], "two")
subcat.remove_item("test-item")
item = Item(
id="test-item",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.utcnow(),
properties={"key": "three"},
)
subcat.add_item(item)
items = list(catalog.get_all_items())
self.assertEqual(len(items), 1)
self.assertEqual(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())
self.assertEqual(len(children), 1)
self.assertEqual(children[0].description, "test")
catalog.clear_children()
subcat = Catalog(id="subcat", description="test2")
catalog.add_child(subcat)
children = list(catalog.get_children())
self.assertEqual(len(children), 1)
self.assertEqual(children[0].description, "test2")
catalog.remove_child("subcat")
subcat = Catalog(id="subcat", description="test3")
catalog.add_child(subcat)
children = list(catalog.get_children())
self.assertEqual(len(children), 1)
self.assertEqual(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])
self.assertIsNotNone(subcat1.get_parent())
self.assertIsNotNone(subcat2.get_parent())
self.assertIsNotNone(subcat1.get_root())
self.assertIsNotNone(subcat2.get_root())
children = list(catalog.get_children())
self.assertEqual(len(children), 2)
catalog.clear_children()
self.assertIsNone(subcat1.get_parent())
self.assertIsNone(subcat2.get_parent())
self.assertIsNone(subcat1.get_root())
self.assertIsNone(subcat2.get_root())
def test_add_child_throws_if_item(self) -> None:
cat = TestCases.test_case_1()
item = next(iter(cat.get_all_items()))
with self.assertRaises(pystac.STACError):
cat.add_child(item) # type:ignore
def test_add_item_throws_if_child(self) -> None:
cat = TestCases.test_case_1()
child = next(iter(cat.get_children()))
with self.assertRaises(pystac.STACError):
cat.add_item(child) # type:ignore
def test_get_child_returns_none_if_not_found(self) -> None:
cat = TestCases.test_case_1()
child = cat.get_child("thisshouldnotbeachildid", recursive=True)
self.assertIsNone(child)
def test_get_item_returns_none_if_not_found(self) -> None:
cat = TestCases.test_case_1()
item = cat.get_item("thisshouldnotbeanitemid", recursive=True)
self.assertIsNone(item)
def test_sets_catalog_type(self) -> None:
cat = TestCases.test_case_1()
self.assertEqual(cat.catalog_type, CatalogType.SELF_CONTAINED)
def test_walk_iterates_correctly(self) -> None:
def test_catalog(cat: Catalog) -> None:
expected_catalog_iterations = 1
actual_catalog_iterations = 0
with self.subTest(title="Testing catalog {}".format(cat.id)):
for root, children, items in cat.walk():
actual_catalog_iterations += 1
expected_catalog_iterations += len(list(root.get_children()))
self.assertEqual(
set([c.id for c in root.get_children()]),
set([c.id for c in children]),
"Children unequal",
)
self.assertEqual(
set([c.id for c in root.get_items()]),
set([c.id for c in items]),
"Items unequal",
)
self.assertEqual(actual_catalog_iterations, expected_catalog_iterations)
for cat in TestCases.all_test_catalogs():
test_catalog(cat)
def test_clone_generates_correct_links(self) -> None:
catalogs = TestCases.all_test_catalogs()
for catalog in catalogs:
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
self.assertEqual(
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]
self.assertEqual(set(expected_counts.keys()), set(actual_counts.keys()))
for rel in expected_counts:
self.assertEqual(
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.test_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)
self.assertEqual(cat2.catalog_type, CatalogType.SELF_CONTAINED)
def test_save_to_provided_href(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.test_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")
self.assertTrue(os.path.exists(catalog_path))
result_cat = Catalog.from_file(catalog_path)
for link in result_cat.get_child_links():
self.assertTrue(cast(str, link.target).startswith(href))
def test_save_relative_published_no_self_links(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.test_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")
self.assertTrue(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,
)
self.assertIsNone(self_link)
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())
self.assertEqual(len(hrefs), stac_io.mock.write_text.call_count)
for call_args_list in stac_io.mock.write_text.call_args_list:
self.assertIn(call_args_list[0][0], hrefs)
def test_subcatalogs_saved_to_correct_path(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.test_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")
self.assertTrue(
os.path.exists(expected_root_catalog_path),
msg=f"{expected_root_catalog_path} does not exist.",
)
self.assertTrue(
os.path.isfile(expected_root_catalog_path),
msg=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,
)
self.assertTrue(
os.path.exists(expected_child_path),
msg=f"{expected_child_path} does not exist.",
)
self.assertTrue(
os.path.isfile(expected_child_path),
msg=f"{expected_child_path} is not a file.",
)
# Check each item
for item in catalog.get_all_items():
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,
)
self.assertTrue(
os.path.exists(expected_item_path),
msg=f"{expected_item_path} does not exist.",
)
self.assertTrue(
os.path.isfile(expected_item_path),
msg=f"{expected_item_path} is not a file.",
)
def test_clone_uses_previous_catalog_type(self) -> None:
catalog = TestCases.test_case_1()
assert catalog.catalog_type == CatalogType.SELF_CONTAINED
clone = catalog.clone()
self.assertEqual(clone.catalog_type, CatalogType.SELF_CONTAINED)
def test_normalize_hrefs_sets_all_hrefs(self) -> None:
catalog = TestCases.test_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
self.assertTrue(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
self.assertTrue(
"http://example.com" in target_href,
'[{}] {} does not contain "{}"'.format(
link.rel, target_href, "http://example.com"
),
)
for item in items:
self.assertIn("http://example.com", item.self_href)
def test_normalize_hrefs_makes_absolute_href(self) -> None:
catalog = TestCases.test_case_1()
catalog.normalize_hrefs("./relativepath")
abspath = os.path.abspath("./relativepath")
self_href = catalog.get_self_href()
assert self_href is not None
self.assertTrue(self_href.startswith(abspath))
def test_normalize_href_works_with_label_source_links(self) -> None:
catalog = TestCases.test_case_1()
catalog.normalize_hrefs("http://example.com")
item = catalog.get_item("area-1-1-labels", recursive=True)
assert item is not None
source = next(iter(LabelExtension.ext(item).get_sources()))
self.assertEqual(
source.get_self_href(),
"http://example.com/country-1/area-1-1/"
"area-1-1-imagery/area-1-1-imagery.json",
)
def test_generate_subcatalogs_works_with_custom_properties(self) -> None:
catalog = TestCases.test_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 = set([cat.id for cat in month_cat.get_children()])
self.assertEqual(type_cats, set(["PSScene4Band", "SkySatScene", "PlanetScope"]))
def test_generate_subcatalogs_does_not_change_item_count(self) -> None:
catalog = TestCases.test_case_7()
item_counts = {
cat.id: len(list(cat.get_all_items())) 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_all_items()))
expected = item_counts[child.id]
self.assertEqual(
actual, expected, msg=" for child '{}'".format(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="item{}".format(ni),
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.utcnow(),
properties=properties,
)
)
result = catalog.generate_subcatalogs("${property1}_${property2}")
actual_subcats = set([cat.id for cat in result])
expected_subcats = set(
["{}_{}".format(d["property1"], d["property2"]) for d in item_properties]
)
self.assertEqual(len(result), len(expected_subcats))
self.assertSetEqual(actual_subcats, expected_subcats)
def test_generate_subcatalogs_can_be_applied_multiple_times(self) -> None:
catalog = TestCases.test_case_8()
_ = catalog.generate_subcatalogs("${year}/${month}")
catalog.normalize_hrefs("/tmp")
expected_hrefs = {
item.id: item.get_self_href() for item in catalog.get_all_items()
}
result = catalog.generate_subcatalogs("${year}/${month}")
self.assertEqual(len(result), 0)
catalog.normalize_hrefs("/tmp")
for item in catalog.get_all_items():
self.assertEqual(
item.get_self_href(),
expected_hrefs[item.id],
msg=" for item '{}'".format(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.utcnow(),
properties=properties,
)
)
catalog.generate_subcatalogs("${property1}/${property2}")
catalog.add_item(
Item(
id="item2",
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.utcnow(),
properties=properties,
)
)
catalog.generate_subcatalogs("${property1}/${property2}")
catalog.normalize_hrefs("/tmp")
item1 = catalog.get_item("item1", recursive=True)
assert item1 is not None
item1_parent = item1.get_parent()
assert item1_parent is not None
item2 = catalog.get_item("item2", recursive=True)
assert item2 is not None
item2_parent = item2.get_parent()
assert item2_parent is not None
self.assertEqual(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="item{}".format(ni),
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.utcnow(),
properties=properties,
)
)
result = catalog.generate_subcatalogs("${property1}/${property2}/${property3}")
self.assertEqual(len(result), 9)
actual_subcats = set([cat.id for cat in result])
expected_subcats = {"A", "B", "1", "2", "i", "j"}
self.assertSetEqual(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="item{}".format(ni),
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime.utcnow(),
properties=properties,
)
)
result = catalog.generate_subcatalogs("${property1}/${property2}")
self.assertEqual(len(result), 6)
catalog.normalize_hrefs("/")
for item in catalog.get_all_items():
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 = [el for el in path_to_parent.split(os.sep) if el]
self.assertEqual(len(subcats), 2, msg=" for item '{}'".format(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.test_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_all_items():
self.assertTrue("ITEM_MAPPER" in item.properties)
for item in catalog.get_all_items():
self.assertFalse("ITEM_MAPPER" 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.test_case_1()
catalog_items = catalog.get_all_items()
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 = result_cat.get_all_items()
self.assertEqual(len(list(catalog_items)) * 2, len(list(result_items)))
ones, twos = 0, 0
for item in result_items:
self.assertTrue(
("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
self.assertEqual(ones, twos)
for item in catalog.get_all_items():
self.assertFalse(
("ITEM_MAPPER_1" in item.properties)
or ("ITEM_MAPPER_2" 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.utcnow(),
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.utcnow(),
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 create_label_item(item: pystac.Item) -> List[pystac.Item]:
# Assumes the GEOJSON labels are in the
# same location as the image
img_href = item.assets["ortho"].href
label_href = "{}.geojson".format(os.path.splitext(img_href)[0])
label_item = Item(
id="Labels",
geometry=item.geometry,
bbox=item.bbox,
datetime=datetime.utcnow(),
properties={},
)
LabelExtension(label_item).add_to(label_item)
label_ext = LabelExtension.ext(label_item)
label_ext.apply(
label_description="labels",
label_type=LabelType.VECTOR,
label_properties=["label"],
label_classes=[
LabelClasses.create(classes=["one", "two"], name="label")
],
label_tasks=["classification"],
)
label_ext.add_source(item, assets=["ortho"])
label_ext.add_geojson_labels(label_href)
return [item, label_item]
c = catalog.map_items(modify_item_title)
c = c.map_items(create_label_item)
new_catalog = c
items = new_catalog.get_all_items()
self.assertTrue(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.test_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_all_items():
for key, asset in item.assets.items():
if key == changed_asset:
found = True
self.assertEqual(asset.title, "NEW TITLE")
else:
self.assertNotEqual(asset.title, "NEW TITLE")
self.assertTrue(found)
def test_map_assets_tup(self) -> None:
changed_assets: List[str] = []
def asset_mapper(
key: str, asset: pystac.Asset
) -> Union[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 ("{}-modified".format(key), asset)
else:
return asset
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.test_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
not_found = False
for item in result_cat.get_all_items():
for key, asset in item.assets.items():
if key.replace("-modified", "") in changed_assets:
found = True
self.assertEqual(asset.title, "NEW TITLE")
else:
not_found = True
self.assertNotEqual(asset.title, "NEW TITLE")
self.assertTrue(found)
self.assertTrue(not_found)
def test_map_assets_multi(self) -> None:
changed_assets = []
def asset_mapper(
key: str, asset: pystac.Asset
) -> Union[pystac.Asset, Dict[str, pystac.Asset]]:
if asset.media_type and "geotiff" in asset.media_type:
changed_assets.append(key)
mod1 = asset.clone()
mod1.title = "NEW TITLE 1"
mod2 = asset.clone()
mod2.title = "NEW TITLE 2"
return {"{}-mod-1".format(key): mod1, "{}-mod-2".format(key): mod2}
else:
return asset
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = TestCases.test_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"))
found1 = False
found2 = False
not_found = False
for item in result_cat.get_all_items():
for key, asset in item.assets.items():
if key.replace("-mod-1", "") in changed_assets:
found1 = True
self.assertEqual(asset.title, "NEW TITLE 1")
elif key.replace("-mod-2", "") in changed_assets:
found2 = True
self.assertEqual(asset.title, "NEW TITLE 2")
else:
not_found = True
self.assertNotEqual(asset.title, "NEW TITLE")
self.assertTrue(found1)
self.assertTrue(found2)
self.assertTrue(not_found)
def test_make_all_asset_hrefs_absolute(self) -> None:
cat = TestCases.test_case_2()
cat.make_all_asset_hrefs_absolute()
item = cat.get_item("cf73ec1a-d790-4b59-b077-e101738571ed", recursive=True)
assert item is not None
href = item.assets["cf73ec1a-d790-4b59-b077-e101738571ed"].href
self.assertTrue(is_absolute_href(href))
def test_make_all_asset_hrefs_relative(self) -> None:
cat = TestCases.test_case_2()
item = cat.get_item("cf73ec1a-d790-4b59-b077-e101738571ed", recursive=True)
assert item is not None
asset = item.assets["cf73ec1a-d790-4b59-b077-e101738571ed"]
original_href = asset.href
cat.make_all_asset_hrefs_absolute()
assert is_absolute_href(asset.href)
cat.make_all_asset_hrefs_relative()
self.assertFalse(is_absolute_href(asset.href))
self.assertEqual(asset.href, original_href)
def test_make_all_links_relative_or_absolute(self) -> None:
def check_all_relative(cat: Catalog) -> None:
for root, catalogs, items in cat.walk():
for link in root.links:
if link.rel in HIERARCHICAL_LINKS:
self.assertFalse(is_absolute_href(link.href))
for item in items:
for link in item.links:
if link.rel in HIERARCHICAL_LINKS:
self.assertFalse(is_absolute_href(link.href))
def check_all_absolute(cat: Catalog) -> None:
for root, catalogs, items in cat.walk():
for link in root.links:
self.assertTrue(is_absolute_href(link.href))
for item in items:
for link in item.links:
self.assertTrue(is_absolute_href(link.href))
test_cases = TestCases.all_test_catalogs()
for catalog in test_cases:
with tempfile.TemporaryDirectory() as tmp_dir:
c2 = catalog.full_copy()
c2.normalize_hrefs(tmp_dir)
c2.catalog_type = CatalogType.RELATIVE_PUBLISHED
check_all_relative(c2)
c2.catalog_type = CatalogType.ABSOLUTE_PUBLISHED
check_all_absolute(c2)
def test_self_contained_catalog_collection_item_links(self) -> None:
"""See issue https://github.com/stac-utils/pystac/issues/657"""
with tempfile.TemporaryDirectory() as tmp_dir:
catalog = pystac.Catalog(
id="catalog-issue-657", description="catalog-issue-657"
)
collection = pystac.Collection(
"collection-issue-657",
"collection-issue-657",
pystac.Extent(
spatial=pystac.SpatialExtent([[-180.0, -90.0, 180.0, 90.0]]),
temporal=pystac.TemporalExtent([[datetime(2021, 11, 1), None]]),
),
license="proprietary",
)
item = pystac.Item(
id="item-issue-657",
stac_extensions=[],
geometry=ARBITRARY_GEOM,
bbox=ARBITRARY_BBOX,
datetime=datetime(2021, 11, 1),
properties={},
)
collection.add_item(item)
catalog.add_child(collection)
catalog.normalize_hrefs(tmp_dir)
catalog.validate_all()
catalog.save(catalog_type=CatalogType.SELF_CONTAINED)
with open(
f"{tmp_dir}/collection-issue-657/item-issue-657/item-issue-657.json"
) as f:
item_json = json.load(f)
for link in item_json["links"]:
# self links are always absolute
if link["rel"] == "self":
continue
href = link["href"]
self.assertFalse(
is_absolute_href(href),