Skip to content

Commit 6037575

Browse files
authored
Merge pull request #73 from fernandezcuesta/main
fix: recursively convert struct to dict
2 parents 50f301a + 556607e commit 6037575

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

crossplane/function/resource.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ def struct_to_dict(s: structpb.Struct) -> dict:
4242
protobuf struct. This function makes it possible to convert resources to a
4343
dictionary.
4444
"""
45-
return dict(s)
45+
return {
46+
k: (struct_to_dict(v) if isinstance(v, structpb.Struct) else v)
47+
for k, v in s.items()
48+
}
4649

4750

4851
@dataclasses.dataclass

tests/test_resource.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,43 @@ class TestCase:
165165
dataclasses.asdict(case.want), dataclasses.asdict(got), "-want, +got"
166166
)
167167

168+
def test_struct_to_dict(self) -> None:
169+
@dataclasses.dataclass
170+
class TestCase:
171+
reason: str
172+
s: structpb.Struct
173+
want: dict
174+
175+
cases = [
176+
TestCase(
177+
reason="Convert a struct with no fields to an empty dictionary.",
178+
s=structpb.Struct(),
179+
want={},
180+
),
181+
TestCase(
182+
reason="Convert a struct with a single field to a dictionary.",
183+
s=structpb.Struct(fields={"foo": structpb.Value(string_value="bar")}),
184+
want={"foo": "bar"},
185+
),
186+
TestCase(
187+
reason="Convert a nested struct to a dictionary.",
188+
s=structpb.Struct(
189+
fields={
190+
"foo": structpb.Value(
191+
struct_value=structpb.Struct(
192+
fields={"bar": structpb.Value(string_value="baz")}
193+
)
194+
)
195+
}
196+
),
197+
want={"foo": {"bar": "baz"}},
198+
),
199+
]
200+
201+
for case in cases:
202+
got = resource.struct_to_dict(case.s)
203+
self.assertEqual(case.want, got, "-want, +got")
204+
168205

169206
if __name__ == "__main__":
170207
unittest.main()

0 commit comments

Comments
 (0)