3 * Copyright 2014 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
26 "google.golang.org/grpc/test/codec_perf"
29 func marshalAndUnmarshal(t *testing.T, protoCodec Codec, expectedBody []byte) {
30 p := &codec_perf.Buffer{}
33 marshalledBytes, err := protoCodec.Marshal(p)
35 t.Errorf("protoCodec.Marshal(_) returned an error")
38 if err := protoCodec.Unmarshal(marshalledBytes, p); err != nil {
39 t.Errorf("protoCodec.Unmarshal(_) returned an error")
42 if bytes.Compare(p.GetBody(), expectedBody) != 0 {
43 t.Errorf("Unexpected body; got %v; want %v", p.GetBody(), expectedBody)
47 func TestBasicProtoCodecMarshalAndUnmarshal(t *testing.T) {
48 marshalAndUnmarshal(t, protoCodec{}, []byte{1, 2, 3})
51 // Try to catch possible race conditions around use of pools
52 func TestConcurrentUsage(t *testing.T) {
55 numMarshUnmarsh = 1000
58 // small, arbitrary byte slices
59 protoBodies := [][]byte{
70 for i := 0; i < numGoRoutines; i++ {
74 for k := 0; k < numMarshUnmarsh; k++ {
75 marshalAndUnmarshal(t, codec, protoBodies[k%len(protoBodies)])
83 // TestStaggeredMarshalAndUnmarshalUsingSamePool tries to catch potential errors in which slices get
84 // stomped on during reuse of a proto.Buffer.
85 func TestStaggeredMarshalAndUnmarshalUsingSamePool(t *testing.T) {
86 codec1 := protoCodec{}
87 codec2 := protoCodec{}
89 expectedBody1 := []byte{1, 2, 3}
90 expectedBody2 := []byte{4, 5, 6}
92 proto1 := codec_perf.Buffer{Body: expectedBody1}
93 proto2 := codec_perf.Buffer{Body: expectedBody2}
98 if m1, err = codec1.Marshal(&proto1); err != nil {
99 t.Errorf("protoCodec.Marshal(%v) failed", proto1)
102 if m2, err = codec2.Marshal(&proto2); err != nil {
103 t.Errorf("protoCodec.Marshal(%v) failed", proto2)
106 if err = codec1.Unmarshal(m1, &proto1); err != nil {
107 t.Errorf("protoCodec.Unmarshal(%v) failed", m1)
110 if err = codec2.Unmarshal(m2, &proto2); err != nil {
111 t.Errorf("protoCodec.Unmarshal(%v) failed", m2)
114 b1 := proto1.GetBody()
115 b2 := proto2.GetBody()
117 for i, v := range b1 {
118 if expectedBody1[i] != v {
119 t.Errorf("expected %v at index %v but got %v", i, expectedBody1[i], v)
123 for i, v := range b2 {
124 if expectedBody2[i] != v {
125 t.Errorf("expected %v at index %v but got %v", i, expectedBody2[i], v)