mirror of
https://github.com/kubevela/kubevela.git
synced 2026-02-14 18:10:21 +00:00
* 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>
211 lines
5.9 KiB
Go
211 lines
5.9 KiB
Go
/*
|
|
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 (
|
|
"embed"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"path"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/google/go-github/v32/github"
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/oam-dev/kubevela/pkg/utils"
|
|
)
|
|
|
|
const (
|
|
// baseURLPath is a non-empty Client.BaseURL path to use during tests,
|
|
// to ensure relative URLs are used for all endpoints. See issue #752.
|
|
baseURLPath = "/api-v3"
|
|
)
|
|
|
|
var (
|
|
//go:embed testdata
|
|
testdata embed.FS
|
|
testdataPrefix = "testdata"
|
|
)
|
|
|
|
func setup() (client *github.Client, mux *http.ServeMux, teardown func()) {
|
|
// mux is the HTTP request multiplexer used with the test server.
|
|
mux = http.NewServeMux()
|
|
|
|
apiHandler := http.NewServeMux()
|
|
apiHandler.Handle(baseURLPath+"/", http.StripPrefix(baseURLPath, mux))
|
|
|
|
// server is a test HTTP server used to provide mock API responses.
|
|
server := httptest.NewServer(apiHandler)
|
|
|
|
// client is the GitHub client being tested and is
|
|
// configured to use test server.
|
|
client = github.NewClient(nil)
|
|
URL, _ := url.Parse(server.URL + baseURLPath + "/")
|
|
client.BaseURL = URL
|
|
client.UploadURL = URL
|
|
|
|
return client, mux, server.Close
|
|
}
|
|
|
|
func TestGitHubReader_ReadFile(t *testing.T) {
|
|
client, mux, teardown := setup()
|
|
defer teardown()
|
|
|
|
githubPattern := "/repos/o/r/contents/"
|
|
mux.HandleFunc(githubPattern, func(rw http.ResponseWriter, req *http.Request) {
|
|
queryPath := strings.TrimPrefix(req.URL.Path, githubPattern)
|
|
localPath := path.Join(testdataPrefix, queryPath)
|
|
file, err := testdata.ReadFile(localPath)
|
|
// test if it's a file
|
|
if err == nil {
|
|
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)
|
|
rw.Write(res)
|
|
return
|
|
}
|
|
|
|
// otherwise, it could be directory
|
|
dir, err := testdata.ReadDir(localPath)
|
|
if err == nil {
|
|
contents := make([]*github.RepositoryContent, 0)
|
|
for _, item := range dir {
|
|
tp := "file"
|
|
if item.IsDir() {
|
|
tp = "dir"
|
|
}
|
|
contents = append(contents, &github.RepositoryContent{Type: String(tp), Name: String(item.Name()), Path: String(path.Join(queryPath, item.Name()))})
|
|
}
|
|
dRes, _ := json.Marshal(contents)
|
|
rw.Write(dRes)
|
|
return
|
|
}
|
|
|
|
rw.WriteHeader(http.StatusNotFound)
|
|
})
|
|
|
|
gith := &gitHelper{
|
|
Client: client,
|
|
Meta: &utils.Content{GithubContent: utils.GithubContent{
|
|
Owner: "o",
|
|
Repo: "r",
|
|
}},
|
|
}
|
|
var r AsyncReader = &gitReader{gith}
|
|
_, err := r.ReadFile("example/metadata.yaml")
|
|
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
|
|
// to store v and returns a pointer to it.
|
|
func Int(v int) *int { return &v }
|
|
|
|
// String is a helper routine that allocates a new string value
|
|
// to store v and returns a pointer to it.
|
|
func String(v string) *string { return &v }
|