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

     1  package auth
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  	"google.golang.org/grpc/metadata"
     9  )
    10  
    11  func TestParseCredential(t *testing.T) {
    12  	tests := []struct {
    13  		name        string
    14  		withNil     bool
    15  		withEmptyMd bool
    16  		app         string
    17  		token       string
    18  	}{
    19  		{
    20  			name:    "nil",
    21  			withNil: true,
    22  		},
    23  		{
    24  			name:        "empty md",
    25  			withEmptyMd: true,
    26  		},
    27  		{
    28  			name: "empty",
    29  		},
    30  		{
    31  			name:  "valid",
    32  			app:   "foo",
    33  			token: "bar",
    34  		},
    35  	}
    36  
    37  	for _, test := range tests {
    38  		test := test
    39  		t.Run(test.name, func(t *testing.T) {
    40  			t.Parallel()
    41  
    42  			var ctx context.Context
    43  			if test.withNil {
    44  				ctx = context.Background()
    45  			} else if test.withEmptyMd {
    46  				ctx = metadata.NewIncomingContext(context.Background(), metadata.MD{})
    47  			} else {
    48  				md := metadata.New(map[string]string{
    49  					"app":   test.app,
    50  					"token": test.token,
    51  				})
    52  				ctx = metadata.NewIncomingContext(context.Background(), md)
    53  			}
    54  			cred := ParseCredential(ctx)
    55  			assert.False(t, cred.RequireTransportSecurity())
    56  			m, err := cred.GetRequestMetadata(context.Background())
    57  			assert.Nil(t, err)
    58  			assert.Equal(t, test.app, m[appKey])
    59  			assert.Equal(t, test.token, m[tokenKey])
    60  		})
    61  	}
    62  }