methods_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // 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. // The protoreflect tag disables fast-path methods, including legacy ones.
  5. // +build !protoreflect
  6. package proto_test
  7. import (
  8. "bytes"
  9. "errors"
  10. "fmt"
  11. "testing"
  12. "google.golang.org/protobuf/internal/impl"
  13. "google.golang.org/protobuf/proto"
  14. )
  15. type selfMarshaler struct {
  16. bytes []byte
  17. err error
  18. }
  19. func (m selfMarshaler) Reset() {}
  20. func (m selfMarshaler) ProtoMessage() {}
  21. func (m selfMarshaler) String() string {
  22. return fmt.Sprintf("selfMarshaler{bytes:%v, err:%v}", m.bytes, m.err)
  23. }
  24. func (m selfMarshaler) Marshal() ([]byte, error) {
  25. return m.bytes, m.err
  26. }
  27. func (m *selfMarshaler) Unmarshal(b []byte) error {
  28. m.bytes = b
  29. return m.err
  30. }
  31. func TestLegacyMarshalMethod(t *testing.T) {
  32. for _, test := range []selfMarshaler{
  33. {bytes: []byte("marshal")},
  34. {bytes: []byte("marshal"), err: errors.New("some error")},
  35. } {
  36. m := impl.Export{}.MessageOf(test).Interface()
  37. b, err := proto.Marshal(m)
  38. if err != test.err || !bytes.Equal(b, test.bytes) {
  39. t.Errorf("proto.Marshal(%v) = %v, %v; want %v, %v", test, b, err, test.bytes, test.err)
  40. }
  41. if gotSize, wantSize := proto.Size(m), len(test.bytes); gotSize != wantSize {
  42. t.Fatalf("proto.Size(%v) = %v, want %v", test, gotSize, wantSize)
  43. }
  44. prefix := []byte("prefix")
  45. want := append(prefix, test.bytes...)
  46. b, err = proto.MarshalOptions{}.MarshalAppend(prefix, m)
  47. if err != test.err || !bytes.Equal(b, want) {
  48. t.Errorf("MarshalAppend(%v, %v) = %v, %v; want %v, %v", prefix, test, b, err, test.bytes, test.err)
  49. }
  50. }
  51. }
  52. func TestLegacyUnmarshalMethod(t *testing.T) {
  53. sm := &selfMarshaler{}
  54. m := impl.Export{}.MessageOf(sm).Interface()
  55. want := []byte("unmarshal")
  56. if err := proto.Unmarshal(want, m); err != nil {
  57. t.Fatalf("proto.Unmarshal(selfMarshaler{}) = %v, want nil", err)
  58. }
  59. if !bytes.Equal(sm.bytes, want) {
  60. t.Fatalf("proto.Unmarshal(selfMarshaler{}): Marshal method not called")
  61. }
  62. }