trpc.group/trpc-go/trpc-go@v1.0.3/codec/codec_test.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package codec_test
    15  
    16  import (
    17  	"context"
    18  	"testing"
    19  
    20  	"github.com/stretchr/testify/assert"
    21  
    22  	"trpc.group/trpc-go/trpc-go/codec"
    23  )
    24  
    25  // go test -v -coverprofile=cover.out
    26  // go tool cover -func=cover.out
    27  
    28  // Fake is a fake codec for test
    29  type Fake struct {
    30  }
    31  
    32  func (c *Fake) Encode(message codec.Msg, inbody []byte) (outbuf []byte, err error) {
    33  	return nil, nil
    34  }
    35  
    36  func (c *Fake) Decode(message codec.Msg, inbuf []byte) (outbody []byte, err error) {
    37  	return nil, nil
    38  }
    39  
    40  // TestCodec is unit test for the register logic of codec.
    41  func TestCodec(t *testing.T) {
    42  	f := &Fake{}
    43  
    44  	codec.Register("fake", f, f)
    45  
    46  	serverCodec := codec.GetServer("NoExists")
    47  	assert.Nil(t, serverCodec)
    48  
    49  	clientCodec := codec.GetClient("NoExists")
    50  	assert.Nil(t, clientCodec)
    51  
    52  	serverCodec = codec.GetServer("fake")
    53  	assert.Equal(t, f, serverCodec)
    54  
    55  	clientCodec = codec.GetClient("fake")
    56  	assert.Equal(t, f, clientCodec)
    57  }
    58  
    59  // GOMAXPROCS=1 go test -bench=WithNewMessage -benchmem -benchtime=10s
    60  // -memprofile mem.out -cpuprofile cpu.out codec_test.go
    61  
    62  // BenchmarkWithNewMessage is the benchmark test of codec
    63  func BenchmarkWithNewMessage(b *testing.B) {
    64  	for i := 0; i < b.N; i++ {
    65  		codec.WithNewMessage(context.Background())
    66  	}
    67  }