From a8961ec8cc29520fc89a4717d848ce97fdffcb31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A5=9A=E5=B2=B3?= Date: Thu, 7 Apr 2022 15:10:08 +0800 Subject: [PATCH] add test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 楚岳 fix check diff Signed-off-by: 楚岳 fix test fix add comments fix test --- pkg/apiserver/rest/usecase/helm.go | 10 ++++---- pkg/apiserver/rest/usecase/helm_test.go | 33 ++++++++++++++++++++++++- pkg/utils/common/common.go | 7 +++--- pkg/utils/common/common_test.go | 11 ++++----- pkg/utils/helm/helm_helper.go | 10 ++++---- pkg/utils/helm/helm_helper_test.go | 8 +++--- references/cli/cli.go | 2 +- references/cli/install.go | 2 +- 8 files changed, 57 insertions(+), 26 deletions(-) diff --git a/pkg/apiserver/rest/usecase/helm.go b/pkg/apiserver/rest/usecase/helm.go index 0640e2558..462568d32 100644 --- a/pkg/apiserver/rest/usecase/helm.go +++ b/pkg/apiserver/rest/usecase/helm.go @@ -65,7 +65,7 @@ type defaultHelmHandler struct { } func (d defaultHelmHandler) ListChartNames(ctx context.Context, url string, secretName string, skipCache bool) ([]string, error) { - var opts *common.HttpOption + var opts *common.HTTPOption var err error if len(secretName) != 0 { opts, err = setAuthInfo(ctx, d.k8sClient, secretName) @@ -82,7 +82,7 @@ func (d defaultHelmHandler) ListChartNames(ctx context.Context, url string, secr } func (d defaultHelmHandler) ListChartVersions(ctx context.Context, url string, chartName string, secretName string, skipCache bool) (repo.ChartVersions, error) { - var opts *common.HttpOption + var opts *common.HTTPOption var err error if len(secretName) != 0 { opts, err = setAuthInfo(ctx, d.k8sClient, secretName) @@ -103,7 +103,7 @@ func (d defaultHelmHandler) ListChartVersions(ctx context.Context, url string, c } func (d defaultHelmHandler) GetChartValues(ctx context.Context, url string, chartName string, version string, secretName string, skipCache bool) (map[string]interface{}, error) { - var opts *common.HttpOption + var opts *common.HTTPOption var err error if len(secretName) != 0 { opts, err = setAuthInfo(ctx, d.k8sClient, secretName) @@ -186,11 +186,11 @@ func flattenKey(prefix string, src map[string]interface{}, dest map[string]inter } } -func setAuthInfo(ctx context.Context, k8sClient client.Client, secretName string) (*common.HttpOption, error) { +func setAuthInfo(ctx context.Context, k8sClient client.Client, secretName string) (*common.HTTPOption, error) { sec := corev1.Secret{} err := k8sClient.Get(ctx, types2.NamespacedName{Namespace: types.DefaultKubeVelaNS, Name: secretName}, &sec) if err != nil { return nil, err } - return &common.HttpOption{Username: string(sec.Data["username"]), Password: string(sec.Data["password"])}, nil + return &common.HTTPOption{Username: string(sec.Data["username"]), Password: string(sec.Data["password"])}, nil } diff --git a/pkg/apiserver/rest/usecase/helm_test.go b/pkg/apiserver/rest/usecase/helm_test.go index fd6701fa6..d637f56c8 100644 --- a/pkg/apiserver/rest/usecase/helm_test.go +++ b/pkg/apiserver/rest/usecase/helm_test.go @@ -49,21 +49,25 @@ func TestFlattenKeyFunc(t *testing.T) { var _ = Describe("Test helm repo list", func() { ctx := context.Background() - var pSec, gSec v1.Secret + var pSec, gSec, aSec v1.Secret BeforeEach(func() { pSec = v1.Secret{} gSec = v1.Secret{} + aSec = v1.Secret{} Expect(k8sClient.Create(ctx, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "vela-system"}})).Should(SatisfyAny(BeNil(), util.AlreadyExistMatcher{})) Expect(yaml.Unmarshal([]byte(projectSecret), &pSec)).Should(BeNil()) Expect(yaml.Unmarshal([]byte(globalSecret), &gSec)).Should(BeNil()) + Expect(yaml.Unmarshal([]byte(authSecret), &aSec)).Should(BeNil()) Expect(k8sClient.Create(ctx, &pSec)).Should(BeNil()) Expect(k8sClient.Create(ctx, &gSec)).Should(BeNil()) + Expect(k8sClient.Create(ctx, &aSec)).Should(BeNil()) }) AfterEach(func() { Expect(k8sClient.Delete(ctx, &gSec)).Should(BeNil()) Expect(k8sClient.Delete(ctx, &pSec)).Should(BeNil()) + Expect(k8sClient.Delete(ctx, &aSec)).Should(BeNil()) }) It("Test list with project ", func() { @@ -102,6 +106,18 @@ var _ = Describe("Test helm repo list", func() { Expect(list.ChartRepoResponse[0].URL).Should(BeEquivalentTo("https://charts.bitnami.com/bitnami")) Expect(list.ChartRepoResponse[0].SecretName).Should(BeEquivalentTo("global-helm-repo")) }) + + It("Test auth info secret func", func() { + opts, err := setAuthInfo(context.Background(), k8sClient, "auth-secret") + Expect(err).Should(BeNil()) + Expect(opts.Username).Should(BeEquivalentTo("admin")) + Expect(opts.Password).Should(BeEquivalentTo("admin")) + }) + + It("Test auth info secret func", func() { + _, err := setAuthInfo(context.Background(), k8sClient, "auth-secret-1") + Expect(err).ShouldNot(BeNil()) + }) }) var ( @@ -266,5 +282,20 @@ metadata: stringData: url: https://kedacore.github.io/charts type: Opaque +` + authSecret = ` +apiVersion: v1 +kind: Secret +metadata: + name: auth-secret + namespace: vela-system + labels: + config.oam.dev/type: config-helm-repository + config.oam.dev/project: my-project-1 +stringData: + url: https://kedacore.github.io/charts + username: admin + password: admin +type: Opaque ` ) diff --git a/pkg/utils/common/common.go b/pkg/utils/common/common.go index 132dcb87e..aeb23c140 100644 --- a/pkg/utils/common/common.go +++ b/pkg/utils/common/common.go @@ -102,8 +102,8 @@ func init() { // +kubebuilder:scaffold:scheme } -// HttpOption define the https options -type HttpOption struct { +// HTTPOption define the https options +type HTTPOption struct { Username string Password string } @@ -140,7 +140,8 @@ func GetClient() (client.Client, error) { return nil, errors.New("client not set, call SetGlobalClient first") } -func HTTPGetWithOption(ctx context.Context, url string, opts *HttpOption) ([]byte, error) { +// HTTPGetWithOption use HTTP option and default client to send get request +func HTTPGetWithOption(ctx context.Context, url string, opts *HTTPOption) ([]byte, error) { // Change NewRequest to NewRequestWithContext and pass context it req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { diff --git a/pkg/utils/common/common_test.go b/pkg/utils/common/common_test.go index fbf35b721..4727b836c 100644 --- a/pkg/utils/common/common_test.go +++ b/pkg/utils/common/common_test.go @@ -98,7 +98,7 @@ func TestHTTPGetWithOption(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { u, p, ok := r.BasicAuth() if !ok { - w.Write([]byte(fmt.Sprintf("Error parsing basic auth"))) + w.Write([]byte("Error parsing basic auth")) w.WriteHeader(401) return } @@ -114,12 +114,11 @@ func TestHTTPGetWithOption(t *testing.T) { } w.Write([]byte("correct password")) w.WriteHeader(200) - return })) defer testServer.Close() cases := map[string]struct { - opts *HttpOption + opts *HTTPOption url string want want }{ @@ -131,7 +130,7 @@ func TestHTTPGetWithOption(t *testing.T) { }, }, "error user name case": { - opts: &HttpOption{ + opts: &HTTPOption{ Username: "no-user", Password: "test-pass", }, @@ -141,7 +140,7 @@ func TestHTTPGetWithOption(t *testing.T) { }, }, "error password case": { - opts: &HttpOption{ + opts: &HTTPOption{ Username: "test-user", Password: "error-pass", }, @@ -151,7 +150,7 @@ func TestHTTPGetWithOption(t *testing.T) { }, }, "correct password case": { - opts: &HttpOption{ + opts: &HTTPOption{ Username: "test-user", Password: "test-pass", }, diff --git a/pkg/utils/helm/helm_helper.go b/pkg/utils/helm/helm_helper.go index b2acac90a..9452527bd 100644 --- a/pkg/utils/helm/helm_helper.go +++ b/pkg/utils/helm/helm_helper.go @@ -73,7 +73,7 @@ func NewHelperWithCache() *Helper { } // LoadCharts load helm chart from local or remote -func (h *Helper) LoadCharts(chartRepoURL string, opts *common.HttpOption) (*chart.Chart, error) { +func (h *Helper) LoadCharts(chartRepoURL string, opts *common.HTTPOption) (*chart.Chart, error) { var err error var chart *chart.Chart if utils.IsValidURL(chartRepoURL) { @@ -178,7 +178,7 @@ func (h *Helper) UninstallRelease(releaseName, namespace string, config *rest.Co } // ListVersions list available versions from repo -func (h *Helper) ListVersions(repoURL string, chartName string, skipCache bool, opts *common.HttpOption) (repo.ChartVersions, error) { +func (h *Helper) ListVersions(repoURL string, chartName string, skipCache bool, opts *common.HTTPOption) (repo.ChartVersions, error) { i, err := h.GetIndexInfo(repoURL, skipCache, opts) if err != nil { return nil, err @@ -187,7 +187,7 @@ func (h *Helper) ListVersions(repoURL string, chartName string, skipCache bool, } // GetIndexInfo get index.yaml form given repo url -func (h *Helper) GetIndexInfo(repoURL string, skipCache bool, opts *common.HttpOption) (*repo.IndexFile, error) { +func (h *Helper) GetIndexInfo(repoURL string, skipCache bool, opts *common.HTTPOption) (*repo.IndexFile, error) { if h.cache != nil && !skipCache { if i := h.cache.Get(fmt.Sprintf(repoPatten, repoURL)); i != nil { return i.(*repo.IndexFile), nil @@ -284,7 +284,7 @@ func newActionConfig(config *rest.Config, namespace string, showDetail bool, log } // ListChartsFromRepo list available helm charts in a repo -func (h *Helper) ListChartsFromRepo(repoURL string, skipCache bool, opts *common.HttpOption) ([]string, error) { +func (h *Helper) ListChartsFromRepo(repoURL string, skipCache bool, opts *common.HTTPOption) ([]string, error) { i, err := h.GetIndexInfo(repoURL, skipCache, opts) if err != nil { return nil, err @@ -299,7 +299,7 @@ func (h *Helper) ListChartsFromRepo(repoURL string, skipCache bool, opts *common } // GetValuesFromChart will extract the parameter from a helm chart -func (h *Helper) GetValuesFromChart(repoURL string, chartName string, version string, skipCache bool, opts *common.HttpOption) (map[string]interface{}, error) { +func (h *Helper) GetValuesFromChart(repoURL string, chartName string, version string, skipCache bool, opts *common.HTTPOption) (map[string]interface{}, error) { if h.cache != nil && !skipCache { if v := h.cache.Get(fmt.Sprintf(valuesPatten, repoURL, chartName, version)); v != nil { return v.(map[string]interface{}), nil diff --git a/pkg/utils/helm/helm_helper_test.go b/pkg/utils/helm/helm_helper_test.go index 7fa62e424..0460df8a6 100644 --- a/pkg/utils/helm/helm_helper_test.go +++ b/pkg/utils/helm/helm_helper_test.go @@ -30,7 +30,7 @@ var _ = Describe("Test helm helper", func() { It("Test LoadCharts ", func() { helper := NewHelper() - chart, err := helper.LoadCharts("./testdata/autoscalertrait-0.1.0.tgz") + chart, err := helper.LoadCharts("./testdata/autoscalertrait-0.1.0.tgz", nil) Expect(err).Should(BeNil()) Expect(chart).ShouldNot(BeNil()) Expect(chart.Metadata).ShouldNot(BeNil()) @@ -39,7 +39,7 @@ var _ = Describe("Test helm helper", func() { It("Test UpgradeChart", func() { helper := NewHelper() - chart, err := helper.LoadCharts("./testdata/autoscalertrait-0.1.0.tgz") + chart, err := helper.LoadCharts("./testdata/autoscalertrait-0.1.0.tgz", nil) Expect(err).Should(BeNil()) release, err := helper.UpgradeChart(chart, "autoscalertrait", "default", nil, UpgradeChartOptions{ Config: cfg, @@ -60,14 +60,14 @@ var _ = Describe("Test helm helper", func() { It("Test ListVersions ", func() { helper := NewHelper() - versions, err := helper.ListVersions("./testdata", "autoscalertrait", true) + versions, err := helper.ListVersions("./testdata", "autoscalertrait", true, nil) Expect(err).Should(BeNil()) Expect(cmp.Diff(len(versions), 2)).Should(BeEmpty()) }) It("Test getValues from chart", func() { helper := NewHelper() - values, err := helper.GetValuesFromChart("./testdata", "autoscalertrait", "0.2.0", true) + values, err := helper.GetValuesFromChart("./testdata", "autoscalertrait", "0.2.0", true, nil) Expect(err).Should(BeNil()) Expect(values).ShouldNot(BeEmpty()) }) diff --git a/references/cli/cli.go b/references/cli/cli.go index de7b38390..496646fc6 100644 --- a/references/cli/cli.go +++ b/references/cli/cli.go @@ -165,7 +165,7 @@ func NewVersionListCommand(ioStream util.IOStreams) *cobra.Command { Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { helmHelper := helm.NewHelper() - versions, err := helmHelper.ListVersions(kubevelaInstallerHelmRepoURL, kubeVelaChartName, true) + versions, err := helmHelper.ListVersions(kubevelaInstallerHelmRepoURL, kubeVelaChartName, true, nil) if err != nil { return err } diff --git a/references/cli/install.go b/references/cli/install.go index d4a360305..f2f4ed0e5 100644 --- a/references/cli/install.go +++ b/references/cli/install.go @@ -106,7 +106,7 @@ func NewInstallCommand(c common.Args, order string, ioStreams util.IOStreams) *c if installArgs.ChartFilePath == "" { installArgs.ChartFilePath = getKubeVelaHelmChartRepoURL(installArgs.Version) } - chart, err := installArgs.helmHelper.LoadCharts(installArgs.ChartFilePath) + chart, err := installArgs.helmHelper.LoadCharts(installArgs.ChartFilePath, nil) if err != nil { return fmt.Errorf("loadding the helm chart of kubeVela control plane failure, %w", err) }