blob: d467b74da220f848669d7d3667dfc4f10ad10acd [file] [log] [blame]
Damien Neil99f24c32019-03-13 17:06:42 -07001package proto_test
2
3import (
4 "bytes"
5 "fmt"
6 "reflect"
7 "testing"
8
9 protoV1 "github.com/golang/protobuf/proto"
Damien Neil99f24c32019-03-13 17:06:42 -070010 "github.com/golang/protobuf/v2/proto"
11 "github.com/google/go-cmp/cmp"
12)
13
14func TestEncode(t *testing.T) {
15 for _, test := range testProtos {
16 for _, want := range test.decodeTo {
17 t.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(t *testing.T) {
18 wire, err := proto.Marshal(want)
19 if err != nil {
Damien Neil61e93c72019-03-27 09:23:20 -070020 t.Fatalf("Marshal error: %v\nMessage:\n%v", err, marshalText(want))
21 }
22
23 size := proto.Size(want)
24 if size != len(wire) {
25 t.Errorf("Size and marshal disagree: Size(m)=%v; len(Marshal(m))=%v\nMessage:\n%v", size, len(wire), marshalText(want))
Damien Neil99f24c32019-03-13 17:06:42 -070026 }
27
28 got := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message)
29 if err := proto.Unmarshal(wire, got); err != nil {
30 t.Errorf("Unmarshal error: %v\nMessage:\n%v", err, protoV1.MarshalTextString(want.(protoV1.Message)))
31 return
32 }
33
34 if !protoV1.Equal(got.(protoV1.Message), want.(protoV1.Message)) {
35 t.Errorf("Unmarshal returned unexpected result; got:\n%v\nwant:\n%v", protoV1.MarshalTextString(got.(protoV1.Message)), protoV1.MarshalTextString(want.(protoV1.Message)))
36 }
37 })
38 }
39 }
40}
41
42func TestEncodeDeterministic(t *testing.T) {
43 for _, test := range testProtos {
44 for _, want := range test.decodeTo {
45 t.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(t *testing.T) {
46 wire, err := proto.MarshalOptions{Deterministic: true}.Marshal(want)
47 if err != nil {
Damien Neil61e93c72019-03-27 09:23:20 -070048 t.Fatalf("Marshal error: %v\nMessage:\n%v", err, marshalText(want))
Damien Neil99f24c32019-03-13 17:06:42 -070049 }
50
51 wire2, err := proto.MarshalOptions{Deterministic: true}.Marshal(want)
52 if err != nil {
Damien Neil61e93c72019-03-27 09:23:20 -070053 t.Fatalf("Marshal error: %v\nMessage:\n%v", err, marshalText(want))
Damien Neil99f24c32019-03-13 17:06:42 -070054 }
55
56 if !bytes.Equal(wire, wire2) {
57 t.Fatalf("deterministic marshal returned varying results:\n%v", cmp.Diff(wire, wire2))
58 }
59
60 got := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message)
61 if err := proto.Unmarshal(wire, got); err != nil {
Damien Neil61e93c72019-03-27 09:23:20 -070062 t.Errorf("Unmarshal error: %v\nMessage:\n%v", err, marshalText(want))
Damien Neil99f24c32019-03-13 17:06:42 -070063 return
64 }
65
66 if !protoV1.Equal(got.(protoV1.Message), want.(protoV1.Message)) {
Damien Neil61e93c72019-03-27 09:23:20 -070067 t.Errorf("Unmarshal returned unexpected result; got:\n%v\nwant:\n%v", marshalText(got), marshalText(want))
Damien Neil99f24c32019-03-13 17:06:42 -070068 }
69 })
70 }
71 }
72}