github.com/lingyao2333/mo-zero@v1.4.1/zrpc/internal/auth/auth_test.go (about)

     1  package auth
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/lingyao2333/mo-zero/core/stores/redis/redistest"
     8  	"github.com/stretchr/testify/assert"
     9  	"google.golang.org/grpc/metadata"
    10  )
    11  
    12  func TestAuthenticator(t *testing.T) {
    13  	tests := []struct {
    14  		name     string
    15  		app      string
    16  		token    string
    17  		strict   bool
    18  		hasError bool
    19  	}{
    20  		{
    21  			name:     "strict=false",
    22  			strict:   false,
    23  			hasError: false,
    24  		},
    25  		{
    26  			name:     "strict=true",
    27  			strict:   true,
    28  			hasError: true,
    29  		},
    30  		{
    31  			name:     "strict=true,with token",
    32  			app:      "foo",
    33  			token:    "bar",
    34  			strict:   true,
    35  			hasError: false,
    36  		},
    37  		{
    38  			name:     "strict=true,with error token",
    39  			app:      "foo",
    40  			token:    "error",
    41  			strict:   true,
    42  			hasError: true,
    43  		},
    44  	}
    45  
    46  	store, clean, err := redistest.CreateRedis()
    47  	assert.Nil(t, err)
    48  	defer clean()
    49  
    50  	for _, test := range tests {
    51  		t.Run(test.name, func(t *testing.T) {
    52  			if len(test.app) > 0 {
    53  				assert.Nil(t, store.Hset("apps", test.app, test.token))
    54  				defer store.Hdel("apps", test.app)
    55  			}
    56  
    57  			authenticator, err := NewAuthenticator(store, "apps", test.strict)
    58  			assert.Nil(t, err)
    59  			assert.NotNil(t, authenticator.Authenticate(context.Background()))
    60  			md := metadata.New(map[string]string{})
    61  			ctx := metadata.NewIncomingContext(context.Background(), md)
    62  			assert.NotNil(t, authenticator.Authenticate(ctx))
    63  			md = metadata.New(map[string]string{
    64  				"app":   "",
    65  				"token": "",
    66  			})
    67  			ctx = metadata.NewIncomingContext(context.Background(), md)
    68  			assert.NotNil(t, authenticator.Authenticate(ctx))
    69  			md = metadata.New(map[string]string{
    70  				"app":   "foo",
    71  				"token": "bar",
    72  			})
    73  			ctx = metadata.NewIncomingContext(context.Background(), md)
    74  			err = authenticator.Authenticate(ctx)
    75  			if test.hasError {
    76  				assert.NotNil(t, err)
    77  			} else {
    78  				assert.Nil(t, err)
    79  			}
    80  		})
    81  	}
    82  }