Skip to content

Commit c632b0c

Browse files
feat: use json_format.ParseDict to convert dicts to structs
Signed-off-by: Jesús Fernández <[email protected]>
1 parent 25e49cf commit c632b0c

File tree

2 files changed

+61
-3
lines changed

2 files changed

+61
-3
lines changed

crossplane/function/resource.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,7 @@ def dict_to_struct(d: dict) -> structpb.Struct:
5858
function makes it possible to work with a Python dict, then convert it to a
5959
struct in a RunFunctionResponse.
6060
"""
61-
s = structpb.Struct()
62-
s.update(d)
63-
return s
61+
return json_format.ParseDict(d, structpb.Struct())
6462

6563

6664
def struct_to_dict(s: structpb.Struct) -> dict:

tests/test_resource.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,66 @@ class TestCase:
244244
dataclasses.asdict(case.want), dataclasses.asdict(got), "-want, +got"
245245
)
246246

247+
def test_dict_to_struct(self) -> None:
248+
@dataclasses.dataclass
249+
class TestCase:
250+
reason: str
251+
d: dict
252+
want: structpb.Struct
253+
254+
cases = [
255+
TestCase(
256+
reason="Convert an empty dictionary to a struct.",
257+
d={},
258+
want=structpb.Struct(),
259+
),
260+
TestCase(
261+
reason="Convert a dictionary with a single field to a struct.",
262+
d={"foo": "bar"},
263+
want=structpb.Struct(
264+
fields={"foo": structpb.Value(string_value="bar")}
265+
),
266+
),
267+
TestCase(
268+
reason="Convert a nested dictionary to a struct.",
269+
d={"foo": {"bar": "baz"}},
270+
want=structpb.Struct(
271+
fields={
272+
"foo": structpb.Value(
273+
struct_value=structpb.Struct(
274+
fields={"bar": structpb.Value(string_value="baz")}
275+
)
276+
)
277+
}
278+
),
279+
),
280+
TestCase(
281+
reason="Convert a nested dictionary containing lists to a struct.",
282+
d={"foo": {"bar": ["baz", "qux"]}},
283+
want=structpb.Struct(
284+
fields={
285+
"foo": structpb.Value(
286+
struct_value=structpb.Struct(
287+
fields={
288+
"bar": structpb.Value(
289+
list_value=structpb.ListValue(
290+
values=[
291+
structpb.Value(string_value="baz"),
292+
structpb.Value(string_value="qux"),
293+
]
294+
)
295+
)
296+
}
297+
)
298+
)
299+
}
300+
),
301+
),
302+
]
303+
for case in cases:
304+
got = resource.dict_to_struct(case.d)
305+
self.assertEqual(case.want, got, "-want, +got")
306+
247307
def test_struct_to_dict(self) -> None:
248308
@dataclasses.dataclass
249309
class TestCase:

0 commit comments

Comments
 (0)