/
test_core.py
1937 lines (1730 loc) · 82 KB
/
test_core.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
# -*- coding: utf-8 -*-
# Copyright 2018, CS GROUP - France, https://www.csgroup.eu/
#
# This file is part of EODAG project
# https://www.github.com/CS-SI/EODAG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import glob
import json
import os
import shutil
import unittest
import uuid
from pathlib import Path
from tempfile import TemporaryDirectory
from pkg_resources import resource_filename
from shapely import wkt
from shapely.geometry import LineString, MultiPolygon, Polygon
from eodag import __version__ as eodag_version
from eodag.utils import GENERIC_PRODUCT_TYPE
from tests import TEST_RESOURCES_PATH
from tests.context import (
DEFAULT_MAX_ITEMS_PER_PAGE,
EODataAccessGateway,
EOProduct,
NoMatchingProductType,
PluginImplementationError,
ProviderConfig,
RequestError,
SearchResult,
UnsupportedProvider,
get_geometry_from_various,
load_default_config,
makedirs,
)
from tests.utils import mock, write_eodag_conf_with_fake_credentials
class TestCoreBase(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(TestCoreBase, cls).setUpClass()
# Mock home and eodag conf directory to tmp dir
cls.tmp_home_dir = TemporaryDirectory()
cls.expanduser_mock = mock.patch(
"os.path.expanduser", autospec=True, return_value=cls.tmp_home_dir.name
)
cls.expanduser_mock.start()
# create eodag conf dir in tmp home dir
eodag_conf_dir = os.path.join(cls.tmp_home_dir.name, ".config", "eodag")
os.makedirs(eodag_conf_dir, exist_ok=False)
# use empty config file with fake credentials in order to have full
# list for tests and prevent providers to be pruned
write_eodag_conf_with_fake_credentials(
os.path.join(eodag_conf_dir, "eodag.yml")
)
@classmethod
def tearDownClass(cls):
super(TestCoreBase, cls).tearDownClass()
# stop Mock and remove tmp config dir
cls.expanduser_mock.stop()
cls.tmp_home_dir.cleanup()
class TestCore(TestCoreBase):
SUPPORTED_PRODUCT_TYPES = {
"CAMS_EAC4": ["cop_ads"],
"CAMS_GACF_AOT": ["cop_ads"],
"CAMS_GACF_MR": ["cop_ads"],
"CAMS_GACF_RH": ["cop_ads"],
"CBERS4_AWFI_L2": ["aws_eos"],
"CBERS4_AWFI_L4": ["aws_eos"],
"CBERS4_MUX_L2": ["aws_eos"],
"CBERS4_MUX_L4": ["aws_eos"],
"CBERS4_PAN10M_L2": ["aws_eos"],
"CBERS4_PAN10M_L4": ["aws_eos"],
"CBERS4_PAN5M_L2": ["aws_eos"],
"CBERS4_PAN5M_L4": ["aws_eos"],
"ERA5_SL": ["cop_cds"],
"L57_REFLECTANCE": ["theia"],
"L8_OLI_TIRS_C1L1": ["aws_eos", "earth_search", "earth_search_gcs", "onda"],
"L8_REFLECTANCE": ["theia"],
"LANDSAT_C2L1": [
"astraea_eod",
"usgs",
"usgs_satapi_aws",
"planetary_computer",
],
"LANDSAT_C2L2": ["usgs", "planetary_computer"],
"LANDSAT_C2L2ALB_BT": ["usgs_satapi_aws"],
"LANDSAT_C2L2ALB_SR": ["usgs_satapi_aws"],
"LANDSAT_C2L2ALB_ST": ["usgs_satapi_aws"],
"LANDSAT_C2L2ALB_TA": ["usgs_satapi_aws"],
"LANDSAT_C2L2_SR": ["usgs_satapi_aws"],
"LANDSAT_C2L2_ST": ["usgs_satapi_aws"],
"LANDSAT_ETM_C1": ["usgs"],
"LANDSAT_ETM_C2L1": ["usgs"],
"LANDSAT_ETM_C2L2": ["usgs"],
"LANDSAT_TM_C1": ["usgs"],
"LANDSAT_TM_C2L1": ["usgs"],
"LANDSAT_TM_C2L2": ["usgs"],
"MODIS_MCD43A4": ["astraea_eod", "aws_eos", "planetary_computer"],
"NAIP": ["astraea_eod", "aws_eos", "planetary_computer"],
"NEMSAUTO_TCDC": ["meteoblue"],
"NEMSGLOBAL_TCDC": ["meteoblue"],
"OSO": ["theia"],
"PLD_BUNDLE": ["theia"],
"PLD_PAN": ["theia"],
"PLD_PANSHARPENED": ["theia"],
"PLD_XS": ["theia"],
"S1_SAR_GRD": [
"astraea_eod",
"aws_eos",
"cop_dataspace",
"creodias",
"mundi",
"onda",
"peps",
"sara",
"planetary_computer",
],
"S1_SAR_OCN": ["cop_dataspace", "creodias", "mundi", "onda", "peps", "sara"],
"S1_SAR_RAW": ["cop_dataspace", "creodias", "mundi", "onda"],
"S1_SAR_SLC": ["cop_dataspace", "creodias", "mundi", "onda", "peps", "sara"],
"S2_MSI_L1C": [
"astraea_eod",
"aws_eos",
"cop_dataspace",
"creodias",
"earth_search",
"earth_search_gcs",
"mundi",
"onda",
"peps",
"sara",
"usgs",
],
"S2_MSI_L2A": [
"astraea_eod",
"aws_eos",
"cop_dataspace",
"creodias",
"earth_search",
"mundi",
"onda",
"peps",
"sara",
"planetary_computer",
],
"S2_MSI_L2A_COG": ["earth_search_cog"],
"S2_MSI_L2A_MAJA": ["theia"],
"S2_MSI_L2B_MAJA_SNOW": ["theia"],
"S2_MSI_L2B_MAJA_WATER": ["theia"],
"S2_MSI_L3A_WASP": ["theia"],
"S3_EFR": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_ERR": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_LAN": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_OLCI_L2LFR": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_OLCI_L2LRR": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_OLCI_L2WFR": ["cop_dataspace", "creodias", "onda", "sara"],
"S3_OLCI_L2WRR": ["cop_dataspace", "creodias", "onda", "sara"],
"S3_RAC": ["sara"],
"S3_SLSTR_L1RBT": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SLSTR_L2AOD": ["cop_dataspace", "creodias", "sara"],
"S3_SLSTR_L2FRP": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SLSTR_L2LST": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SLSTR_L2WST": ["cop_dataspace", "creodias", "onda", "sara"],
"S3_SRA": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SRA_A": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SRA_BS": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SY_AOD": ["cop_dataspace", "creodias", "onda", "sara"],
"S3_SY_SYN": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SY_V10": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SY_VG1": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_SY_VGP": ["cop_dataspace", "creodias", "mundi", "onda", "sara"],
"S3_WAT": ["cop_dataspace", "creodias", "onda", "sara"],
"S5P_L1B_IR_SIR": ["creodias", "mundi"],
"S5P_L1B_IR_UVN": ["creodias", "mundi"],
"S5P_L1B_RA_BD1": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L1B_RA_BD2": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L1B_RA_BD3": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L1B_RA_BD4": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L1B_RA_BD5": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L1B_RA_BD6": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L1B_RA_BD7": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L1B_RA_BD8": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_AER_AI": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_AER_LH": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_CH4": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_CLOUD": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_CO": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_HCHO": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_NO2": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_NP_BD3": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_NP_BD6": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_NP_BD7": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_O3": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_O3_PR": ["cop_dataspace", "creodias", "mundi", "onda"],
"S5P_L2_O3_TCL": ["creodias", "mundi"],
"S5P_L2_SO2": ["cop_dataspace", "creodias", "mundi", "onda"],
"SPOT5_SPIRIT": ["theia"],
"SPOT_SWH": ["theia"],
"SPOT_SWH_OLD": ["theia"],
"TIGGE_CF_SFC": ["ecmwf"],
"VENUS_L1C": ["theia"],
"VENUS_L2A_MAJA": ["theia"],
"VENUS_L3A_MAJA": ["theia"],
GENERIC_PRODUCT_TYPE: [
"theia",
"peps",
"onda",
"mundi",
"usgs",
"creodias",
"astraea_eod",
"usgs_satapi_aws",
"earth_search",
"earth_search_cog",
"earth_search_gcs",
"ecmwf",
"cop_ads",
"cop_cds",
"meteoblue",
"cop_dataspace",
"planetary_computer",
],
}
SUPPORTED_PROVIDERS = [
"peps",
"usgs",
"theia",
"creodias",
"mundi",
"onda",
"aws_eos",
"astraea_eod",
"usgs_satapi_aws",
"earth_search",
"earth_search_cog",
"earth_search_gcs",
"ecmwf",
"cop_ads",
"cop_cds",
"sara",
"meteoblue",
"cop_dataspace",
"planetary_computer",
]
def setUp(self):
super(TestCore, self).setUp()
self.dag = EODataAccessGateway()
self.conf_dir = os.path.join(os.path.expanduser("~"), ".config", "eodag")
# mock os.environ to empty env
self.mock_os_environ = mock.patch.dict(os.environ, {}, clear=True)
self.mock_os_environ.start()
def tearDown(self):
super(TestCore, self).tearDown()
# stop os.environ
self.mock_os_environ.stop()
def test_supported_providers_in_unit_test(self):
"""Every provider must be referenced in the core unittest SUPPORTED_PROVIDERS class attribute"""
for provider in self.dag.available_providers():
self.assertIn(provider, self.SUPPORTED_PROVIDERS)
def test_supported_product_types_in_unit_test(self):
"""Every product type must be referenced in the core unit test SUPPORTED_PRODUCT_TYPES class attribute"""
for product_type in self.dag.list_product_types(fetch_providers=False):
self.assertIn(product_type["ID"], self.SUPPORTED_PRODUCT_TYPES.keys())
def test_list_product_types_ok(self):
"""Core api must correctly return the list of supported product types"""
product_types = self.dag.list_product_types(fetch_providers=False)
self.assertIsInstance(product_types, list)
for product_type in product_types:
self.assertListProductTypesRightStructure(product_type)
# There should be no repeated product type in the output
self.assertEqual(len(product_types), len(set(pt["ID"] for pt in product_types)))
def test_list_product_types_for_provider_ok(self):
"""Core api must correctly return the list of supported product types for a given provider"""
for provider in self.SUPPORTED_PROVIDERS:
product_types = self.dag.list_product_types(
provider=provider, fetch_providers=False
)
self.assertIsInstance(product_types, list)
for product_type in product_types:
self.assertListProductTypesRightStructure(product_type)
self.assertIn(
provider, self.SUPPORTED_PRODUCT_TYPES[product_type["ID"]]
)
def test_list_product_types_for_unsupported_provider(self):
"""Core api must raise UnsupportedProvider error for list_product_types with unsupported provider"""
unsupported_provider = "a"
self.assertRaises(
UnsupportedProvider,
self.dag.list_product_types,
provider=unsupported_provider,
)
@mock.patch(
"eodag.api.core.EODataAccessGateway.fetch_product_types_list", autospec=True
)
def test_list_product_types_fetch_providers(self, mock_fetch_product_types_list):
"""Core api must fetch providers for new product types if option is passed to list_product_types"""
self.dag.list_product_types(fetch_providers=False)
assert not mock_fetch_product_types_list.called
self.dag.list_product_types(provider="peps", fetch_providers=True)
mock_fetch_product_types_list.assert_called_once_with(self.dag, provider="peps")
def test_update_product_types_list(self):
"""Core api.update_product_types_list must update eodag product types list"""
with open(os.path.join(TEST_RESOURCES_PATH, "ext_product_types.json")) as f:
ext_product_types_conf = json.load(f)
self.assertNotIn("foo", self.dag.providers_config["astraea_eod"].products)
self.assertNotIn("bar", self.dag.providers_config["astraea_eod"].products)
self.assertNotIn("foo", self.dag.product_types_config)
self.assertNotIn("bar", self.dag.product_types_config)
self.dag.update_product_types_list(ext_product_types_conf)
self.assertIn("foo", self.dag.providers_config["astraea_eod"].products)
self.assertIn("bar", self.dag.providers_config["astraea_eod"].products)
self.assertEqual(self.dag.product_types_config["foo"]["license"], "WTFPL")
self.assertEqual(
self.dag.product_types_config["bar"]["title"], "Bar collection"
)
def test_update_product_types_list_unknown_provider(self):
"""Core api.update_product_types_list on unkwnown provider must not crash and not update conf"""
with open(os.path.join(TEST_RESOURCES_PATH, "ext_product_types.json")) as f:
ext_product_types_conf = json.load(f)
self.dag.providers_config.pop("astraea_eod")
self.dag.update_product_types_list(ext_product_types_conf)
self.assertNotIn("astraea_eod", self.dag.providers_config)
@mock.patch(
"eodag.plugins.search.qssearch.QueryStringSearch.discover_product_types",
autospec=True,
)
def test_update_product_types_list_with_api_plugin(
self, mock_plugin_discover_product_types
):
"""Core api.update_product_types_list with the api plugin must update eodag product types list"""
with open(os.path.join(TEST_RESOURCES_PATH, "ext_product_types.json")) as f:
ext_product_types_conf = json.load(f)
# we keep the existing ext-conf to use it for a provider with an api plugin
ext_product_types_conf["ecmwf"] = ext_product_types_conf.pop("astraea_eod")
self.assertNotIn("foo", self.dag.providers_config["ecmwf"].products)
self.assertNotIn("bar", self.dag.providers_config["ecmwf"].products)
self.assertNotIn("foo", self.dag.product_types_config)
self.assertNotIn("bar", self.dag.product_types_config)
# ecmwf must have discover_product_types attribute to allow the launch of update_product_types_list
self.dag.update_providers_config(
"""
ecmwf:
api:
discover_product_types:
fetch_url: 'http://new-endpoint'
need_auth: False
"""
)
self.dag.update_product_types_list(ext_product_types_conf)
self.assertIn("foo", self.dag.providers_config["ecmwf"].products)
self.assertIn("bar", self.dag.providers_config["ecmwf"].products)
self.assertEqual(self.dag.product_types_config["foo"]["license"], "WTFPL")
self.assertEqual(
self.dag.product_types_config["bar"]["title"], "Bar collection"
)
def test_update_product_types_list_without_plugin(self):
"""Core api.update_product_types_list without search and api plugin do nothing"""
with open(os.path.join(TEST_RESOURCES_PATH, "ext_product_types.json")) as f:
ext_product_types_conf = json.load(f)
self.assertNotIn("foo", self.dag.providers_config["astraea_eod"].products)
self.assertNotIn("bar", self.dag.providers_config["astraea_eod"].products)
self.assertNotIn("foo", self.dag.product_types_config)
self.assertNotIn("bar", self.dag.product_types_config)
delattr(self.dag.providers_config["astraea_eod"], "search")
self.dag.update_product_types_list(ext_product_types_conf)
self.assertNotIn("foo", self.dag.providers_config["astraea_eod"].products)
self.assertNotIn("bar", self.dag.providers_config["astraea_eod"].products)
self.assertNotIn("foo", self.dag.product_types_config)
self.assertNotIn("bar", self.dag.product_types_config)
@mock.patch(
"eodag.plugins.search.qssearch.QueryStringSearch.discover_product_types",
autospec=True,
return_value={
"providers_config": {"foo": {"productType": "foo"}},
"product_types_config": {"foo": {"title": "Foo collection"}},
},
)
def test_discover_product_types(self, mock_plugin_discover_product_types):
"""Core api must fetch providers for product types"""
ext_product_types_conf = self.dag.discover_product_types(provider="astraea_eod")
self.assertEqual(
ext_product_types_conf["astraea_eod"]["providers_config"]["foo"][
"productType"
],
"foo",
)
self.assertEqual(
ext_product_types_conf["astraea_eod"]["product_types_config"]["foo"][
"title"
],
"Foo collection",
)
@mock.patch(
"eodag.plugins.search.qssearch.QueryStringSearch.discover_product_types",
autospec=True,
return_value={
"providers_config": {"foo": {"productType": "foo"}},
"product_types_config": {"foo": {"title": "Foo collection"}},
},
)
def test_discover_product_types_with_api_plugin(
self, mock_plugin_discover_product_types
):
"""Core api must fetch providers with api plugin for product types"""
self.dag.update_providers_config(
"""
ecmwf:
api:
discover_product_types:
fetch_url: 'http://new-endpoint'
need_auth: False
"""
)
ext_product_types_conf = self.dag.discover_product_types(provider="ecmwf")
self.assertEqual(
ext_product_types_conf["ecmwf"]["providers_config"]["foo"]["productType"],
"foo",
)
self.assertEqual(
ext_product_types_conf["ecmwf"]["product_types_config"]["foo"]["title"],
"Foo collection",
)
def test_discover_product_types_without_plugin(self):
"""Core api must not fetch providers without search and api plugins"""
delattr(self.dag.providers_config["astraea_eod"], "search")
ext_product_types_conf = self.dag.discover_product_types(provider="astraea_eod")
self.assertEqual(
ext_product_types_conf,
None,
)
@mock.patch("eodag.api.core.get_ext_product_types_conf", autospec=True)
@mock.patch(
"eodag.api.core.EODataAccessGateway.discover_product_types", autospec=True
)
def test_fetch_product_types_list(
self, mock_discover_product_types, mock_get_ext_product_types_conf
):
"""Core api must fetch product types list and update if needed"""
# check that no provider has already been fetched
for provider_config in self.dag.providers_config.values():
self.assertFalse(getattr(provider_config, "product_types_fetched", False))
# check that by default get_ext_product_types_conf() is called without args
self.dag.fetch_product_types_list()
mock_get_ext_product_types_conf.assert_called_with()
# check that with an empty/mocked ext-conf, no provider has been fetched
for provider_config in self.dag.providers_config.values():
self.assertFalse(getattr(provider_config, "product_types_fetched", False))
# check that EODAG_EXT_PRODUCT_TYPES_CFG_FILE env var will be used as get_ext_product_types_conf() arg
os.environ["EODAG_EXT_PRODUCT_TYPES_CFG_FILE"] = "some/file"
self.dag.fetch_product_types_list()
mock_get_ext_product_types_conf.assert_called_with("some/file")
os.environ.pop("EODAG_EXT_PRODUCT_TYPES_CFG_FILE")
# check that with a non-empty ext-conf, a provider will be marked as fetched, and eodag conf updated
mock_get_ext_product_types_conf.return_value = {
"astraea_eod": {
"providers_config": {"foo": {"productType": "foo"}},
"product_types_config": {"foo": {"title": "Foo collection"}},
}
}
# add an empty ext-conf for other providers to prevent them to be fetched
for provider, provider_config in self.dag.providers_config.items():
if provider != "astraea_eod" and hasattr(provider_config, "search"):
provider_search_config = provider_config.search
elif provider != "astraea_eod" and hasattr(provider_config, "api"):
provider_search_config = provider_config.api
else:
continue
if hasattr(
provider_search_config, "discover_product_types"
) and provider_search_config.discover_product_types.get("fetch_url", None):
mock_get_ext_product_types_conf.return_value[provider] = {}
self.dag.fetch_product_types_list()
self.assertTrue(self.dag.providers_config["astraea_eod"].product_types_fetched)
self.assertEqual(
self.dag.providers_config["astraea_eod"].products["foo"],
{"productType": "foo"},
)
self.assertEqual(
self.dag.product_types_config.source["foo"], {"title": "Foo collection"}
)
# update existing provider conf and check that discover_product_types() is launched for it
self.assertEqual(mock_discover_product_types.call_count, 0)
self.dag.update_providers_config(
"""
astraea_eod:
search:
discover_product_types:
fetch_url: 'http://new-endpoint'
"""
)
self.dag.fetch_product_types_list()
mock_discover_product_types.assert_called_once_with(
self.dag, provider="astraea_eod"
)
# add new provider conf and check that discover_product_types() is launched for it
self.assertEqual(mock_discover_product_types.call_count, 1)
self.dag.update_providers_config(
"""
foo_provider:
search:
type: StacSearch
api_endpoint: https://foo.bar/search
products:
GENERIC_PRODUCT_TYPE:
productType: '{productType}'
"""
)
self.dag.fetch_product_types_list()
mock_discover_product_types.assert_called_with(
self.dag, provider="foo_provider"
)
# discover_product_types() should have been called 2 more times
# (once per dynamically configured provider)
self.assertEqual(mock_discover_product_types.call_count, 3)
# now check that if provider is specified, only this one is fetched
mock_discover_product_types.reset_mock()
self.dag.fetch_product_types_list(provider="foo_provider")
mock_discover_product_types.assert_called_once_with(
self.dag, provider="foo_provider"
)
@mock.patch("eodag.api.core.get_ext_product_types_conf", autospec=True)
@mock.patch(
"eodag.api.core.EODataAccessGateway.discover_product_types", autospec=True
)
def test_fetch_product_types_list_without_ext_conf(
self, mock_discover_product_types, mock_get_ext_product_types_conf
):
"""Core api must not fetch product types list and must discover product types without ext-conf"""
# check that no provider has already been fetched
for provider_config in self.dag.providers_config.values():
self.assertFalse(getattr(provider_config, "product_types_fetched", False))
# check that without an ext-conf, discover_product_types() is launched for it
mock_get_ext_product_types_conf.return_value = {}
self.dag.fetch_product_types_list()
self.assertEqual(mock_discover_product_types.call_count, 1)
# check that without an ext-conf, no provider has been fetched
for provider_config in self.dag.providers_config.values():
self.assertFalse(getattr(provider_config, "product_types_fetched", False))
@mock.patch("eodag.api.core.get_ext_product_types_conf", autospec=True)
@mock.patch(
"eodag.api.core.EODataAccessGateway.discover_product_types", autospec=True
)
def test_fetch_product_types_list_updated_system_conf(
self, mock_discover_product_types, mock_get_ext_product_types_conf
):
"""fetch_product_types_list must launch product types discovery for new system-wide providers"""
# add a new system-wide provider not listed in ext-conf
new_default_conf = load_default_config()
new_default_conf["new_provider"] = new_default_conf["astraea_eod"]
with mock.patch(
"eodag.api.core.load_default_config",
return_value=new_default_conf,
autospec=True,
):
self.dag = EODataAccessGateway()
mock_get_ext_product_types_conf.return_value = {}
# disabled product types discovery
os.environ["EODAG_EXT_PRODUCT_TYPES_CFG_FILE"] = ""
self.dag.fetch_product_types_list()
mock_discover_product_types.assert_not_called()
os.environ.pop("EODAG_EXT_PRODUCT_TYPES_CFG_FILE")
# add an empty ext-conf for other providers to prevent them to be fetched
for provider, provider_config in self.dag.providers_config.items():
if provider != "new_provider" and hasattr(provider_config, "search"):
provider_search_config = provider_config.search
elif provider != "new_provider" and hasattr(provider_config, "api"):
provider_search_config = provider_config.api
else:
continue
if hasattr(
provider_search_config, "discover_product_types"
) and provider_search_config.discover_product_types.get(
"fetch_url", None
):
mock_get_ext_product_types_conf.return_value[provider] = {}
self.dag.fetch_product_types_list()
mock_discover_product_types.assert_called_once_with(
self.dag, provider="new_provider"
)
@mock.patch(
"eodag.api.core.EODataAccessGateway.discover_product_types", autospec=True
)
def test_fetch_product_types_list_disabled(self, mock_discover_product_types):
"""fetch_product_types_list must not launch product types discovery if disabled"""
# disable product types discovery
os.environ["EODAG_EXT_PRODUCT_TYPES_CFG_FILE"] = ""
# default settings
self.dag.fetch_product_types_list()
mock_discover_product_types.assert_not_called()
# only user-defined providers must be fetched
self.dag.update_providers_config(
"""
astraea_eod:
search:
discover_product_types:
fetch_url: 'http://new-endpoint'
foo_provider:
search:
type: StacSearch
api_endpoint: https://foo.bar/search
products:
GENERIC_PRODUCT_TYPE:
productType: '{productType}'
"""
)
self.dag.fetch_product_types_list()
self.assertEqual(mock_discover_product_types.call_count, 2)
def assertListProductTypesRightStructure(self, structure):
"""Helper method to verify that the structure given is a good result of
EODataAccessGateway.list_product_types
"""
self.assertIsInstance(structure, dict)
self.assertIn("ID", structure)
self.assertIn("abstract", structure)
self.assertIn("instrument", structure)
self.assertIn("platform", structure)
self.assertIn("platformSerialIdentifier", structure)
self.assertIn("processingLevel", structure)
self.assertIn("sensorType", structure)
self.assertIn(structure["ID"], self.SUPPORTED_PRODUCT_TYPES)
@mock.patch("eodag.api.core.open_dir", autospec=True)
@mock.patch("eodag.api.core.exists_in", autospec=True, return_value=True)
def test_core_object_open_index_if_exists(self, exists_in_mock, open_dir_mock):
"""The core object must use the existing index dir if any"""
index_dir = os.path.join(self.conf_dir, ".index")
if not os.path.exists(index_dir):
makedirs(index_dir)
EODataAccessGateway()
open_dir_mock.assert_called_with(index_dir)
def test_core_object_set_default_locations_config(self):
"""The core object must set the default locations config on instantiation"""
default_shpfile = os.path.join(
self.conf_dir, "shp", "ne_110m_admin_0_map_units.shp"
)
self.assertIsInstance(self.dag.locations_config, list)
self.assertEqual(
self.dag.locations_config,
[dict(attr="ADM0_A3_US", name="country", path=default_shpfile)],
)
def test_core_object_locations_file_not_found(self):
"""The core object must set the locations to an empty list when the file is not found"""
dag = EODataAccessGateway(locations_conf_path="no_locations.yml")
self.assertEqual(dag.locations_config, [])
def test_prune_providers_list(self):
"""Providers needing auth for search but without credentials must be pruned on init"""
empty_conf_file = resource_filename(
"eodag", os.path.join("resources", "user_conf_template.yml")
)
try:
# Default conf: no auth needed for search
dag = EODataAccessGateway(user_conf_file_path=empty_conf_file)
assert not getattr(dag.providers_config["peps"].search, "need_auth", False)
# auth needed for search without credentials
os.environ["EODAG__PEPS__SEARCH__NEED_AUTH"] = "true"
dag = EODataAccessGateway(user_conf_file_path=empty_conf_file)
assert "peps" not in dag.available_providers()
# auth needed for search with credentials
os.environ["EODAG__PEPS__SEARCH__NEED_AUTH"] = "true"
os.environ["EODAG__PEPS__AUTH__CREDENTIALS__USERNAME"] = "foo"
dag = EODataAccessGateway(user_conf_file_path=empty_conf_file)
assert "peps" in dag.available_providers()
assert getattr(dag.providers_config["peps"].search, "need_auth", False)
# Teardown
finally:
os.environ.pop("EODAG__PEPS__SEARCH__NEED_AUTH", None)
os.environ.pop("EODAG__PEPS__AUTH__CREDENTIALS__USERNAME", None)
def test_prune_providers_list_for_search_without_auth(self):
"""Providers needing auth for search but without auth plugin must be pruned on init"""
empty_conf_file = resource_filename(
"eodag", os.path.join("resources", "user_conf_template.yml")
)
try:
# auth needed for search with need_auth but without auth plugin
os.environ["EODAG__PEPS__SEARCH__NEED_AUTH"] = "true"
os.environ["EODAG__PEPS__AUTH__CREDENTIALS__USERNAME"] = "foo"
dag = EODataAccessGateway(user_conf_file_path=empty_conf_file)
delattr(dag.providers_config["peps"], "auth")
assert "peps" in dag.available_providers()
assert getattr(dag.providers_config["peps"].search, "need_auth", False)
assert not hasattr(dag.providers_config["peps"], "auth")
with self.assertLogs(level="INFO") as cm:
dag._prune_providers_list()
self.assertNotIn("peps", dag.providers_config.keys())
self.assertIn(
"peps: provider needing auth for search has been pruned because no auth plugin could be found",
str(cm.output),
)
# Teardown
finally:
os.environ.pop("EODAG__PEPS__SEARCH__NEED_AUTH", None)
os.environ.pop("EODAG__PEPS__AUTH__CREDENTIALS__USERNAME", None)
def test_prune_providers_list_without_api_or_search_plugin(self):
"""Providers without api or search plugin must be pruned on init"""
empty_conf_file = resource_filename(
"eodag", os.path.join("resources", "user_conf_template.yml")
)
dag = EODataAccessGateway(user_conf_file_path=empty_conf_file)
delattr(dag.providers_config["peps"], "search")
assert "peps" in dag.available_providers()
assert not hasattr(dag.providers_config["peps"], "api")
assert not hasattr(dag.providers_config["peps"], "search")
assert "peps" in dag.available_providers()
with self.assertLogs(level="INFO") as cm:
dag._prune_providers_list()
self.assertNotIn("peps", dag.providers_config.keys())
self.assertIn(
"peps: provider has been pruned because no api or search plugin could be found",
str(cm.output),
)
def test_rebuild_index(self):
"""Change product_types_config_md5 and check that whoosh index is rebuilt"""
index_dir = os.path.join(self.dag.conf_dir, ".index")
index_dir_mtime = os.path.getmtime(index_dir)
random_md5 = uuid.uuid4().hex
self.assertNotEqual(self.dag.product_types_config_md5, random_md5)
self.dag.product_types_config_md5 = random_md5
self.dag.build_index()
# check that index_dir has beeh re-created
self.assertNotEqual(os.path.getmtime(index_dir), index_dir_mtime)
def test_get_version(self):
"""Test if the version we get is the current one"""
version_str = self.dag.get_version()
self.assertEqual(eodag_version, version_str)
@mock.patch("eodag.api.core.exists_in", autospec=True)
def test_build_index_ko(self, exists_in_mock):
"""
Trying to build index with unsupported pickle version or other reason leads to ValueError
and may delete the current index to rebuild it
"""
exists_in_mock.side_effect = ValueError("unsupported pickle protocol")
index_dir = os.path.join(self.conf_dir, ".index")
path = Path(index_dir)
self.assertTrue(path.is_dir())
last_index_modif_date = os.stat(index_dir).st_atime_ns
with self.assertLogs(level="DEBUG") as cm:
self.dag.build_index()
new_index_modif_date = os.stat(index_dir).st_atime_ns
self.assertIn(
f"Need to recreate whoosh .index: '{exists_in_mock.side_effect}'",
str(cm.output),
)
self.assertNotEqual(last_index_modif_date, new_index_modif_date)
exists_in_mock.side_effect = ValueError("dummy error")
with self.assertLogs(level="ERROR") as cm_logs:
with self.assertRaisesRegex(ValueError, "dummy error"):
self.dag.build_index()
self.assertIn(
"Error while opening .index using whoosh, "
"please report this issue and try to delete",
str(cm_logs.output),
)
def test_set_preferred_provider(self):
"""set_preferred_provider must set the preferred provider with increasing priority"""
self.assertEqual(self.dag.get_preferred_provider(), ("peps", 1))
self.assertRaises(
UnsupportedProvider, self.dag.set_preferred_provider, "unknown"
)
self.dag.set_preferred_provider("creodias")
self.assertEqual(self.dag.get_preferred_provider(), ("creodias", 2))
self.dag.set_preferred_provider("theia")
self.assertEqual(self.dag.get_preferred_provider(), ("theia", 3))
self.dag.set_preferred_provider("creodias")
self.assertEqual(self.dag.get_preferred_provider(), ("creodias", 4))
def test_update_providers_config(self):
"""update_providers_config must update providers configuration"""
new_config = """
my_new_provider:
search:
type: StacSearch
api_endpoint: https://api.my_new_provider/search
products:
GENERIC_PRODUCT_TYPE:
productType: '{productType}'
"""
# add new provider
self.dag.update_providers_config(new_config)
self.assertIsInstance(
self.dag.providers_config["my_new_provider"], ProviderConfig
)
self.assertEqual(self.dag.providers_config["my_new_provider"].priority, 0)
# run a 2nd time: check that it does not raise an error
self.dag.update_providers_config(new_config)
class TestCoreConfWithEnvVar(TestCoreBase):
@classmethod
def setUpClass(cls):
super(TestCoreConfWithEnvVar, cls).setUpClass()
cls.dag = EODataAccessGateway()
# mock os.environ to empty env
cls.mock_os_environ = mock.patch.dict(os.environ, {}, clear=True)
cls.mock_os_environ.start()
@classmethod
def tearDownClass(cls):
super(TestCoreConfWithEnvVar, cls).tearDownClass()
# stop os.environ
cls.mock_os_environ.stop()
def test_core_object_prioritize_locations_file_in_envvar(self):
"""The core object must use the locations file pointed to by the EODAG_LOCS_CFG_FILE env var"""
try:
os.environ["EODAG_LOCS_CFG_FILE"] = os.path.join(
TEST_RESOURCES_PATH, "file_locations_override.yml"
)
dag = EODataAccessGateway()
self.assertEqual(
dag.locations_config,
[dict(attr="dummyattr", name="dummyname", path="dummypath.shp")],
)
finally:
os.environ.pop("EODAG_LOCS_CFG_FILE", None)
def test_core_object_prioritize_config_file_in_envvar(self):
"""The core object must use the config file pointed to by the EODAG_CFG_FILE env var"""
try:
os.environ["EODAG_CFG_FILE"] = os.path.join(
TEST_RESOURCES_PATH, "file_config_override.yml"
)
dag = EODataAccessGateway()
# usgs priority is set to 5 in the test config overrides
self.assertEqual(dag.get_preferred_provider(), ("usgs", 5))
# peps outputs prefix is set to /data
self.assertEqual(
dag.providers_config["peps"].download.outputs_prefix, "/data"
)
finally:
os.environ.pop("EODAG_CFG_FILE", None)
class TestCoreInvolvingConfDir(unittest.TestCase):
def setUp(self):
super(TestCoreInvolvingConfDir, self).setUp()
self.dag = EODataAccessGateway()
def tearDown(self):
super(TestCoreInvolvingConfDir, self).tearDown()
for old in glob.glob1(self.dag.conf_dir, "*.old") + glob.glob1(
self.dag.conf_dir, ".*.old"
):
old_path = os.path.join(self.dag.conf_dir, old)
if os.path.exists(old_path):
try:
os.remove(old_path)
except OSError:
shutil.rmtree(old_path)
def execution_involving_conf_dir(self, inspect=None):
"""Check that the path(s) inspected (str, list) are created after the instantation
of EODataAccessGateway. If they were already there, rename them (.old), instantiate,
check, delete the new files, and restore the existing files to there previous name."""
if inspect is not None:
if isinstance(inspect, str):
inspect = [inspect]
conf_dir = os.path.join(os.path.expanduser("~"), ".config", "eodag")
olds = []
currents = []
for inspected in inspect:
old = current = os.path.join(conf_dir, inspected)
if os.path.exists(current):
old = os.path.join(conf_dir, "{}.old".format(inspected))
shutil.move(current, old)
olds.append(old)
currents.append(current)
EODataAccessGateway()
for old, current in zip(olds, currents):
self.assertTrue(os.path.exists(current))
if old != current:
try:
shutil.rmtree(current)
except OSError:
os.unlink(current)
shutil.move(old, current)
def test_core_object_creates_config_standard_location(self):
"""The core object must create a user config file in standard user config location on instantiation"""
self.execution_involving_conf_dir(inspect="eodag.yml")
def test_core_object_creates_index_if_not_exist(self):
"""The core object must create an index in user config directory"""
self.execution_involving_conf_dir(inspect=".index")
def test_core_object_creates_locations_standard_location(self):
"""The core object must create a locations config file and a shp dir in standard user config location on instantiation""" # noqa
self.execution_involving_conf_dir(inspect=["locations.yml", "shp"])
class TestCoreGeometry(TestCoreBase):
@classmethod
def setUpClass(cls):
super(TestCoreGeometry, cls).setUpClass()
cls.dag = EODataAccessGateway()
def test_get_geometry_from_various_no_locations(self):
"""The search geometry can be set from a dict, list, tuple, WKT string or shapely geom"""
ref_geom_as_wkt = "POLYGON ((0 50, 0 52, 2 52, 2 50, 0 50))"
ref_geom = wkt.loads(ref_geom_as_wkt)
# Good dict
geometry = {
"lonmin": 0,