MCPcopy
hub / github.com/golang/protobuf / TestMarshalerEncoding

Function TestMarshalerEncoding

proto/proto_test.go:228–287  ·  view source on GitHub ↗

Simple tests for proto messages that implement the Marshaler interface.

(t *testing.T)

Source from the content-addressed store, hash-verified

226
227// Simple tests for proto messages that implement the Marshaler interface.
228func TestMarshalerEncoding(t *testing.T) {
229 tests := []struct {
230 name string
231 m proto.Message
232 want []byte
233 errType reflect.Type
234 }{
235 {
236 name: "Marshaler that fails",
237 m: &fakeMarshaler{
238 err: errors.New("some marshal err"),
239 b: []byte{5, 6, 7},
240 },
241 errType: reflect.TypeOf(errors.New("some marshal err")),
242 },
243 {
244 name: "Marshaler that fails with RequiredNotSetError",
245 m: &msgWithFakeMarshaler{
246 M: &fakeMarshaler{
247 err: &proto.RequiredNotSetError{},
248 b: []byte{5, 6, 7},
249 },
250 },
251 errType: reflect.TypeOf(&proto.RequiredNotSetError{}),
252 },
253 {
254 name: "Marshaler that succeeds",
255 m: &fakeMarshaler{
256 b: []byte{0, 1, 2, 3, 4, 127, 255},
257 },
258 want: []byte{0, 1, 2, 3, 4, 127, 255},
259 },
260 }
261 for _, test := range tests {
262 t.Run(test.name, func(t *testing.T) {
263 b := proto.NewBuffer(nil)
264 err := b.Marshal(test.m)
265 if reflect.TypeOf(err) != test.errType {
266 t.Errorf("got err %T(%v) wanted %T", err, err, test.errType)
267 }
268 if err != nil {
269 return // skip comparing output when marshal fails.
270 }
271 if !reflect.DeepEqual(test.want, b.Bytes()) {
272 t.Errorf("got bytes %v wanted %v", b.Bytes(), test.want)
273 }
274 if size := proto.Size(test.m); size != len(b.Bytes()) {
275 t.Errorf("Size(_) = %v, but marshaled to %v bytes", size, len(b.Bytes()))
276 }
277
278 m, mErr := proto.Marshal(test.m)
279 if !bytes.Equal(b.Bytes(), m) {
280 t.Errorf("Marshal returned %v, but (*Buffer).Marshal wrote %v", m, b.Bytes())
281 }
282 if !reflect.DeepEqual(err, mErr) {
283 t.Errorf("Marshal err = %v, but (*Buffer).Marshal returned %v", mErr, err)
284 }
285 })

Callers

nothing calls this directly

Calls 6

MarshalMethod · 0.95
BytesMethod · 0.95
NewBufferFunction · 0.92
SizeFunction · 0.92
MarshalFunction · 0.92
NewMethod · 0.45

Tested by

no test coverage detected