Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame^] | 1 | package proto_test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "reflect" |
| 7 | "testing" |
| 8 | |
| 9 | protoV1 "github.com/golang/protobuf/proto" |
| 10 | //_ "github.com/golang/protobuf/v2/internal/legacy" |
| 11 | "github.com/golang/protobuf/v2/proto" |
| 12 | "github.com/google/go-cmp/cmp" |
| 13 | ) |
| 14 | |
| 15 | func TestEncode(t *testing.T) { |
| 16 | for _, test := range testProtos { |
| 17 | for _, want := range test.decodeTo { |
| 18 | t.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(t *testing.T) { |
| 19 | wire, err := proto.Marshal(want) |
| 20 | if err != nil { |
| 21 | t.Fatalf("Marshal error: %v\nMessage:\n%v", err, protoV1.MarshalTextString(want.(protoV1.Message))) |
| 22 | } |
| 23 | |
| 24 | got := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message) |
| 25 | if err := proto.Unmarshal(wire, got); err != nil { |
| 26 | t.Errorf("Unmarshal error: %v\nMessage:\n%v", err, protoV1.MarshalTextString(want.(protoV1.Message))) |
| 27 | return |
| 28 | } |
| 29 | |
| 30 | if !protoV1.Equal(got.(protoV1.Message), want.(protoV1.Message)) { |
| 31 | t.Errorf("Unmarshal returned unexpected result; got:\n%v\nwant:\n%v", protoV1.MarshalTextString(got.(protoV1.Message)), protoV1.MarshalTextString(want.(protoV1.Message))) |
| 32 | } |
| 33 | }) |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func TestEncodeDeterministic(t *testing.T) { |
| 39 | for _, test := range testProtos { |
| 40 | for _, want := range test.decodeTo { |
| 41 | t.Run(fmt.Sprintf("%s (%T)", test.desc, want), func(t *testing.T) { |
| 42 | wire, err := proto.MarshalOptions{Deterministic: true}.Marshal(want) |
| 43 | if err != nil { |
| 44 | t.Fatalf("Marshal error: %v\nMessage:\n%v", err, protoV1.MarshalTextString(want.(protoV1.Message))) |
| 45 | } |
| 46 | |
| 47 | wire2, err := proto.MarshalOptions{Deterministic: true}.Marshal(want) |
| 48 | if err != nil { |
| 49 | t.Fatalf("Marshal error: %v\nMessage:\n%v", err, protoV1.MarshalTextString(want.(protoV1.Message))) |
| 50 | } |
| 51 | |
| 52 | if !bytes.Equal(wire, wire2) { |
| 53 | t.Fatalf("deterministic marshal returned varying results:\n%v", cmp.Diff(wire, wire2)) |
| 54 | } |
| 55 | |
| 56 | got := reflect.New(reflect.TypeOf(want).Elem()).Interface().(proto.Message) |
| 57 | if err := proto.Unmarshal(wire, got); err != nil { |
| 58 | t.Errorf("Unmarshal error: %v\nMessage:\n%v", err, protoV1.MarshalTextString(want.(protoV1.Message))) |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | if !protoV1.Equal(got.(protoV1.Message), want.(protoV1.Message)) { |
| 63 | t.Errorf("Unmarshal returned unexpected result; got:\n%v\nwant:\n%v", protoV1.MarshalTextString(got.(protoV1.Message)), protoV1.MarshalTextString(want.(protoV1.Message))) |
| 64 | } |
| 65 | }) |
| 66 | } |
| 67 | } |
| 68 | } |