1
2
3
4
5 package proto_test
6
7 import (
8 "testing"
9
10 "github.com/golang/protobuf/proto"
11 "google.golang.org/protobuf/testing/protopack"
12
13 pb2 "github.com/golang/protobuf/internal/testprotos/proto2_proto"
14 pb3 "github.com/golang/protobuf/internal/testprotos/proto3_proto"
15 )
16
17 var rawFields = protopack.Message{
18 protopack.Tag{5, protopack.Fixed32Type}, protopack.Uint32(4041331395),
19 }.Marshal()
20
21 func TestDiscardUnknown(t *testing.T) {
22 tests := []struct {
23 desc string
24 in, want proto.Message
25 }{{
26 desc: "Nil",
27 in: nil, want: nil,
28 }, {
29 desc: "NilPtr",
30 in: (*pb3.Message)(nil), want: (*pb3.Message)(nil),
31 }, {
32 desc: "Nested",
33 in: &pb3.Message{
34 Name: "Aaron",
35 Nested: &pb3.Nested{Cute: true, XXX_unrecognized: []byte(rawFields)},
36 XXX_unrecognized: []byte(rawFields),
37 },
38 want: &pb3.Message{
39 Name: "Aaron",
40 Nested: &pb3.Nested{Cute: true},
41 },
42 }, {
43 desc: "Slice",
44 in: &pb3.Message{
45 Name: "Aaron",
46 Children: []*pb3.Message{
47 {Name: "Sarah", XXX_unrecognized: []byte(rawFields)},
48 {Name: "Abraham", XXX_unrecognized: []byte(rawFields)},
49 },
50 XXX_unrecognized: []byte(rawFields),
51 },
52 want: &pb3.Message{
53 Name: "Aaron",
54 Children: []*pb3.Message{
55 {Name: "Sarah"},
56 {Name: "Abraham"},
57 },
58 },
59 }, {
60 desc: "OneOf",
61 in: &pb2.Communique{
62 Union: &pb2.Communique_Msg{&pb2.Strings{
63 StringField: proto.String("123"),
64 XXX_unrecognized: []byte(rawFields),
65 }},
66 XXX_unrecognized: []byte(rawFields),
67 },
68 want: &pb2.Communique{
69 Union: &pb2.Communique_Msg{&pb2.Strings{StringField: proto.String("123")}},
70 },
71 }, {
72 desc: "Map",
73 in: &pb2.MessageWithMap{MsgMapping: map[int64]*pb2.FloatingPoint{
74 0x4002: &pb2.FloatingPoint{
75 Exact: proto.Bool(true),
76 XXX_unrecognized: []byte(rawFields),
77 },
78 }},
79 want: &pb2.MessageWithMap{MsgMapping: map[int64]*pb2.FloatingPoint{
80 0x4002: &pb2.FloatingPoint{Exact: proto.Bool(true)},
81 }},
82 }, {
83 desc: "Extension",
84 in: func() proto.Message {
85 m := &pb2.MyMessage{
86 Count: proto.Int32(42),
87 Somegroup: &pb2.MyMessage_SomeGroup{
88 GroupField: proto.Int32(6),
89 XXX_unrecognized: []byte(rawFields),
90 },
91 XXX_unrecognized: []byte(rawFields),
92 }
93 proto.SetExtension(m, pb2.E_Ext_More, &pb2.Ext{
94 Data: proto.String("extension"),
95 XXX_unrecognized: []byte(rawFields),
96 })
97 return m
98 }(),
99 want: func() proto.Message {
100 m := &pb2.MyMessage{
101 Count: proto.Int32(42),
102 Somegroup: &pb2.MyMessage_SomeGroup{GroupField: proto.Int32(6)},
103 }
104 proto.SetExtension(m, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("extension")})
105 return m
106 }(),
107 }}
108
109 for _, tt := range tests {
110 proto.DiscardUnknown(tt.in)
111 if !proto.Equal(tt.in, tt.want) {
112 t.Errorf("test %s, expected unknown fields to be discarded\ngot %v\nwant %v", tt.desc, tt.in, tt.want)
113 }
114 }
115 }
116
View as plain text