@@ -248,6 +248,66 @@ class TestCase:
248248 dataclasses .asdict (case .want ), dataclasses .asdict (got ), "-want, +got"
249249 )
250250
251+ def test_dict_to_struct (self ) -> None :
252+ @dataclasses .dataclass
253+ class TestCase :
254+ reason : str
255+ d : dict
256+ want : structpb .Struct
257+
258+ cases = [
259+ TestCase (
260+ reason = "Convert an empty dictionary to a struct." ,
261+ d = {},
262+ want = structpb .Struct (),
263+ ),
264+ TestCase (
265+ reason = "Convert a dictionary with a single field to a struct." ,
266+ d = {"foo" : "bar" },
267+ want = structpb .Struct (
268+ fields = {"foo" : structpb .Value (string_value = "bar" )}
269+ ),
270+ ),
271+ TestCase (
272+ reason = "Convert a nested dictionary to a struct." ,
273+ d = {"foo" : {"bar" : "baz" }},
274+ want = structpb .Struct (
275+ fields = {
276+ "foo" : structpb .Value (
277+ struct_value = structpb .Struct (
278+ fields = {"bar" : structpb .Value (string_value = "baz" )}
279+ )
280+ )
281+ }
282+ ),
283+ ),
284+ TestCase (
285+ reason = "Convert a nested dictionary containing lists to a struct." ,
286+ d = {"foo" : {"bar" : ["baz" , "qux" ]}},
287+ want = structpb .Struct (
288+ fields = {
289+ "foo" : structpb .Value (
290+ struct_value = structpb .Struct (
291+ fields = {
292+ "bar" : structpb .Value (
293+ list_value = structpb .ListValue (
294+ values = [
295+ structpb .Value (string_value = "baz" ),
296+ structpb .Value (string_value = "qux" ),
297+ ]
298+ )
299+ )
300+ }
301+ )
302+ )
303+ }
304+ ),
305+ ),
306+ ]
307+ for case in cases :
308+ got = resource .dict_to_struct (case .d )
309+ self .assertEqual (case .want , got , "-want, +got" )
310+
251311 def test_struct_to_dict (self ) -> None :
252312 @dataclasses .dataclass
253313 class TestCase :
@@ -279,6 +339,28 @@ class TestCase:
279339 ),
280340 want = {"foo" : {"bar" : "baz" }},
281341 ),
342+ TestCase (
343+ reason = "Convert a nested struct containing ListValues to a dictionary." ,
344+ s = structpb .Struct (
345+ fields = {
346+ "foo" : structpb .Value (
347+ struct_value = structpb .Struct (
348+ fields = {
349+ "bar" : structpb .Value (
350+ list_value = structpb .ListValue (
351+ values = [
352+ structpb .Value (string_value = "baz" ),
353+ structpb .Value (string_value = "qux" ),
354+ ]
355+ )
356+ )
357+ }
358+ )
359+ )
360+ }
361+ ),
362+ want = {"foo" : {"bar" : ["baz" , "qux" ]}},
363+ ),
282364 ]
283365
284366 for case in cases :
0 commit comments