From fef798343c635728ed82e1d8f9afa8e719e1b7ba Mon Sep 17 00:00:00 2001 From: Dov Shlachter Date: Tue, 3 Nov 2020 12:58:07 -0800 Subject: [PATCH] test: unknown fields are preserved (#160) * test: unknown fields are preserved Consider the following: ```proto message Old { string name = 1; } message New { string name = 1; string path = 2; } ``` We can think of `New` as being a minor version release update of `Old`. If a client using the older version receives a message over the wire from a server using the newer version, it is desirable that any new, unknown fields are preserved. These can store context the server needs, which is important in get/modify/set loops. --- proto/message.py | 1 - tests/test_message.py | 22 ++++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/proto/message.py b/proto/message.py index f1c3bbbe..08e6623f 100644 --- a/proto/message.py +++ b/proto/message.py @@ -155,7 +155,6 @@ def __new__(mcls, name, bases, attrs): # Same thing, but for enums. elif field.enum and not isinstance(field.enum, str): - field_enum = field.enum field_enum = ( field.enum._meta.pb if hasattr(field.enum, "_meta") diff --git a/tests/test_message.py b/tests/test_message.py index 32a61802..b723fcde 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -285,6 +285,28 @@ class Octopus_New(proto.Message): assert not hasattr(o_old, "length_cm") +def test_unknown_field_deserialize_keep_fields(): + # This is a somewhat common setup: a client uses an older proto definition, + # while the server sends the newer definition. The client still needs to be + # able to interact with the protos it receives from the server. + + class Octopus_Old(proto.Message): + mass_kg = proto.Field(proto.INT32, number=1) + + class Octopus_New(proto.Message): + mass_kg = proto.Field(proto.INT32, number=1) + length_cm = proto.Field(proto.INT32, number=2) + + o_new = Octopus_New(mass_kg=20, length_cm=100) + o_ser = Octopus_New.serialize(o_new) + + o_old = Octopus_Old.deserialize(o_ser) + assert not hasattr(o_old, "length_cm") + + o_new = Octopus_New.deserialize(Octopus_Old.serialize(o_old)) + assert o_new.length_cm == 100 + + def test_unknown_field_from_dict(): class Squid(proto.Message): mass_kg = proto.Field(proto.INT32, number=1)