diff --git a/pkg/cmd/addon/index.go b/pkg/cmd/addon/index.go index cec8cad38..434416b23 100644 --- a/pkg/cmd/addon/index.go +++ b/pkg/cmd/addon/index.go @@ -187,7 +187,7 @@ func newIndexUpdateCmd(streams genericiooptions.IOStreams) *cobra.Command { // IsValidIndexName validates if an index name contains invalid characters func IsValidIndexName(name string) bool { - var validNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) + var validNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,16}$`) return validNamePattern.MatchString(name) } diff --git a/pkg/cmd/addon/index_test.go b/pkg/cmd/addon/index_test.go new file mode 100644 index 000000000..d3045fc1c --- /dev/null +++ b/pkg/cmd/addon/index_test.go @@ -0,0 +1,83 @@ +package addon + +import ( + "bytes" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "k8s.io/cli-runtime/pkg/genericiooptions" +) + +var _ = Describe("index test", func() { + var streams genericiooptions.IOStreams + var out *bytes.Buffer + const ( + defaultIndexName = "kubeblocks" + testIndexName = "kb-other" + testIndexURL = "unknown" + ) + BeforeEach(func() { + streams, _, out, _ = genericiooptions.NewTestIOStreams() + Expect(addDefaultIndex()).Should(Succeed()) + }) + + It("test index cmd", func() { + Expect(newIndexCmd(streams)).ShouldNot(BeNil()) + }) + + It("test index add cmd", func() { + cmd := newIndexAddCmd() + Expect(cmd).ShouldNot(BeNil()) + Expect(addIndex([]string{defaultIndexName, testIndexURL})).Should(HaveOccurred()) + Expect(addIndex([]string{testIndexName, testIndexURL})).Should(HaveOccurred()) + }) + + It("test index delete cmd", func() { + Expect(newIndexDeleteCmd()).ShouldNot(BeNil()) + Expect(deleteIndex(testIndexName)).Should(HaveOccurred()) + }) + + It("test index list cmd", func() { + Expect(newIndexListCmd(streams)).ShouldNot(BeNil()) + Expect(listIndexes(out)).Should(Succeed()) + expect := `INDEX URL +kubeblocks https://github.com/apecloud/block-index.git +` + Expect(out.String()).Should(Equal(expect)) + }) + + It("test index update cmd", func() { + Expect(newIndexUpdateCmd(streams)).ShouldNot(BeNil()) + + o := &updateOption{ + names: make([]string, 0), + all: false, + IOStreams: streams, + } + Expect(o.validate([]string{defaultIndexName})).Should(Succeed()) + Expect(o.validate([]string{testIndexName})).Should(HaveOccurred()) + Expect(o.validate([]string{})).Should(HaveOccurred()) + o.all = true + Expect(o.validate([]string{})).Should(Succeed()) + Expect(o.run()).Should(Succeed()) + }) + + It("test index name", func() { + cases := []struct { + name string + success bool + }{ + {"kubeblocks", true}, {"KubeBlocks123", true}, {"Kube_Blocks", true}, {"kube-blocks", true}, {"12345", true}, + {"kube blocks", false}, {"kube@blocks", false}, {"", false}, {"kubekubekubeblocks", false}, + } + + for _, t := range cases { + if t.success { + Expect(IsValidIndexName(t.name)).Should(BeTrue()) + } else { + Expect(IsValidIndexName(t.name)).Should(BeFalse()) + } + } + }) +})