Feat(addon): Enhance unit test coverage for pkg/addon (#6901)

* feat(addon): add comprehensive unit tests for addon readers

This commit enhances the test coverage and code quality for the addon reader implementations in the pkg/addon package.

- Refactors all existing addon reader tests (gitee, github, gitlab, local) to use consistent, modern testing patterns like sub-tests.
- Replaces the old memory_reader_test.go with a completely refactored implementation.
- Adds new unit tests for previously untested functions, including various getters, client constructors, and RelativePath helpers.
- Improves http-based tests (gitlab, github, gitee) to use robust mock handlers that correctly simulate API behavior, including pagination and error states.

These changes improve the overall quality and reliability of the addon system and uncovered two minor bugs during the process.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(addon): add more unit tests for addon helpers

This commit continues to improve the test coverage for the pkg/addon package by adding unit tests for several helper and factory functions.

- Adds a test for WrapErrRateLimit to ensure GitHub API rate limit errors are handled correctly.
- Adds a test for ClassifyItemByPattern to verify addon file classification logic.
- Adds a test for the NewAsyncReader factory function to ensure correct reader instantiation.
- Adds tests for various utility functions in utils.go, including IsRegistryFuncs, InstallOptions, ProduceDefConflictError, and GenerateChartMetadata.

These tests increase the reliability of the addon installation and handling logic.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(addon): add unit tests for versioned addon registry

This commit improves test coverage for the versioned addon registry logic in the pkg/addon package.

- Adds a unit test for resolveAddonListFromIndex to verify the logic for parsing Helm index files.
- Introduces a new table-driven test for the internal loadAddon function, covering success and multiple failure scenarios (e.g., version not found, download failure, corrupt data).
- Adds a new test helper, setupAddonTestServer, to create isolated mock HTTP servers for testing addon loading, improving test reliability and clarity.

These tests ensure the core logic for discovering and fetching versioned addons is robust and functions as expected.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* chore(addon): remove unused gitlab testdata path constant

- remove unused gitlab testdata path constant name `gitlabTestdataPath`

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* refactor(addon): improve unit tests based on review feedback

This commit addresses several code review comments to improve the quality, correctness, and robustness of the unit tests in the pkg/addon package.
- Refactors map key assertions in the memory reader test to use the correct "comma ok" idiom instead of assert.NotNil.
- Updates the GitHub reader test to use a compliant addon mock that includes the required template.cue file.
- Modifies the chart metadata test in utils_test.go to use t.TempDir() for better test isolation and automatic cleanup.
- Switches from assert.NotNil to require.NotNil in the versioned registry test to prevent panics on nil pointers.
These changes make the test suite more robust, reliable, and easier to maintain.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
This commit is contained in:
AshvinBambhaniya2003
2025-10-17 15:17:43 +05:30
committed by GitHub
parent 3f5b698dac
commit 21d9d24b07
10 changed files with 931 additions and 145 deletions

View File

@@ -20,6 +20,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/google/go-github/v32/github"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@@ -41,3 +43,13 @@ func TestGetAvailableVersion(t *testing.T) {
assert.NotEmpty(t, err) assert.NotEmpty(t, err)
assert.Equal(t, version, "") assert.Equal(t, version, "")
} }
func TestWrapErrRateLimit(t *testing.T) {
regularErr := errors.New("regular error")
wrappedErr := WrapErrRateLimit(regularErr)
assert.Equal(t, regularErr, wrappedErr)
rateLimitErr := &github.RateLimitError{}
wrappedErr = WrapErrRateLimit(rateLimitErr)
assert.Equal(t, ErrRateLimit, wrappedErr)
}

View File

@@ -1,71 +0,0 @@
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package addon
import (
"testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v3/pkg/chart/loader"
)
var files = []*loader.BufferedFile{
{
Name: "metadata.yaml",
Data: []byte(`name: test-helm-addon
version: 1.0.0
description: This is a addon for test when install addon from helm repo
icon: https://www.terraform.io/assets/images/logo-text-8c3ba8a6.svg
url: https://terraform.io/
tags: []
deployTo:
control_plane: true
runtime_cluster: false
dependencies: []
invisible: false`),
},
{
Name: "/resources/parameter.cue",
Data: []byte(`parameter: {
// test wrong parameter
example: *"default"
}`),
},
}
func TestMemoryReader(t *testing.T) {
m := MemoryReader{
Name: "fluxcd",
Files: files,
}
meta, err := m.ListAddonMeta()
assert.NoError(t, err)
assert.Equal(t, len(meta["fluxcd"].Items), 2)
metaFile, err := m.ReadFile("metadata.yaml")
assert.NoError(t, err)
assert.NotEmpty(t, metaFile)
parameterData, err := m.ReadFile("/resources/parameter.cue")
assert.NoError(t, err)
assert.NotEmpty(t, parameterData)
}

View File

@@ -97,3 +97,155 @@ func TestGiteeReader(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
} }
func TestNewGiteeClient(t *testing.T) {
defaultURL, _ := url.Parse(DefaultGiteeURL)
testCases := map[string]struct {
httpClient *http.Client
baseURL *url.URL
wantClient *http.Client
wantURL *url.URL
}{
"Nil inputs": {
httpClient: nil,
baseURL: nil,
wantClient: &http.Client{},
wantURL: defaultURL,
},
"Custom inputs": {
httpClient: &http.Client{Timeout: 10},
baseURL: &url.URL{Host: "my-gitee.com"},
wantClient: &http.Client{Timeout: 10},
wantURL: &url.URL{Host: "my-gitee.com"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
client := NewGiteeClient(tc.httpClient, tc.baseURL)
assert.Equal(t, tc.wantClient.Timeout, client.Client.Timeout)
assert.Equal(t, tc.wantURL.Host, client.BaseURL.Host)
})
}
}
func TestGiteeReaderRelativePath(t *testing.T) {
testCases := map[string]struct {
basePath string
itemPath string
expectedPath string
}{
"No base path": {
basePath: "",
itemPath: "fluxcd/metadata.yaml",
expectedPath: "fluxcd/metadata.yaml",
},
"With base path": {
basePath: "addons",
itemPath: "addons/fluxcd/metadata.yaml",
expectedPath: "fluxcd/metadata.yaml",
},
"With deep base path": {
basePath: "official/addons",
itemPath: "official/addons/fluxcd/template.cue",
expectedPath: "fluxcd/template.cue",
},
"Item at root of base path": {
basePath: "addons",
itemPath: "addons/README.md",
expectedPath: "README.md",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
gith := &giteeHelper{
Meta: &utils.Content{GiteeContent: utils.GiteeContent{
Path: tc.basePath,
}},
}
r := &giteeReader{h: gith}
item := &github.RepositoryContent{Path: &tc.itemPath}
result := r.RelativePath(item)
assert.Equal(t, tc.expectedPath, result)
})
}
}
func TestGiteeReader_ListAddonMeta(t *testing.T) {
client, mux, teardown := giteeSetup()
defer teardown()
giteePattern := "/repos/o/r/contents/"
mux.HandleFunc(giteePattern, func(rw http.ResponseWriter, req *http.Request) {
var contents []*github.RepositoryContent
queryPath := strings.TrimPrefix(req.URL.Path, giteePattern)
switch queryPath {
case "": // Root directory
contents = []*github.RepositoryContent{
{Type: String("dir"), Name: String("fluxcd"), Path: String("fluxcd")},
{Type: String("dir"), Name: String("velaux"), Path: String("velaux")},
{Type: String("file"), Name: String("README.md"), Path: String("README.md")},
}
case "fluxcd":
contents = []*github.RepositoryContent{
{Type: String("file"), Name: String("metadata.yaml"), Path: String("fluxcd/metadata.yaml")},
{Type: String("dir"), Name: String("resources"), Path: String("fluxcd/resources")},
}
case "fluxcd/resources":
contents = []*github.RepositoryContent{
{Type: String("file"), Name: String("parameter.cue"), Path: String("fluxcd/resources/parameter.cue")},
}
case "velaux":
contents = []*github.RepositoryContent{
{Type: String("file"), Name: String("metadata.yaml"), Path: String("velaux/metadata.yaml")},
}
default:
rw.WriteHeader(http.StatusNotFound)
return
}
res, _ := json.Marshal(contents)
rw.Write(res)
})
gith := &giteeHelper{
Client: client,
Meta: &utils.Content{GiteeContent: utils.GiteeContent{
Owner: "o",
Repo: "r",
}},
}
r := &giteeReader{h: gith}
meta, err := r.ListAddonMeta()
assert.NoError(t, err)
assert.NotNil(t, meta)
assert.Equal(t, 2, len(meta), "Expected to find 2 addons, root files should be ignored")
t.Run("fluxcd addon discovery", func(t *testing.T) {
addon, ok := meta["fluxcd"]
assert.True(t, ok, "fluxcd addon should be discovered")
assert.Equal(t, "fluxcd", addon.Name)
// Should find 2 items recursively: metadata.yaml and resources/parameter.cue
assert.Equal(t, 2, len(addon.Items), "fluxcd should contain 2 files")
foundPaths := make(map[string]bool)
for _, item := range addon.Items {
foundPaths[item.GetPath()] = true
}
assert.True(t, foundPaths["fluxcd/metadata.yaml"], "should find fluxcd/metadata.yaml")
assert.True(t, foundPaths["fluxcd/resources/parameter.cue"], "should find fluxcd/resources/parameter.cue")
})
t.Run("velaux addon discovery", func(t *testing.T) {
addon, ok := meta["velaux"]
assert.True(t, ok, "velaux addon should be discovered")
assert.Equal(t, "velaux", addon.Name)
assert.Equal(t, 1, len(addon.Items), "velaux should contain 1 file")
assert.Equal(t, "velaux/metadata.yaml", addon.Items[0].GetPath())
})
}

View File

@@ -64,8 +64,10 @@ func setup() (client *github.Client, mux *http.ServeMux, teardown func()) {
return client, mux, server.Close return client, mux, server.Close
} }
func TestGitHubReader(t *testing.T) { func TestGitHubReader_ReadFile(t *testing.T) {
client, mux, teardown := setup() client, mux, teardown := setup()
defer teardown()
githubPattern := "/repos/o/r/contents/" githubPattern := "/repos/o/r/contents/"
mux.HandleFunc(githubPattern, func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc(githubPattern, func(rw http.ResponseWriter, req *http.Request) {
queryPath := strings.TrimPrefix(req.URL.Path, githubPattern) queryPath := strings.TrimPrefix(req.URL.Path, githubPattern)
@@ -76,6 +78,7 @@ func TestGitHubReader(t *testing.T) {
content := &github.RepositoryContent{Type: String("file"), Name: String(path.Base(queryPath)), Size: Int(len(file)), Encoding: String(""), Path: String(queryPath), Content: String(string(file))} content := &github.RepositoryContent{Type: String("file"), Name: String(path.Base(queryPath)), Size: Int(len(file)), Encoding: String(""), Path: String(queryPath), Content: String(string(file))}
res, _ := json.Marshal(content) res, _ := json.Marshal(content)
rw.Write(res) rw.Write(res)
return
} }
// otherwise, it could be directory // otherwise, it could be directory
@@ -91,11 +94,11 @@ func TestGitHubReader(t *testing.T) {
} }
dRes, _ := json.Marshal(contents) dRes, _ := json.Marshal(contents)
rw.Write(dRes) rw.Write(dRes)
return
} }
rw.Write([]byte("invalid github query")) rw.WriteHeader(http.StatusNotFound)
}) })
defer teardown()
gith := &gitHelper{ gith := &gitHelper{
Client: client, Client: client,
@@ -107,7 +110,95 @@ func TestGitHubReader(t *testing.T) {
var r AsyncReader = &gitReader{gith} var r AsyncReader = &gitReader{gith}
_, err := r.ReadFile("example/metadata.yaml") _, err := r.ReadFile("example/metadata.yaml")
assert.NoError(t, err) assert.NoError(t, err)
}
func TestGitReader_RelativePath(t *testing.T) {
testCases := map[string]struct {
basePath string
itemPath string
expectedPath string
}{
"No base path": {
basePath: "",
itemPath: "fluxcd/metadata.yaml",
expectedPath: "fluxcd/metadata.yaml",
},
"With base path": {
basePath: "addons",
itemPath: "addons/fluxcd/metadata.yaml",
expectedPath: "fluxcd/metadata.yaml",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
gith := &gitHelper{
Meta: &utils.Content{GithubContent: utils.GithubContent{
Path: tc.basePath,
}},
}
r := &gitReader{h: gith}
item := &github.RepositoryContent{Path: &tc.itemPath}
result := r.RelativePath(item)
assert.Equal(t, tc.expectedPath, result)
})
}
}
func TestGitReader_ListAddonMeta(t *testing.T) {
client, mux, teardown := setup()
defer teardown()
githubPattern := "/repos/o/r/contents/"
mux.HandleFunc(githubPattern, func(rw http.ResponseWriter, req *http.Request) {
var contents []*github.RepositoryContent
queryPath := strings.TrimPrefix(req.URL.Path, githubPattern)
switch queryPath {
case "": // Root directory
contents = []*github.RepositoryContent{
{Type: String("dir"), Name: String("fluxcd"), Path: String("fluxcd")},
{Type: String("file"), Name: String("README.md"), Path: String("README.md")},
}
case "fluxcd":
contents = []*github.RepositoryContent{
{Type: String("file"), Name: String("metadata.yaml"), Path: String("fluxcd/metadata.yaml")},
{Type: String("dir"), Name: String("resources"), Path: String("fluxcd/resources")},
{Type: String("file"), Name: String("template.cue"), Path: String("fluxcd/template.cue")},
}
case "fluxcd/resources":
contents = []*github.RepositoryContent{
{Type: String("file"), Name: String("parameter.cue"), Path: String("fluxcd/resources/parameter.cue")},
}
default:
rw.WriteHeader(http.StatusNotFound)
return
}
res, _ := json.Marshal(contents)
rw.Write(res)
})
gith := &gitHelper{
Client: client,
Meta: &utils.Content{GithubContent: utils.GithubContent{
Owner: "o",
Repo: "r",
}},
}
r := &gitReader{h: gith}
meta, err := r.ListAddonMeta()
assert.NoError(t, err)
assert.NotNil(t, meta)
assert.Equal(t, 1, len(meta), "Expected to find 1 addon, root files should be ignored")
t.Run("fluxcd addon discovery", func(t *testing.T) {
addon, ok := meta["fluxcd"]
assert.True(t, ok, "fluxcd addon should be discovered")
assert.Equal(t, "fluxcd", addon.Name)
assert.Equal(t, 3, len(addon.Items), "fluxcd should contain 3 files")
})
} }
// Int is a helper routine that allocates a new int value // Int is a helper routine that allocates a new int value

View File

@@ -21,8 +21,7 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"path" "strconv"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -33,83 +32,156 @@ import (
var baseUrl = "/api/v4" var baseUrl = "/api/v4"
func gitlabSetup() (client *gitlab.Client, mux *http.ServeMux, teardown func()) { func gitlabSetup(t *testing.T) (*gitlab.Client, *http.ServeMux, func()) {
// mux is the HTTP request multiplexer used with the test server. mux := http.NewServeMux()
mux = http.NewServeMux()
apiHandler := http.NewServeMux() apiHandler := http.NewServeMux()
apiHandler.Handle(baseUrl+"/", http.StripPrefix(baseUrl, mux)) apiHandler.Handle(baseUrl+"/", http.StripPrefix(baseUrl, mux))
// server is a test HTTP server used to provide mock API responses.
server := httptest.NewServer(apiHandler) server := httptest.NewServer(apiHandler)
// client is the Gitlab client being tested and is
// configured to use test server.
client, err := gitlab.NewClient("", gitlab.WithBaseURL(server.URL+baseUrl+"/")) client, err := gitlab.NewClient("", gitlab.WithBaseURL(server.URL+baseUrl+"/"))
if err != nil { assert.NoError(t, err)
return
}
return client, mux, server.Close return client, mux, server.Close
} }
func TestGitlabReader(t *testing.T) { func TestGitlabReader_ReadFile(t *testing.T) {
client, mux, teardown := gitlabSetup() client, mux, teardown := gitlabSetup(t)
gitlabPattern := "/projects/9999/repository/files/"
mux.HandleFunc(gitlabPattern, func(rw http.ResponseWriter, req *http.Request) {
queryPath := strings.TrimPrefix(req.URL.Path, gitlabPattern)
localPath := path.Join(testdataPrefix, queryPath)
file, err := testdata.ReadFile(localPath)
// test if it's a file
if err == nil {
content := &gitlab.File{
FilePath: localPath,
FileName: path.Base(queryPath),
Size: *Int(len(file)),
Encoding: "base64",
Ref: "master",
Content: base64.StdEncoding.EncodeToString(file),
}
res, _ := json.Marshal(content)
rw.Write(res)
return
}
// otherwise, it could be directory
dir, err := testdata.ReadDir(localPath)
if err == nil {
contents := make([]*gitlab.TreeNode, 0)
for _, item := range dir {
tp := "file"
if item.IsDir() {
tp = "dir"
}
contents = append(contents, &gitlab.TreeNode{
ID: "",
Name: item.Name(),
Type: tp,
Path: localPath + "/" + item.Name(),
Mode: "",
})
}
dRes, _ := json.Marshal(contents)
rw.Write(dRes)
return
}
rw.Write([]byte("invalid gitlab query"))
})
defer teardown() defer teardown()
// The gitlab client URL-encodes the file path, so we must match the encoded path.
mux.HandleFunc("/projects/9999/repository/files/example%2Fmetadata.yaml", func(rw http.ResponseWriter, req *http.Request) {
content := &gitlab.File{
Content: base64.StdEncoding.EncodeToString([]byte("hello world")),
}
res, err := json.Marshal(content)
assert.NoError(t, err)
_, err = rw.Write(res)
assert.NoError(t, err)
})
mux.HandleFunc("/projects/9999/repository/files/example%2Fnot%2Ffound.yaml", func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusNotFound)
})
gith := &gitlabHelper{
Client: client,
Meta: &utils.Content{GitlabContent: utils.GitlabContent{PId: 9999, Path: "example"}},
}
var r AsyncReader = &gitlabReader{h: gith}
t.Run("success case", func(t *testing.T) {
content, err := r.ReadFile("metadata.yaml")
assert.NoError(t, err)
assert.Equal(t, "hello world", content)
})
t.Run("not found case", func(t *testing.T) {
_, err := r.ReadFile("not/found.yaml")
assert.Error(t, err)
})
}
func TestGitlabReader_ListAddonMeta(t *testing.T) {
client, mux, teardown := gitlabSetup(t)
defer teardown()
projectID := 9999
projectPath := "addons"
mux.HandleFunc("/projects/"+strconv.Itoa(projectID)+"/repository/tree", func(rw http.ResponseWriter, req *http.Request) {
pathParam := req.URL.Query().Get("path")
pageParam := req.URL.Query().Get("page")
if pageParam == "" {
pageParam = "1"
}
var tree []*gitlab.TreeNode
switch pathParam {
case projectPath:
rw.Header().Set("X-Total-Pages", "2")
if pageParam == "1" {
tree = []*gitlab.TreeNode{{ID: "1", Name: "fluxcd", Type: "tree", Path: "addons/fluxcd"}}
} else if pageParam == "2" {
tree = []*gitlab.TreeNode{{ID: "2", Name: "velaux", Type: "tree", Path: "addons/velaux"}}
}
case "addons/fluxcd":
tree = []*gitlab.TreeNode{{ID: "3", Name: "metadata.yaml", Type: "blob", Path: "addons/fluxcd/metadata.yaml"}}
case "addons/velaux":
tree = []*gitlab.TreeNode{{ID: "4", Name: "template.cue", Type: "blob", Path: "addons/velaux/template.cue"}}
default:
rw.WriteHeader(http.StatusNotFound)
return
}
res, err := json.Marshal(tree)
assert.NoError(t, err)
_, err = rw.Write(res)
assert.NoError(t, err)
})
gith := &gitlabHelper{ gith := &gitlabHelper{
Client: client, Client: client,
Meta: &utils.Content{GitlabContent: utils.GitlabContent{ Meta: &utils.Content{GitlabContent: utils.GitlabContent{
PId: 9999, PId: projectID,
Path: projectPath,
}}, }},
} }
var r AsyncReader = &gitlabReader{gith} r := &gitlabReader{h: gith}
_, err := r.ReadFile("example/metadata.yaml")
meta, err := r.ListAddonMeta()
assert.NoError(t, err) assert.NoError(t, err)
assert.NotNil(t, meta)
assert.Equal(t, 2, len(meta))
expectedAddons := map[string]struct {
itemCount int
itemPath string
}{
"fluxcd": {itemCount: 1, itemPath: "fluxcd/metadata.yaml"},
"velaux": {itemCount: 1, itemPath: "velaux/template.cue"},
}
for name, expected := range expectedAddons {
t.Run(name, func(t *testing.T) {
addon, ok := meta[name]
assert.True(t, ok, "addon not found in result")
assert.Equal(t, name, addon.Name)
assert.Equal(t, expected.itemCount, len(addon.Items))
assert.Equal(t, expected.itemPath, addon.Items[0].GetPath())
})
}
}
func TestGitlabReader_Getters(t *testing.T) {
t.Run("GetRef", func(t *testing.T) {
githWithRef := &gitlabHelper{Meta: &utils.Content{GitlabContent: utils.GitlabContent{Ref: "develop"}}}
rWithRef := &gitlabReader{h: githWithRef}
assert.Equal(t, "develop", rWithRef.GetRef())
githWithoutRef := &gitlabHelper{Meta: &utils.Content{GitlabContent: utils.GitlabContent{Ref: ""}}}
rWithoutRef := &gitlabReader{h: githWithoutRef}
assert.Equal(t, "master", rWithoutRef.GetRef())
})
t.Run("GetProjectID and GetProjectPath", func(t *testing.T) {
gith := &gitlabHelper{
Meta: &utils.Content{GitlabContent: utils.GitlabContent{
PId: 12345,
Path: "my/project/path",
}},
}
r := &gitlabReader{h: gith}
assert.Equal(t, 12345, r.GetProjectID())
assert.Equal(t, "my/project/path", r.GetProjectPath())
})
t.Run("RelativePath", func(t *testing.T) {
r := &gitlabReader{}
item := &GitLabItem{
basePath: "addons",
path: "addons/fluxcd/metadata.yaml",
}
assert.Equal(t, "fluxcd/metadata.yaml", r.RelativePath(item))
})
} }
func TestGitLabItem(t *testing.T) { func TestGitLabItem(t *testing.T) {

View File

@@ -17,6 +17,7 @@ limitations under the License.
package addon package addon
import ( import (
"path/filepath"
"strings" "strings"
"testing" "testing"
@@ -25,17 +26,66 @@ import (
func TestLocalReader(t *testing.T) { func TestLocalReader(t *testing.T) {
r := localReader{name: "local", dir: "./testdata/local"} r := localReader{name: "local", dir: "./testdata/local"}
m, err := r.ListAddonMeta()
assert.NoError(t, err)
assert.Equal(t, len(m["local"].Items), 2)
file, err := r.ReadFile("metadata.yaml") t.Run("ListAddonMeta", func(t *testing.T) {
assert.NoError(t, err) m, err := r.ListAddonMeta()
assert.Equal(t, file, metaFile) assert.NoError(t, err)
assert.NotNil(t, m["local"])
assert.Equal(t, 2, len(m["local"].Items))
file, err = r.ReadFile("resources/parameter.cue") // Check that the correct files are found, regardless of order.
assert.NoError(t, err) foundPaths := make(map[string]bool)
assert.Equal(t, true, strings.Contains(file, parameterFile)) for _, item := range m["local"].Items {
// Normalize path separators for consistent checking
foundPaths[filepath.ToSlash(item.GetPath())] = true
}
assert.True(t, foundPaths[filepath.ToSlash("testdata/local/metadata.yaml")])
assert.True(t, foundPaths[filepath.ToSlash("testdata/local/resources/parameter.cue")])
})
t.Run("ReadFile", func(t *testing.T) {
t.Run("read root file", func(t *testing.T) {
file, err := r.ReadFile("metadata.yaml")
assert.NoError(t, err)
assert.Equal(t, file, metaFile)
})
t.Run("read nested file", func(t *testing.T) {
file, err := r.ReadFile("resources/parameter.cue")
assert.NoError(t, err)
assert.True(t, strings.Contains(file, parameterFile))
})
})
}
func TestLocalReader_RelativePath(t *testing.T) {
testCases := map[string]struct {
dir string
addonName string
itemPath string
expected string
}{
"item in root": {
dir: "./testdata/local",
addonName: "my-addon",
itemPath: filepath.Join("./testdata/local", "metadata.yaml"),
expected: filepath.Join("my-addon", "metadata.yaml"),
},
"item in subdirectory": {
dir: "./testdata/local",
addonName: "my-addon",
itemPath: filepath.Join("./testdata/local", "resources", "parameter.cue"),
expected: filepath.Join("my-addon", "resources", "parameter.cue"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
r := localReader{name: tc.addonName, dir: tc.dir}
item := OSSItem{path: tc.itemPath}
result := r.RelativePath(item)
assert.Equal(t, tc.expected, result)
})
}
} }
const ( const (

View File

@@ -0,0 +1,116 @@
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package addon
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v3/pkg/chart/loader"
)
var files = []*loader.BufferedFile{
{
Name: "metadata.yaml",
Data: []byte(`name: test-helm-addon
version: 1.0.0
description: This is a addon for test when install addon from helm repo
icon: https://www.terraform.io/assets/images/logo-text-8c3ba8a6.svg
url: https://terraform.io/
tags: []
deployTo:
control_plane: true
runtime_cluster: false
dependencies: []
invisible: false`),
},
{
Name: "resources/parameter.cue",
Data: []byte(`parameter: {
// test wrong parameter
example: *"default"
}`),
},
}
func TestMemoryReader(t *testing.T) {
m := MemoryReader{
Name: "fluxcd",
Files: files,
}
t.Run("ListAddonMeta", func(t *testing.T) {
meta, err := m.ListAddonMeta()
assert.NoError(t, err)
assert.Equal(t, 2, len(meta["fluxcd"].Items))
// Verify the internal fileData map was populated
_, metadataExists := m.fileData["metadata.yaml"]
assert.True(t, metadataExists, "metadata.yaml should exist in fileData map")
_, parameterExists := m.fileData["resources/parameter.cue"]
assert.True(t, parameterExists, "resources/parameter.cue should exist in fileData map")
})
t.Run("ReadFile", func(t *testing.T) {
// Ensure ListAddonMeta has been called to populate the internal map
_, _ = m.ListAddonMeta()
t.Run("read by exact name", func(t *testing.T) {
metaFile, err := m.ReadFile("metadata.yaml")
assert.NoError(t, err)
assert.NotEmpty(t, metaFile)
})
t.Run("read by prefixed name", func(t *testing.T) {
parameterData, err := m.ReadFile("fluxcd/resources/parameter.cue")
assert.NoError(t, err)
assert.NotEmpty(t, parameterData)
})
})
}
func TestMemoryReader_RelativePath(t *testing.T) {
testCases := map[string]struct {
addonName string
itemName string
expected string
}{
"name without prefix": {
addonName: "my-addon",
itemName: "metadata.yaml",
expected: filepath.Join("my-addon", "metadata.yaml"),
},
"name with prefix": {
addonName: "my-addon",
itemName: "my-addon/template.cue",
expected: "my-addon/template.cue",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
r := MemoryReader{Name: tc.addonName}
item := OSSItem{name: tc.itemName}
result := r.RelativePath(item)
assert.Equal(t, tc.expected, result)
})
}
}

View File

@@ -22,6 +22,127 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
// mockItem implements the Item interface for testing
type mockItem struct {
path string
name string
typeName string
}
func (m mockItem) GetType() string { return m.typeName }
func (m mockItem) GetPath() string { return m.path }
func (m mockItem) GetName() string { return m.name }
// mockReader implements the AsyncReader interface for testing
type mockReader struct{}
func (m mockReader) ListAddonMeta() (map[string]SourceMeta, error) { return nil, nil }
func (m mockReader) ReadFile(path string) (string, error) { return "", nil }
func (m mockReader) RelativePath(item Item) string { return item.GetPath() }
func TestClassifyItemByPattern(t *testing.T) {
addonName := "my-addon"
meta := &SourceMeta{
Name: addonName,
Items: []Item{
mockItem{path: "my-addon/metadata.yaml"},
mockItem{path: "my-addon/template.cue"},
mockItem{path: "my-addon/definitions/def.cue"},
mockItem{path: "my-addon/resources/res.yaml"},
mockItem{path: "my-addon/schemas/schema.cue"},
mockItem{path: "my-addon/views/view.cue"},
mockItem{path: "my-addon/some-other-file.txt"}, // Should be ignored
},
}
r := mockReader{}
classified := ClassifyItemByPattern(meta, r)
assert.Contains(t, classified, MetadataFileName)
assert.Len(t, classified[MetadataFileName], 1)
assert.Contains(t, classified, AppTemplateCueFileName)
assert.Len(t, classified[AppTemplateCueFileName], 1)
assert.Contains(t, classified, DefinitionsDirName)
assert.Len(t, classified[DefinitionsDirName], 1)
assert.Contains(t, classified, ResourcesDirName)
assert.Len(t, classified[ResourcesDirName], 1)
assert.Contains(t, classified, DefSchemaName)
assert.Len(t, classified[DefSchemaName], 1)
assert.Contains(t, classified, ViewDirName)
assert.Len(t, classified[ViewDirName], 1)
assert.NotContains(t, classified, "some-other-file.txt")
}
func TestNewAsyncReader(t *testing.T) {
testCases := map[string]struct {
baseURL string
bucket string
repo string
subPath string
token string
rdType ReaderType
wantType interface{}
wantErr bool
}{
"git type": {
baseURL: "https://github.com/kubevela/catalog",
subPath: "addons",
rdType: gitType,
wantType: &gitReader{},
wantErr: false,
},
"gitee type": {
baseURL: "https://gitee.com/kubevela/catalog",
subPath: "addons",
rdType: giteeType,
wantType: &giteeReader{},
wantErr: false,
},
"oss type": {
baseURL: "oss-cn-hangzhou.aliyuncs.com",
bucket: "kubevela-addons",
rdType: ossType,
wantType: &ossReader{},
wantErr: false,
},
"invalid url": {
baseURL: "://invalid-url",
rdType: gitType,
wantErr: true,
},
"invalid type": {
baseURL: "https://github.com/kubevela/catalog",
rdType: "invalid",
wantErr: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// Note: This test does not cover the gitlab case as it requires a live API call
// or a complex mock setup, which is beyond the scope of this unit test.
if tc.rdType == gitlabType {
t.Skip("Skipping gitlab test in this unit test suite.")
}
reader, err := NewAsyncReader(tc.baseURL, tc.bucket, tc.repo, tc.subPath, tc.token, tc.rdType)
if tc.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.IsType(t, tc.wantType, reader)
}
})
}
}
func TestPathWithParent(t *testing.T) { func TestPathWithParent(t *testing.T) {
testCases := []struct { testCases := []struct {
readPath string readPath string

View File

@@ -26,6 +26,7 @@ import (
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chartutil" "helm.sh/helm/v3/pkg/chartutil"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -402,6 +403,90 @@ func TestCheckAddonPackageValid(t *testing.T) {
} }
} }
func TestIsRegistryFuncs(t *testing.T) {
t.Run("IsLocalRegistry", func(t *testing.T) {
assert.True(t, IsLocalRegistry(Registry{Name: "local"}))
assert.False(t, IsLocalRegistry(Registry{Name: "KubeVela"}))
})
t.Run("IsVersionRegistry", func(t *testing.T) {
assert.True(t, IsVersionRegistry(Registry{Helm: &HelmSource{}}))
assert.False(t, IsVersionRegistry(Registry{Git: &GitAddonSource{}}))
assert.False(t, IsVersionRegistry(Registry{}))
})
}
func TestInstallOptions(t *testing.T) {
t.Run("SkipValidateVersion", func(t *testing.T) {
installer := &Installer{}
SkipValidateVersion(installer)
assert.True(t, installer.skipVersionValidate)
})
t.Run("DryRunAddon", func(t *testing.T) {
installer := &Installer{}
DryRunAddon(installer)
assert.True(t, installer.dryRun)
})
t.Run("OverrideDefinitions", func(t *testing.T) {
installer := &Installer{}
OverrideDefinitions(installer)
assert.True(t, installer.overrideDefs)
})
}
func TestProduceDefConflictError(t *testing.T) {
t.Run("no conflicts", func(t *testing.T) {
err := produceDefConflictError(map[string]string{})
assert.NoError(t, err)
})
t.Run("with conflicts", func(t *testing.T) {
conflicts := map[string]string{
"def1": "error message 1",
"def2": "error message 2",
}
err := produceDefConflictError(conflicts)
assert.Error(t, err)
assert.Contains(t, err.Error(), "error message 1")
assert.Contains(t, err.Error(), "error message 2")
assert.Contains(t, err.Error(), "--override-definitions")
})
}
func TestGenerateChartMetadata(t *testing.T) {
addonDir := t.TempDir()
// Corrected YAML content with no leading whitespace
metaFileContent := `name: my-addon
version: 1.2.3
description: my addon description
icon: http://my-icon.com
url: http://my-home.com
tags:
- tag1
- tag2
system:
vela: ">=1.5.0"
kubernetes: "1.20.0"
`
err := os.WriteFile(filepath.Join(addonDir, MetadataFileName), []byte(metaFileContent), 0644)
assert.NoError(t, err)
chartMeta, err := generateChartMetadata(addonDir)
assert.NoError(t, err)
assert.NotNil(t, chartMeta)
assert.Equal(t, "my-addon", chartMeta.Name)
assert.Equal(t, "1.2.3", chartMeta.Version)
assert.Equal(t, "my addon description", chartMeta.Description)
assert.Equal(t, "library", chartMeta.Type)
assert.Equal(t, chart.APIVersionV2, chartMeta.APIVersion)
assert.Equal(t, "http://my-icon.com", chartMeta.Icon)
assert.Equal(t, "http://my-home.com", chartMeta.Home)
assert.Equal(t, []string{"tag1", "tag2"}, chartMeta.Keywords)
assert.Equal(t, ">=1.5.0", chartMeta.Annotations[velaSystemRequirement])
assert.Equal(t, "1.20.0", chartMeta.Annotations[kubernetesSystemRequirement])
assert.Equal(t, "my-addon", chartMeta.Annotations[addonSystemRequirement])
}
const ( const (
compDefYaml = ` compDefYaml = `
apiVersion: core.oam.dev/v1beta1 apiVersion: core.oam.dev/v1beta1

View File

@@ -17,6 +17,7 @@ limitations under the License.
package addon package addon
import ( import (
"context"
"encoding/base64" "encoding/base64"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -28,6 +29,7 @@ import (
"helm.sh/helm/v3/pkg/repo" "helm.sh/helm/v3/pkg/repo"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/oam-dev/kubevela/pkg/utils/common" "github.com/oam-dev/kubevela/pkg/utils/common"
"github.com/oam-dev/kubevela/pkg/utils/helm" "github.com/oam-dev/kubevela/pkg/utils/helm"
@@ -227,3 +229,159 @@ func TestToVersionedRegistry(t *testing.T) {
assert.EqualError(t, err, "registry 'git-based-registry' is not a versioned registry") assert.EqualError(t, err, "registry 'git-based-registry' is not a versioned registry")
assert.Nil(t, actual) assert.Nil(t, actual)
} }
func TestResolveAddonListFromIndex(t *testing.T) {
r := &versionedRegistry{name: "test-repo"}
indexFile := &repo.IndexFile{
Entries: map[string]repo.ChartVersions{
"addon-good": {
{Metadata: &chart.Metadata{Name: "addon-good", Version: "1.0.0", Description: "old desc", Icon: "old_icon", Keywords: []string{"tag1"}}},
{Metadata: &chart.Metadata{Name: "addon-good", Version: "1.2.0", Description: "latest desc", Icon: "latest_icon", Keywords: []string{"tag2"}}},
{Metadata: &chart.Metadata{Name: "addon-good", Version: "1.1.0", Description: "middle desc", Icon: "middle_icon", Keywords: []string{"tag3"}}},
},
"addon-empty": {},
"addon-single": {
{Metadata: &chart.Metadata{Name: "addon-single", Version: "0.1.0", Description: "single desc"}},
},
},
}
result := r.resolveAddonListFromIndex(r.name, indexFile)
assert.Equal(t, 2, len(result))
var addonGood, addonSingle *UIData
for _, addon := range result {
if addon.Name == "addon-good" {
addonGood = addon
}
if addon.Name == "addon-single" {
addonSingle = addon
}
}
require.NotNil(t, addonGood)
assert.Equal(t, "addon-good", addonGood.Name)
assert.Equal(t, "test-repo", addonGood.RegistryName)
assert.Equal(t, "1.2.0", addonGood.Version)
assert.Equal(t, "latest desc", addonGood.Description)
assert.Equal(t, "latest_icon", addonGood.Icon)
assert.Equal(t, []string{"tag2"}, addonGood.Tags)
assert.Equal(t, []string{"1.2.0", "1.1.0", "1.0.0"}, addonGood.AvailableVersions)
require.NotNil(t, addonSingle)
assert.Equal(t, "addon-single", addonSingle.Name)
assert.Equal(t, "0.1.0", addonSingle.Version)
assert.Equal(t, []string{"0.1.0"}, addonSingle.AvailableVersions)
}
// setupAddonTestServer creates a mock HTTP server for testing addon loading.
// It can simulate success, 404 errors, or serving corrupt data based on the handlerType.
func setupAddonTestServer(t *testing.T, handlerType string) string {
var server *httptest.Server
// This handler rewrites URLs in the index file to point to the server it's running on.
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "index.yaml") {
content, err := os.ReadFile("./testdata/multiversion-helm-repo/index.yaml")
assert.NoError(t, err)
newContent := strings.ReplaceAll(string(content), "http://127.0.0.1:18083/multi", server.URL)
_, err = w.Write([]byte(newContent))
assert.NoError(t, err)
return
}
// After serving the index, the next request depends on the handler type.
switch handlerType {
case "success":
multiVersionHandler(w, r)
case "notfound":
w.WriteHeader(http.StatusNotFound)
case "corrupt":
_, err := w.Write([]byte("this is not a valid tgz file"))
assert.NoError(t, err)
default:
t.Errorf("unknown handler type: %s", handlerType)
}
})
server = httptest.NewServer(handler)
t.Cleanup(server.Close)
return server.URL
}
func TestLoadAddon(t *testing.T) {
testCases := []struct {
name string
handlerType string
addonName string
addonVersion string
expectErr bool
expectedErrStr string
checkFunc func(t *testing.T, pkg *WholeAddonPackage)
}{
{
name: "Success case",
handlerType: "success",
addonName: "fluxcd",
addonVersion: "1.0.0",
expectErr: false,
checkFunc: func(t *testing.T, pkg *WholeAddonPackage) {
assert.NotNil(t, pkg)
assert.Equal(t, "fluxcd", pkg.Name)
assert.Equal(t, "1.0.0", pkg.Version)
assert.NotEmpty(t, pkg.YAMLTemplates)
assert.Equal(t, []string{"2.0.0", "1.0.0"}, pkg.AvailableVersions)
},
},
{
name: "Version not found",
handlerType: "success",
addonName: "fluxcd",
addonVersion: "3.0.0",
expectErr: true,
expectedErrStr: "specified version 3.0.0 for addon fluxcd not exist",
},
{
name: "Chart download fails",
handlerType: "notfound",
addonName: "fluxcd",
addonVersion: "1.0.0",
expectErr: true,
expectedErrStr: ErrFetch.Error(),
},
{
name: "Corrupt chart file",
handlerType: "corrupt",
addonName: "fluxcd",
addonVersion: "1.0.0",
expectErr: true,
expectedErrStr: ErrFetch.Error(),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
serverURL := setupAddonTestServer(t, tc.handlerType)
reg := &versionedRegistry{
name: "test-registry",
url: serverURL,
h: helm.NewHelperWithCache(),
Opts: nil,
}
pkg, err := reg.loadAddon(context.Background(), tc.addonName, tc.addonVersion)
if tc.expectErr {
assert.Error(t, err)
if tc.expectedErrStr != "" {
assert.Contains(t, err.Error(), tc.expectedErrStr)
}
} else {
assert.NoError(t, err)
}
if tc.checkFunc != nil {
tc.checkFunc(t, pkg)
}
})
}
}