From 307fcbf4e71fe32585f2bc3138231f6de43681ed Mon Sep 17 00:00:00 2001 From: Jason Paryani Date: Tue, 18 Feb 2014 17:34:34 -0800 Subject: [PATCH] Fix problem with uninitialized unions in _from_dict --- capnp/lib/capnp.pyx | 7 ++++++- test/addressbook.capnp | 7 ++++++- test/test_struct.py | 6 ++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/capnp/lib/capnp.pyx b/capnp/lib/capnp.pyx index 525c653..88bd7e9 100644 --- a/capnp/lib/capnp.pyx +++ b/capnp/lib/capnp.pyx @@ -741,7 +741,12 @@ cdef _to_dict(msg, bint verbose): cdef _from_dict(_DynamicStructBuilder msg, dict d): for key, val in d.iteritems(): if key != 'which': - msg._set(key, val) + try: + msg._set(key, val) + except Exception as e: + if 'expected isSetInUnion(field)' in str(e): + msg.init(key) + msg._set(key, val) cdef _from_list(_DynamicListBuilder msg, list d): cdef size_t count = 0 diff --git a/test/addressbook.capnp b/test/addressbook.capnp index e1cd77c..b50b68b 100644 --- a/test/addressbook.capnp +++ b/test/addressbook.capnp @@ -21,13 +21,18 @@ struct Person { employment :union { unemployed @4 :Void; - employer @5 :Text; + employer @5 :Employer; school @6 :Text; selfEmployed @7 :Void; # We assume that a person is only one of these. } } +struct Employer { + name @0 :Text; + boss @1 :Person; +} + struct AddressBook { people @0 :List(Person); } diff --git a/test/test_struct.py b/test/test_struct.py index 51533d7..f73e4f2 100644 --- a/test/test_struct.py +++ b/test/test_struct.py @@ -164,3 +164,9 @@ def test_set_dict(all_types): msg.structList[0] = {'int32Field': 102} assert msg.structList[0].int32Field == 102 + + +def test_set_dict_union(addressbook): + person = addressbook.Person.new_message(**{'employment': {'employer': {'name': 'foo'}}}) + + assert person.employment.employer.name == 'foo'