feat (package share): add unit test

package share unit test coverage is above 70% now
This commit is contained in:
xusworld
2020-12-17 16:06:27 +08:00
parent 39de745529
commit 679373edb8
2 changed files with 64 additions and 14 deletions

View File

@@ -5,40 +5,63 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"go.opencensus.io/trace"
)
var (
TheAnswer = "Answer to the Ultimate Question of Life, the Universe, and Everything"
TheAnswer = "Answer to the Ultimate Question of Life, the Universe, and Everything"
MagicNumber = 42
)
func TestNewContext(t *testing.T) {
func TestContext(t *testing.T) {
rpcxContext := NewContext(context.Background())
assert.NotNil(t, rpcxContext.Context)
assert.NotNil(t, rpcxContext.tags)
}
func TestContext_SetValue(t *testing.T) {
rpcxContext := NewContext(context.Background())
rpcxContext.SetValue("string", TheAnswer)
rpcxContext.SetValue(42, MagicNumber)
assert.Equal(t, MagicNumber, rpcxContext.Value(42))
assert.Equal(t, TheAnswer, rpcxContext.Value("string"))
}
func TestContext_String(t *testing.T) {
rpcxContext := NewContext(context.Background())
rpcxContext.SetValue("string", TheAnswer)
t.Log(rpcxContext.String())
}
func TestWithValue(t *testing.T) {
func TestGetOpencensusSpanContextFromContext(t *testing.T) {
var ctx Context
ctx.SetValue("key", "value")
ctx.SetValue(ReqMetaDataKey, make(map[string]string))
spanCtx, err := GetOpencensusSpanContextFromContext(&ctx)
assert.Nil(t, spanCtx)
assert.Equal(t, "key not found", err.Error())
PI := "3141592653589793238462643383279"
ctx.SetValue(ReqMetaDataKey, map[string]string{
OpencensusSpanRequestKey: PI,
})
spanCtx, err = GetOpencensusSpanContextFromContext(&ctx)
var exceptTraceID [16]byte
copy(exceptTraceID[:], []byte(PI)[:16])
assert.Equal(t, trace.TraceID(exceptTraceID), spanCtx.TraceID)
assert.Nil(t, err)
}
func TestWithValue(t *testing.T) {
ctx := WithValue(context.Background(), "key", "value")
assert.NotNil(t, ctx.tags)
}
func TestWithLocalValue(t *testing.T) {
var c Context
c.SetValue("key", "value")
ctx := WithLocalValue(&c, "MagicNumber", "42")
assert.Equal(t, "value", ctx.tags["key"])
assert.Equal(t, "42", ctx.tags["MagicNumber"])
}

27
share/share_test.go Normal file
View File

@@ -0,0 +1,27 @@
package share
import (
"testing"
"github.com/smallnest/rpcx/protocol"
"github.com/stretchr/testify/assert"
)
type MockCodec struct {}
func (codec MockCodec) Encode(i interface{}) ([]byte, error) {
return nil, nil
}
func (codec MockCodec) Decode(data []byte, i interface{}) error {
return nil
}
func TestShare(t *testing.T) {
registeredCodecNum := len(Codecs)
codec := MockCodec{}
mockCodecType := 127
RegisterCodec(protocol.SerializeType(mockCodecType), codec)
assert.Equal(t, registeredCodecNum + 1, len(Codecs))
}