encoding/textpb: marshal Any as regular message if unable to expand

If there are any kind of errors in trying to expand the Any message,
always fallback to marshaling it as regular message.  This makes it
consistent with V1 and C++ libs.

Change-Id: I007414c1767e682623c45d4dd8c82b9998f61781
Reviewed-on: https://go-review.googlesource.com/c/156257
Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
This commit is contained in:
Herbie Ong 2019-01-03 15:39:58 -08:00
parent f42b55ff8c
commit a94f78c0f0
2 changed files with 28 additions and 4 deletions

View File

@ -78,10 +78,7 @@ func (o MarshalOptions) marshalMessage(m pref.Message) (text.Value, error) {
// Return as is for nil or non-fatal error.
return msg, nerr.E
}
if err != protoregistry.NotFound {
return text.Value{}, err
}
// Continue on to marshal Any as a regular message if error is not found.
// For other errors, continue on to marshal Any as a regular message.
}
// Handle known fields.

View File

@ -5,6 +5,7 @@
package textpb_test
import (
"encoding/hex"
"math"
"strings"
"testing"
@ -66,6 +67,15 @@ func setExtension(m proto.Message, xd *protoapi.ExtensionDesc, val interface{})
knownFields.Set(wire.Number(xd.Field), pval)
}
// dhex decodes a hex-string and returns the bytes and panics if s is invalid.
func dhex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}
func TestMarshal(t *testing.T) {
tests := []struct {
desc string
@ -1050,6 +1060,23 @@ value: "\n\x13embedded inside Any\x12\x0b\n\tinception"
}
`,
wantErr: true,
}, {
desc: "google.protobuf.Any message with invalid value",
mo: func() textpb.MarshalOptions {
m := &pb2.Nested{}
resolver := preg.NewTypes(m.ProtoReflect().Type())
return textpb.MarshalOptions{Resolver: resolver}
}(),
input: func() proto.Message {
m := &pb2.Nested{}
return impl.Export{}.MessageOf(&anypb.Any{
TypeUrl: string(m.ProtoReflect().Type().FullName()),
Value: dhex("80"),
}).Interface()
}(),
want: `type_url: "pb2.Nested"
value: "\x80"
`,
}, {
desc: "google.protobuf.Any field",
mo: textpb.MarshalOptions{Resolver: preg.NewTypes()},