blob: 436df6df06a728c0c0652b2919324fbcb4910b83 [file] [log] [blame]
Damien Neil37ef6912019-09-25 16:51:15 -07001// Copyright 2019 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// The protoreflect tag disables fast-path methods, including legacy ones.
6// +build !protoreflect
7
8package proto_test
9
10import (
11 "bytes"
12 "errors"
13 "fmt"
14 "testing"
15
16 "google.golang.org/protobuf/internal/impl"
17 "google.golang.org/protobuf/proto"
18)
19
20type selfMarshaler struct {
21 bytes []byte
22 err error
23}
24
25func (m selfMarshaler) Reset() {}
26func (m selfMarshaler) ProtoMessage() {}
27
28func (m selfMarshaler) String() string {
29 return fmt.Sprintf("selfMarshaler{bytes:%v, err:%v}", m.bytes, m.err)
30}
31
32func (m selfMarshaler) Marshal() ([]byte, error) {
33 return m.bytes, m.err
34}
35
36func (m *selfMarshaler) Unmarshal(b []byte) error {
37 m.bytes = b
38 return m.err
39}
40
41func TestLegacyMarshalMethod(t *testing.T) {
42 for _, test := range []*selfMarshaler{
43 {bytes: []byte("marshal")},
44 {bytes: []byte("marshal"), err: errors.New("some error")},
45 } {
46 m := impl.Export{}.MessageOf(test).Interface()
47 b, err := proto.Marshal(m)
48 if err != test.err || !bytes.Equal(b, test.bytes) {
49 t.Errorf("proto.Marshal(%v) = %v, %v; want %v, %v", test, b, err, test.bytes, test.err)
50 }
51 if gotSize, wantSize := proto.Size(m), len(test.bytes); gotSize != wantSize {
52 t.Fatalf("proto.Size(%v) = %v, want %v", test, gotSize, wantSize)
53 }
54
55 prefix := []byte("prefix")
56 want := append(prefix, test.bytes...)
57 b, err = proto.MarshalOptions{}.MarshalAppend(prefix, m)
58 if err != test.err || !bytes.Equal(b, want) {
59 t.Errorf("MarshalAppend(%v, %v) = %v, %v; want %v, %v", prefix, test, b, err, test.bytes, test.err)
60 }
61 }
62}
63
64func TestLegacyUnmarshalMethod(t *testing.T) {
65 sm := &selfMarshaler{}
66 m := impl.Export{}.MessageOf(sm).Interface()
67 want := []byte("unmarshal")
68 if err := proto.Unmarshal(want, m); err != nil {
69 t.Fatalf("proto.Unmarshal(selfMarshaler{}) = %v, want nil", err)
70 }
71 if !bytes.Equal(sm.bytes, want) {
72 t.Fatalf("proto.Unmarshal(selfMarshaler{}): Marshal method not called")
73 }
74}