@@ -244,6 +244,66 @@ class TestCase:
244
244
dataclasses .asdict (case .want ), dataclasses .asdict (got ), "-want, +got"
245
245
)
246
246
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
+
247
307
def test_struct_to_dict (self ) -> None :
248
308
@dataclasses .dataclass
249
309
class TestCase :
0 commit comments