vitess.io/vitess@v0.16.2/go/vt/vtadmin/cluster/dynamic/cluster_test.go (about)

     1  package dynamic
     2  
     3  import (
     4  	"context"
     5  	"encoding/base32"
     6  	"encoding/base64"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestClusterFromString(t *testing.T) {
    14  	t.Parallel()
    15  
    16  	tests := []struct {
    17  		name       string
    18  		s          string
    19  		encoder    func(b []byte) string
    20  		expectedID string
    21  		shouldErr  bool
    22  	}{
    23  		{
    24  			name: "ok",
    25  			s: `{
    26  				"id": "dynamic_cluster",
    27  				"discovery": "dynamic",
    28  				"discovery-dynamic-discovery": "{\"vtctlds\": [ { \"host\": { \"fqdn\": \"localhost:15000\", \"hostname\": \"localhost:15999\" } } ], \"vtgates\": [ { \"host\": {\"hostname\": \"localhost:15991\" } } ] }"
    29  			}`,
    30  			expectedID: "dynamic_cluster",
    31  		},
    32  		{
    33  			name:      "empty id",
    34  			s:         `{"id": ""}`,
    35  			shouldErr: true,
    36  		},
    37  		{
    38  			name:      "no id",
    39  			s:         `{"vtctlds": []}`,
    40  			shouldErr: true,
    41  		},
    42  		{
    43  			name:      "bad encoding",
    44  			s:         "…∆ø†h¬®ç宸ç", // this junk (when base32 hex'd) breaks base64 std decoding
    45  			encoder:   base32.HexEncoding.EncodeToString,
    46  			shouldErr: true,
    47  		},
    48  		{
    49  			name:      "invalid json",
    50  			s:         `{`,
    51  			shouldErr: true,
    52  		},
    53  	}
    54  
    55  	for _, tt := range tests {
    56  		tt := tt
    57  		t.Run(tt.name, func(t *testing.T) {
    58  			t.Parallel()
    59  
    60  			if tt.encoder == nil {
    61  				tt.encoder = base64.StdEncoding.EncodeToString
    62  			}
    63  
    64  			enc := tt.encoder([]byte(tt.s))
    65  
    66  			c, id, err := ClusterFromString(context.Background(), enc)
    67  			if tt.shouldErr {
    68  				assert.Error(t, err)
    69  				assert.Nil(t, c, "when err != nil, cluster must be nil")
    70  				return
    71  			}
    72  
    73  			require.NoError(t, err)
    74  			require.NotEmpty(t, id, "when err == nil, id must be non-empty")
    75  
    76  			assert.Equal(t, tt.expectedID, id)
    77  			assert.NotNil(t, c, "when err == nil, cluster should not be nil")
    78  		})
    79  	}
    80  }