From 45198b5115ca1fdc745710459bf4188f70d0f91e Mon Sep 17 00:00:00 2001 From: Renat Mennanov Date: Fri, 3 Sep 2021 14:19:30 -0700 Subject: [PATCH] Fixes #21: incorrect behavior with Anypb. --- copy.go | 21 ++++++++++++--------- copy_proto_test.go | 6 ++++-- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/copy.go b/copy.go index 022e6bc..9ec304f 100644 --- a/copy.go +++ b/copy.go @@ -84,33 +84,36 @@ func structToStruct(filter FieldFilter, src, dst *reflect.Value, userOptions *op } if srcAny, ok := src.Interface().(*anypb.Any); ok { - dstAny, ok := src.Interface().(*anypb.Any) + dstAny, ok := dst.Interface().(*anypb.Any) if !ok { return errors.Errorf("dst type is %s, expected: %s ", dst.Type(), "*any.Any") } - newSrcProto, err := srcAny.UnmarshalNew() + srcProto, err := srcAny.UnmarshalNew() if err != nil { return errors.WithStack(err) } - newSrc := reflect.ValueOf(newSrcProto) + srcProtoValue := reflect.ValueOf(srcProto) - newDstProto, err := dstAny.UnmarshalNew() + if dstAny.GetTypeUrl() == "" { + dstAny.TypeUrl = srcAny.GetTypeUrl() + } + dstProto, err := dstAny.UnmarshalNew() if err != nil { return errors.WithStack(err) } - newDst := reflect.ValueOf(newDstProto) + dstProtoValue := reflect.ValueOf(dstProto) - if err := structToStruct(filter, &newSrc, &newDst, userOptions); err != nil { + if err := structToStruct(filter, &srcProtoValue, &dstProtoValue, userOptions); err != nil { return err } - newSrcAny := new(anypb.Any) - if err := newSrcAny.MarshalFrom(newDst.Interface().(proto.Message)); err != nil { + newDstAny := new(anypb.Any) + if err := newDstAny.MarshalFrom(dstProtoValue.Interface().(proto.Message)); err != nil { return errors.WithStack(err) } - dst.Set(reflect.ValueOf(newSrcAny)) + dst.Set(reflect.ValueOf(newDstAny)) break } diff --git a/copy_proto_test.go b/copy_proto_test.go index 03d786d..573eece 100644 --- a/copy_proto_test.go +++ b/copy_proto_test.go @@ -129,7 +129,8 @@ func TestStructToStruct_Proto(t *testing.T) { func TestStructToStruct_ExistingAnyPreserved(t *testing.T) { existingExtraUser := &testproto.User{ Id: 42, - Username: "username", + Username: "emily", + Role: testproto.Role_REGULAR, } existingExtraUserAny, err := anypb.New(existingExtraUser) require.NoError(t, err) @@ -145,7 +146,8 @@ func TestStructToStruct_ExistingAnyPreserved(t *testing.T) { require.NoError(t, err) assert.Equal(t, testUserFull.Id, extraUser.Id) assert.Equal(t, testUserFull.Avatar.OriginalUrl, extraUser.Avatar.OriginalUrl) - assert.Equal(t, "username", extraUser.Username) + assert.Equal(t, existingExtraUser.Username, extraUser.Username) + assert.Equal(t, existingExtraUser.Role, extraUser.Role) } func TestStructToStruct_PartialProtoSuccess(t *testing.T) {