mirror of
https://github.com/kubevela/kubevela.git
synced 2026-05-19 15:56:54 +00:00
* feat(env): Add comprehensive unit tests for environment management This commit introduces a comprehensive suite of unit tests for the environment management functions in `pkg/utils/env`. Key changes include: - Refactoring the test setup to use `TestMain` for better test environment control. - Adding new test cases for `CreateEnv`, `GetEnvByName`, `ListEnvs`, `SetCurrentEnv`, `SetEnvLabels`, and `DeleteEnv`. These tests improve the overall test coverage and ensure the correctness and reliability of environment-related operations. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * feat(errors): Add unit tests for error handling utilities This commit introduces new unit tests for the error handling utilities located in `pkg/utils/errors/`. Specifically, new test files have been added for: - `crd_test.go`: Tests for CRD-related error checks. - `list_test.go`: Tests for error list aggregation. - `reason_test.go`: Tests for specific error reasons like label conflicts and CUE path not found. - `resourcetracker_test.go`: Tests for resource tracker errors. These additions improve the test coverage and ensure the robustness of KubeVela's error handling mechanisms. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * refactor(schema): Refactor ui_schema_test.go to use testify/assert and add new test cases This commit refactors `pkg/utils/schema/ui_schema_test.go` to improve its readability and maintainability. Key changes include: - Migrating from Ginkgo/Gomega to testify/assert for assertions. - Restructuring `TestGetDefaultUIType` into a table-driven test. - Adding new comprehensive test cases for `Condition_Validate` function. These changes enhance the test suite for UI schema utilities, making it more robust and easier to extend. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * refactor(system): Refactor system_test.go and add comprehensive unit tests This commit refactors `pkg/utils/system/system_test.go` to improve its structure, readability, and test coverage. Key changes include: - Converting existing tests to a table-driven format using `testify/assert`. - Adding new comprehensive test cases for: - `CreateIfNotExist` - `GetVelaHomeDir` - `GetDirectoryFunctions` (e.g., `GetCapCenterDir`, `GetCapabilityDir`) - `InitFunctions` (e.g., `InitCapabilityDir`, `InitCapCenterDir`, `InitDirs`) - `BindEnvironmentVariables` These changes enhance the test suite for system utilities, ensuring their correctness and robustness. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * feat(types): Add unit tests for QL types This commit introduces new unit tests for the types defined in `pkg/utils/types`, specifically focusing on types related to KubeVela Query Language (QL). New test cases cover: - `ServiceEndpoint.String()`: Verifies the string representation of service endpoints, including various protocols, ports, and paths. - `AppliedResource.GroupVersionKind()`: Ensures correct extraction of GroupVersionKind from applied resources. - `ResourceTreeNode.GroupVersionKind()`: Verifies correct extraction of GroupVersionKind from resource tree nodes. These tests improve the coverage and reliability of core data structures used in KubeVela. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * feat(util): Add and refactor unit tests for utility functions This commit introduces new unit tests and refactors existing ones within the `pkg/utils/util` package. Key changes include: - **`pkg/utils/util/cmd_test.go`**: Adds comprehensive tests for `IOStreams` and its print functions, as well as `NewDefaultIOStreams` and `NewTestIOStreams`. - **`pkg/utils/util/factory_test.go`**: Refactors the `GenerateLeaderElectionID` test to a table-driven format and adds new tests for `computeDiscoverCacheDir` and `RestConfigGetter` methods, ensuring the correctness of Kubernetes client configuration and discovery. These additions and refactorings enhance the test coverage and reliability of core utility functions. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * feat(utils): Add and refactor unit tests for json, jwt, parse, and strings utilities This commit introduces new unit tests and refactors existing ones across several utility packages within `pkg/utils/`. Key changes include: - **`pkg/utils/json`**: Adds tests for `StrictUnmarshal` to ensure proper JSON unmarshaling. - **`pkg/utils/jwt`**: Adds tests for JWT token subject extraction and certificate subject retrieval. - **`pkg/utils/parse`**: Expands test coverage for URL parsing functions (`Parse`, `ParseGitlab`). - **`pkg/utils/strings`**: Refactors existing tests to a table-driven format and adds tests for box drawing string generation. These additions and refactorings significantly improve the test coverage and reliability of KubeVela's utility functions. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * fix(tests): Address test and error handling issues This commit addresses several issues identified in unit tests and error handling utilities, improving test reliability and code safety. Key fixes and improvements include: - **`pkg/utils/errors`**: - Added nil check to `IsCuePathNotFound` to prevent panics. - Corrected `fmt.Errorf` usage to `errors.New` in `reason_test.go` (SA1006 fix). - Used `assert.EqualError` for clearer error message comparisons in `resourcetracker_test.go`. - **`pkg/utils/jwt_test.go`**: Marked `generateTestCert` as a test helper using `t.Helper()` for better error reporting. - **`pkg/utils/system_test.go`**: - Removed unused `verifyCleanup` field. - Modified `TestGetVelaHomeDir` to use a temporary home directory, preventing destructive operations on the user's system. - **`pkg/utils/util/cmd_test.go`**: Swapped `assert.Equal` arguments to follow `expected, actual` convention. These changes enhance the robustness and correctness of the test suite and related utility functions. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> * chore(tests): Apply gofmt and import ordering to test files This commit applies standard Go formatting (`gofmt`) and corrects import ordering in several test files. Affected files: - `pkg/utils/schema/ui_schema_test.go`: Added missing newline at EOF. - `pkg/utils/system/system_test.go`: Corrected import ordering. - `pkg/utils/util/factory_test.go`: Corrected import ordering. These changes ensure consistency with project coding standards. Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com> --------- Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
186 lines
5.0 KiB
Go
186 lines
5.0 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 util
|
|
|
|
import (
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
"k8s.io/client-go/rest"
|
|
"k8s.io/client-go/tools/clientcmd"
|
|
|
|
"github.com/oam-dev/kubevela/version"
|
|
)
|
|
|
|
func TestGenerateLeaderElectionID(t *testing.T) {
|
|
orig := version.VelaVersion
|
|
defer func() { version.VelaVersion = orig }()
|
|
|
|
testCases := []struct {
|
|
name string
|
|
ver string
|
|
versioned bool
|
|
want string
|
|
}{
|
|
{name: "versioned", ver: "v10.13.0", versioned: true, want: "kubevela-v10-13-0"},
|
|
{name: "unversioned", ver: "v10.13.0", versioned: false, want: "kubevela"},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
version.VelaVersion = tc.ver
|
|
got := GenerateLeaderElectionID("kubevela", tc.versioned)
|
|
require.Equal(t, tc.want, got)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestComputeDiscoverCacheDir(t *testing.T) {
|
|
t.Parallel()
|
|
parent := "/parent"
|
|
|
|
testCases := []struct {
|
|
name string
|
|
host string
|
|
want string
|
|
}{
|
|
{name: "https scheme removed", host: "https://example.com:6443", want: "example.com_6443"},
|
|
{name: "http scheme removed", host: "http://example.com:6443", want: "example.com_6443"},
|
|
{name: "no scheme", host: "k8s.example.io:443", want: "k8s.example.io_443"},
|
|
{name: "sanitize special", host: "exa_mple.com:6443?x=y#frag", want: "exa_mple.com_6443_x_y_frag"},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
got := computeDiscoverCacheDir(parent, tc.host)
|
|
want := filepath.Join(parent, tc.want)
|
|
require.Equal(t, want, got)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRestConfigGetter(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
t.Run("ToRESTConfig returns same pointer", func(t *testing.T) {
|
|
t.Parallel()
|
|
cfg := &rest.Config{Host: "https://cluster.local"}
|
|
r := &restConfigGetter{config: cfg, namespace: "ns"}
|
|
got, err := r.ToRESTConfig()
|
|
require.NoError(t, err)
|
|
require.Same(t, cfg, got)
|
|
})
|
|
|
|
t.Run("NewRestConfigGetterByConfig sets fields", func(t *testing.T) {
|
|
t.Parallel()
|
|
cfg := &rest.Config{Host: "https://cluster.local"}
|
|
g := NewRestConfigGetterByConfig(cfg, "my-ns")
|
|
r, ok := g.(*restConfigGetter)
|
|
require.True(t, ok, "unexpected underlying type for RESTClientGetter")
|
|
require.Equal(t, "my-ns", r.namespace)
|
|
require.Same(t, cfg, r.config)
|
|
})
|
|
}
|
|
|
|
func TestRestConfigGetter_ToRawKubeConfigLoader(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
testCases := []struct {
|
|
name string
|
|
config *rest.Config
|
|
namespace string
|
|
assertFunc func(*testing.T, clientcmd.ClientConfig)
|
|
}{
|
|
{
|
|
name: "simple config",
|
|
config: &rest.Config{
|
|
Host: "https://my-cluster.local",
|
|
},
|
|
namespace: "my-ns",
|
|
assertFunc: func(t *testing.T, clientConfig clientcmd.ClientConfig) {
|
|
ns, _, err := clientConfig.Namespace()
|
|
require.NoError(t, err)
|
|
require.Equal(t, "my-ns", ns)
|
|
},
|
|
},
|
|
{
|
|
name: "full config",
|
|
config: &rest.Config{
|
|
Host: "https://my-cluster.local:6443",
|
|
Username: "my-user",
|
|
Password: "my-pass",
|
|
BearerToken: "my-token",
|
|
TLSClientConfig: rest.TLSClientConfig{
|
|
CertFile: "/path/to/cert",
|
|
KeyFile: "/path/to/key",
|
|
CAFile: "/path/to/ca",
|
|
Insecure: true,
|
|
},
|
|
Timeout: 30 * time.Second,
|
|
Impersonate: rest.ImpersonationConfig{
|
|
UserName: "impersonate-user",
|
|
Groups: []string{"group1", "group2"},
|
|
Extra: map[string][]string{"extra": {"val"}},
|
|
},
|
|
},
|
|
namespace: "full-ns",
|
|
assertFunc: func(t *testing.T, clientConfig clientcmd.ClientConfig) {
|
|
ns, _, err := clientConfig.Namespace()
|
|
require.NoError(t, err)
|
|
require.Equal(t, "full-ns", ns)
|
|
},
|
|
},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
getter := NewRestConfigGetterByConfig(tc.config, tc.namespace)
|
|
clientConfig := getter.ToRawKubeConfigLoader()
|
|
require.NotNil(t, clientConfig)
|
|
tc.assertFunc(t, clientConfig)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRestConfigGetter_DiscoveryAndMapper(t *testing.T) {
|
|
tmpHome := t.TempDir()
|
|
t.Setenv("HOME", tmpHome)
|
|
|
|
originalDefaultCacheDir := defaultCacheDir
|
|
defaultCacheDir = filepath.Join(tmpHome, ".kube", "http-cache")
|
|
defer func() { defaultCacheDir = originalDefaultCacheDir }()
|
|
|
|
cfg := &rest.Config{Host: "http://127.0.0.1:1"}
|
|
getter := NewRestConfigGetterByConfig(cfg, "default")
|
|
|
|
t.Run("ToDiscoveryClient", func(t *testing.T) {
|
|
discoveryClient, err := getter.ToDiscoveryClient()
|
|
require.NoError(t, err)
|
|
require.NotNil(t, discoveryClient)
|
|
})
|
|
|
|
t.Run("ToRESTMapper", func(t *testing.T) {
|
|
mapper, err := getter.ToRESTMapper()
|
|
require.NoError(t, err)
|
|
require.NotNil(t, mapper)
|
|
})
|
|
}
|