From e356025cef4f0d7353b0caafb5336f46ca5f610d Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 7 Oct 2020 08:11:20 +0800 Subject: [PATCH] add more tests --- zrpc/internal/auth/auth_test.go | 84 +++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 zrpc/internal/auth/auth_test.go diff --git a/zrpc/internal/auth/auth_test.go b/zrpc/internal/auth/auth_test.go new file mode 100644 index 00000000..0da64d2f --- /dev/null +++ b/zrpc/internal/auth/auth_test.go @@ -0,0 +1,84 @@ +package auth + +import ( + "context" + "testing" + + "github.com/alicebob/miniredis" + "github.com/stretchr/testify/assert" + "github.com/tal-tech/go-zero/core/stores/redis" + "google.golang.org/grpc/metadata" +) + +func TestAuthenticator(t *testing.T) { + tests := []struct { + name string + app string + token string + strict bool + hasError bool + }{ + { + name: "strict=false", + strict: false, + hasError: false, + }, + { + name: "strict=true", + strict: true, + hasError: true, + }, + { + name: "strict=true,with token", + app: "foo", + token: "bar", + strict: true, + hasError: false, + }, + { + name: "strict=true,with error token", + app: "foo", + token: "error", + strict: true, + hasError: true, + }, + } + + r := miniredis.NewMiniRedis() + assert.Nil(t, r.Start()) + defer r.Close() + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + store := redis.NewRedis(r.Addr(), redis.NodeType) + if len(test.app) > 0 { + assert.Nil(t, store.Hset("apps", test.app, test.token)) + defer store.Hdel("apps", test.app) + } + + authenticator, err := NewAuthenticator(store, "apps", test.strict) + assert.Nil(t, err) + assert.NotNil(t, authenticator.Authenticate(context.Background())) + md := metadata.New(map[string]string{}) + ctx := metadata.NewIncomingContext(context.Background(), md) + assert.NotNil(t, authenticator.Authenticate(ctx)) + md = metadata.New(map[string]string{ + "app": "", + "token": "", + }) + ctx = metadata.NewIncomingContext(context.Background(), md) + assert.NotNil(t, authenticator.Authenticate(ctx)) + md = metadata.New(map[string]string{ + "app": "foo", + "token": "bar", + }) + ctx = metadata.NewIncomingContext(context.Background(), md) + err = authenticator.Authenticate(ctx) + if test.hasError { + assert.NotNil(t, err) + } else { + assert.Nil(t, err) + } + }) + } +}