Skip to content

Commit

Permalink
feat: use json_format.ParseDict to convert dicts to structs
Browse files Browse the repository at this point in the history
  • Loading branch information
fernandezcuesta committed Nov 25, 2024
1 parent 25e49cf commit 8724e2d
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
4 changes: 1 addition & 3 deletions crossplane/function/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ def dict_to_struct(d: dict) -> structpb.Struct:
function makes it possible to work with a Python dict, then convert it to a
struct in a RunFunctionResponse.
"""
s = structpb.Struct()
s.update(d)
return s
return json_format.ParseDict(d, structpb.Struct())


def struct_to_dict(s: structpb.Struct) -> dict:
Expand Down
60 changes: 60 additions & 0 deletions tests/test_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,66 @@ class TestCase:
dataclasses.asdict(case.want), dataclasses.asdict(got), "-want, +got"
)

def test_dict_to_struct(self) -> None:
@dataclasses.dataclass
class TestCase:
reason: str
d: dict
want: structpb.Struct

cases = [
TestCase(
reason="Convert an empty dictionary to a struct.",
d={},
want=structpb.Struct(),
),
TestCase(
reason="Convert a dictionary with a single field to a struct.",
d={"foo": "bar"},
want=structpb.Struct(
fields={"foo": structpb.Value(string_value="bar")}
),
),
TestCase(
reason="Convert a nested dictionary to a struct.",
d={"foo": {"bar": "baz"}},
want=structpb.Struct(
fields={
"foo": structpb.Value(
struct_value=structpb.Struct(
fields={"bar": structpb.Value(string_value="baz")}
)
)
}
),
),
TestCase(
reason="Convert a nested dictionary containing lists to a struct.",
d={"foo": {"bar": ["baz", "qux"]}},
want=structpb.Struct(
fields={
"foo": structpb.Value(
struct_value=structpb.Struct(
fields={
"bar": structpb.Value(
list_value=structpb.ListValue(
values=[
structpb.Value(string_value="baz"),
structpb.Value(string_value="qux"),
]
)
)
}
)
)
}
),
),
]
for case in cases:
got = resource.dict_to_struct(case.d)
self.assertEqual(case.want, got, "-want, +got")

def test_struct_to_dict(self) -> None:
@dataclasses.dataclass
class TestCase:
Expand Down

0 comments on commit 8724e2d

Please sign in to comment.