Skip to content

Commit a4b79a0

Browse files
issue693 move adapt search_list_for_dict_key to get_enum_options for Schema and add testing
1 parent 503154b commit a4b79a0

File tree

6 files changed

+96
-68
lines changed

6 files changed

+96
-68
lines changed

openeo/internal/processes/parse.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ def is_geojson_schema(schema) -> bool:
4343
return any(is_geojson_schema(s) for s in self.schema)
4444
return False
4545

46+
def get_enum_options(self,name):
47+
result = None
48+
if isinstance(self.schema,list):
49+
for item in self.schema:
50+
if name in item:
51+
if result is None:
52+
result = item[name]
53+
else:
54+
raise ValueError("Multiple entries found with name {v}.".format(v=name))
55+
elif isinstance(self.schema,dict):
56+
if name in self.schema:
57+
result = self.schema[name]
58+
return result
59+
4660

4761
_NO_DEFAULT = object()
4862

@@ -127,11 +141,11 @@ def from_json_file(cls, path: Union[str, Path]) -> Process:
127141
with Path(path).open("r") as f:
128142
return cls.from_json(f.read())
129143

130-
def get_parameter(self, parameter_id: str) -> Union[dict, list]:
144+
def get_parameter(self, name: str) -> Parameter:
131145
for parameter in self.parameters:
132-
if parameter.name == parameter_id:
133-
return parameter.schema.schema
134-
raise LookupError(f"Expected parameter {parameter_id} not found.")
146+
if parameter.name == name:
147+
return parameter
148+
raise LookupError(f"Parameter {name!r} not found.")
135149

136150

137151
def parse_all_from_dir(path: Union[str, Path], pattern="*.json") -> Iterator[Process]:

openeo/rest/connection.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
from openeo.internal.graph_building import FlatGraphableMixin, PGNode, as_flat_graph
3939
from openeo.internal.jupyter import VisualDict, VisualList
4040
from openeo.internal.processes.builder import ProcessBuilderBase
41-
from openeo.internal.processes.parse import Process
4241
from openeo.internal.warnings import deprecated, legacy_alias
4342
from openeo.metadata import (
4443
Band,

openeo/rest/datacube.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@
6666
load_json,
6767
normalize_crs,
6868
rfc3339,
69-
search_list_for_dict_key,
7069
)
7170

7271
if typing.TYPE_CHECKING:
@@ -2741,10 +2740,10 @@ def sar_backscatter(
27412740
.. versionchanged:: 0.4.10 replace `orthorectify` and `rtc` arguments with `coefficient`.
27422741
"""
27432742
try:
2744-
schema = Process.from_dict(self.connection.describe_process("sar_backscatter")).get_parameter("coefficient")
2745-
coefficient_options = search_list_for_dict_key(schema, "enum") + [None]
2746-
except Exception:
2747-
log.warning(f"Failed to extract option for coefficient in sar_backscatter")
2743+
schema = Process.from_dict(self.connection.describe_process("sar_backscatter")).get_parameter("coefficient").schema
2744+
coefficient_options = schema.get_enum_options("enum") + [None]
2745+
except Exception as e:
2746+
log.warning(f"Failed to extract coefficient options for process `sar_backscatter`: {e}")
27482747
coefficient_options = [
27492748
"beta0",
27502749
"sigma0-ellipsoid",

openeo/util.py

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -687,22 +687,3 @@ def normalize_crs(crs: Any, *, use_pyproj: bool = True) -> Union[None, int, str]
687687
raise ValueError(f"Can not normalize CRS data {type(crs)}")
688688

689689
return crs
690-
691-
692-
def search_list_for_dict_key(lst: list, key: str) -> Union[dict, list]:
693-
"""
694-
Searches a value of the dict that matches with the key in the list.
695-
696-
:param lst: list with dictionaries.
697-
:param key: The key for which the value is searched for.
698-
699-
:return: value that matches key.
700-
"""
701-
result = None
702-
for item in lst:
703-
if key in item:
704-
if result is None:
705-
result = item[key]
706-
else:
707-
raise ValueError("Multiple keys found with value {v}.".format(v=key))
708-
return result

tests/internal/processes/test_parse.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,35 @@ def test_schema_accepts_geojson(schema, expected):
3636
assert Schema([{"type": "number"}, schema]).accepts_geojson() == expected
3737

3838

39+
@pytest.mark.parametrize(
40+
"schema",
41+
[
42+
Schema([
43+
{"x1": "y1"},
44+
{"x2": "y2"},
45+
{"x3": "y3"},
46+
{"x5": "y3"},
47+
]),
48+
Schema({"x1":"y1","x2":"y2","x3": "y3","x5": "y3"})
49+
],
50+
)
51+
@pytest.mark.parametrize(("key", "expected"), [("x1", "y1"), ("x2", "y2"), ("x4", None)])
52+
def test_get_enum_options(schema, key, expected):
53+
assert schema.get_enum_options(key) == expected
54+
55+
@pytest.mark.parametrize("key",["x2","x3",])
56+
def test_get_enum_options_error(key):
57+
schema = Schema([
58+
{"x1": "y1"},
59+
{"x2": "y2"},
60+
{"x3": "y3"},
61+
{"x3": "y4"},
62+
{"x2": "y1"},
63+
])
64+
with pytest.raises(ValueError):
65+
schema.get_enum_options(key)
66+
67+
3968
def test_parameter():
4069
p = Parameter.from_dict({
4170
"name": "foo",
@@ -138,6 +167,51 @@ def test_process_from_json():
138167
assert p.returns.schema.schema == {"type": ["number", "null"], "minimum": 0}
139168

140169

170+
@pytest.mark.parametrize(
171+
("key", "expected"), [
172+
("x", Parameter.from_dict({"name": "x", "description": "A number.", "schema": {"type": ["number", "null"]}})),
173+
("y", Parameter.from_dict({"name": "y", "description": "A number.", "schema": {"type": ["number", "null"]}})),
174+
]
175+
)
176+
def test_get_parameter(key, expected):
177+
p = Process.from_dict({
178+
"id": "absolute",
179+
"summary": "Absolute value",
180+
"description": "Computes the absolute value of a real number.",
181+
"categories": ["math"],
182+
"parameters": [
183+
{"name": "x", "description": "A number.", "schema": {"type": ["number", "null"]}},
184+
{"name": "y", "description": "A number.", "schema": {"type": ["number", "null"]}},
185+
],
186+
"returns": {
187+
"description": "The computed absolute value.",
188+
"schema": {"type": ["number", "null"], "minimum": 0}
189+
},
190+
"links": [{"rel": "about", "href": "http://example.com/abs.html"}],
191+
})
192+
assert p.get_parameter(key) == expected
193+
194+
195+
def test_get_parameter_error():
196+
p = Process.from_dict({
197+
"id": "absolute",
198+
"summary": "Absolute value",
199+
"description": "Computes the absolute value of a real number.",
200+
"categories": ["math"],
201+
"parameters": [
202+
{"name": "x", "description": "A number.", "schema": {"type": ["number", "null"]}},
203+
{"name": "y", "description": "A number.", "schema": {"type": ["number", "null"]}},
204+
],
205+
"returns": {
206+
"description": "The computed absolute value.",
207+
"schema": {"type": ["number", "null"], "minimum": 0}
208+
},
209+
"links": [{"rel": "about", "href": "http://example.com/abs.html"}],
210+
})
211+
with pytest.raises(LookupError):
212+
p.get_parameter("z")
213+
214+
141215
def test_parse_remote_process_definition_minimal(requests_mock):
142216
url = "https://example.com/ndvi.json"
143217
requests_mock.get(url, json={"id": "ndvi"})

tests/test_util.py

Lines changed: 0 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333
normalize_crs,
3434
repr_truncate,
3535
rfc3339,
36-
search_list_for_dict_key,
3736
str_truncate,
3837
to_bbox_dict,
3938
url_join,
@@ -1056,41 +1055,3 @@ def test_normalize_crs_succeeds_with_correct_projstring(self, epsg_input, expect
10561055
def test_normalize_crs_handles_incorrect_crs(self, epsg_input, use_pyproj):
10571056
with pytest.raises(ValueError):
10581057
normalize_crs(epsg_input, use_pyproj=use_pyproj)
1059-
1060-
@pytest.mark.parametrize(
1061-
"list_with_dicts",
1062-
[
1063-
[
1064-
{"x1": "y1"},
1065-
{"x2": "y2"},
1066-
{"x3": "y3"},
1067-
{"x3": "y3"},
1068-
]
1069-
],
1070-
)
1071-
@pytest.mark.parametrize(("key", "expected"), [("x1", "y1"), ("x2", "y2"), ("x4", None)])
1072-
def test_search_list_for_dict_key(self, list_with_dicts, key, expected):
1073-
assert search_list_for_dict_key(list_with_dicts, key) == expected
1074-
1075-
@pytest.mark.parametrize(
1076-
"list_with_dicts",
1077-
[
1078-
[
1079-
{"x1": "y1"},
1080-
{"x2": "y2"},
1081-
{"x3": "y3"},
1082-
{"x3": "y4"},
1083-
{"x2": "y1"},
1084-
]
1085-
],
1086-
)
1087-
@pytest.mark.parametrize(
1088-
"key",
1089-
[
1090-
"x2",
1091-
"x3",
1092-
],
1093-
)
1094-
def test_search_list_for_dict_key_value_error(self, list_with_dicts, key):
1095-
with pytest.raises(ValueError):
1096-
search_list_for_dict_key(list_with_dicts, key)

0 commit comments

Comments
 (0)