github.com/gogo/protobuf@v1.3.2/test/issue411/ids_test.go (about) 1 package issue411_test 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/gogo/protobuf/jsonpb" 8 "github.com/gogo/protobuf/proto" 9 "github.com/gogo/protobuf/test/issue411" 10 ) 11 12 // Thanks to @yurishkuro for reporting this issue (#411) and providing this test case 13 14 // TraceID/SpanID fields are defined as bytes in proto, backed by custom types in Go. 15 // Unfortunately, that means they require manual implementations of proto & json serialization. 16 // To ensure that it's the same as the default protobuf serialization, file jaeger_test.proto 17 // contains a copy of SpanRef message without any gogo options. This test file is compiled with 18 // plain protoc -go_out (without gogo). This test performs proto and JSON marshaling/unmarshaling 19 // to ensure that the outputs of manual and standard serialization are identical. 20 func TestTraceSpanIDMarshalProto(t *testing.T) { 21 testCases := []struct { 22 name string 23 marshal func(proto.Message) ([]byte, error) 24 unmarshal func([]byte, proto.Message) error 25 expected string 26 }{ 27 { 28 name: "protobuf", 29 marshal: proto.Marshal, 30 unmarshal: proto.Unmarshal, 31 }, 32 { 33 name: "JSON", 34 marshal: func(m proto.Message) ([]byte, error) { 35 out := new(bytes.Buffer) 36 err := new(jsonpb.Marshaler).Marshal(out, m) 37 if err != nil { 38 return nil, err 39 } 40 return out.Bytes(), nil 41 }, 42 unmarshal: func(in []byte, m proto.Message) error { 43 return jsonpb.Unmarshal(bytes.NewReader(in), m) 44 }, 45 expected: `{"traceId":"AAAAAAAAAAIAAAAAAAAAAw==","spanId":"AAAAAAAAAAs="}`, 46 }, 47 } 48 for _, testCase := range testCases { 49 t.Run(testCase.name, func(t *testing.T) { 50 o1 := issue411.Span{TraceID: issue411.NewTraceID(2, 3), SpanID: issue411.NewSpanID(11)} 51 d1, err := testCase.marshal(&o1) 52 if err != nil { 53 t.Fatalf("marshal error: %v", err) 54 } 55 // test unmarshal 56 var o2 issue411.Span 57 err = testCase.unmarshal(d1, &o2) 58 if err != nil { 59 t.Fatalf("umarshal error: %v", err) 60 } 61 if o1.TraceID != o2.TraceID { 62 t.Fatalf("TraceID: expected %v but got %v", o1, o2) 63 } 64 if o1.SpanID != o2.SpanID { 65 t.Fatalf("SpanID: expected %v but got %v", o1, o2) 66 } 67 }) 68 } 69 }