feat: use json_format.ParseDict to convert dicts to structs

Signed-off-by: Jesús Fernández <7312236+fernandezcuesta@users.noreply.github.com>
This commit is contained in:
Jesús Fernández 2024-11-25 12:07:47 +01:00
parent 25e49cf3bd
commit c632b0c1ad
No known key found for this signature in database
GPG Key ID: F009C46F547D9A66
2 changed files with 61 additions and 3 deletions

View File

@ -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:

View File

@ -244,6 +244,66 @@ class TestResource(unittest.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: