mirror of
https://github.com/kubevela/kubevela.git
synced 2026-05-17 23:07:34 +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>
267 lines
6.7 KiB
Go
267 lines
6.7 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 system
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/oam-dev/kubevela/apis/types"
|
|
"github.com/oam-dev/kubevela/pkg/oam"
|
|
)
|
|
|
|
func TestCreateIfNotExist(t *testing.T) {
|
|
testCases := []struct {
|
|
name string
|
|
setup func(t *testing.T) string
|
|
wantExisted bool
|
|
wantErr bool
|
|
}{
|
|
{
|
|
name: "directory does not exist",
|
|
setup: func(t *testing.T) string {
|
|
return filepath.Join(t.TempDir(), "new-dir")
|
|
},
|
|
wantExisted: false,
|
|
wantErr: false,
|
|
},
|
|
{
|
|
name: "directory already exists",
|
|
setup: func(t *testing.T) string {
|
|
return t.TempDir()
|
|
},
|
|
wantExisted: true,
|
|
wantErr: false,
|
|
},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
path := tc.setup(t)
|
|
existed, err := CreateIfNotExist(path)
|
|
|
|
assert.Equal(t, tc.wantExisted, existed)
|
|
if tc.wantErr {
|
|
assert.Error(t, err)
|
|
} else {
|
|
assert.NoError(t, err)
|
|
_, statErr := os.Stat(path)
|
|
assert.NoError(t, statErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGetVelaHomeDir(t *testing.T) {
|
|
testCases := []struct {
|
|
name string
|
|
setup func(t *testing.T) (expectedPath string, cleanup func())
|
|
wantErr bool
|
|
}{
|
|
{
|
|
name: "from VELA_HOME env var",
|
|
setup: func(t *testing.T) (string, func()) {
|
|
tmpDir := t.TempDir()
|
|
t.Setenv(VelaHomeEnv, tmpDir)
|
|
return tmpDir, func() {}
|
|
},
|
|
wantErr: false,
|
|
},
|
|
{
|
|
name: "from default user home",
|
|
setup: func(t *testing.T) (string, func()) {
|
|
tmpHome := t.TempDir()
|
|
t.Setenv("HOME", tmpHome)
|
|
t.Setenv(VelaHomeEnv, "") // Ensure VELA_HOME is not set, so it falls back to HOME
|
|
expectedPath := filepath.Join(tmpHome, defaultVelaHome)
|
|
return expectedPath, func() {} // t.TempDir() handles cleanup
|
|
},
|
|
wantErr: false,
|
|
},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
expectedPath, cleanup := tc.setup(t)
|
|
defer cleanup()
|
|
|
|
got, err := GetVelaHomeDir()
|
|
|
|
if tc.wantErr {
|
|
assert.Error(t, err)
|
|
} else {
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, expectedPath, got)
|
|
_, statErr := os.Stat(got)
|
|
assert.NoError(t, statErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGetDirectoryFunctions(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
t.Setenv(VelaHomeEnv, tmpDir)
|
|
|
|
testCases := []struct {
|
|
name string
|
|
getFunc func() (string, error)
|
|
expectedPath string
|
|
}{
|
|
{"GetCapCenterDir", GetCapCenterDir, filepath.Join(tmpDir, "centers")},
|
|
{"GetRepoConfig", GetRepoConfig, filepath.Join(tmpDir, "centers", "config.yaml")},
|
|
{"GetCapabilityDir", GetCapabilityDir, filepath.Join(tmpDir, "capabilities")},
|
|
{"GetCurrentEnvPath", GetCurrentEnvPath, filepath.Join(tmpDir, "curenv")},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
got, err := tc.getFunc()
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, tc.expectedPath, got)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestInitFunctions(t *testing.T) {
|
|
testCases := []struct {
|
|
name string
|
|
initFunc func() error
|
|
verifyFunc func(t *testing.T, velaHome string)
|
|
}{
|
|
{
|
|
name: "InitCapabilityDir",
|
|
initFunc: InitCapabilityDir,
|
|
verifyFunc: func(t *testing.T, velaHome string) {
|
|
dir := filepath.Join(velaHome, "capabilities")
|
|
_, err := os.Stat(dir)
|
|
assert.NoError(t, err)
|
|
},
|
|
},
|
|
{
|
|
name: "InitCapCenterDir",
|
|
initFunc: InitCapCenterDir,
|
|
verifyFunc: func(t *testing.T, velaHome string) {
|
|
dir := filepath.Join(velaHome, "centers", ".tmp")
|
|
_, err := os.Stat(dir)
|
|
assert.NoError(t, err)
|
|
},
|
|
},
|
|
{
|
|
name: "InitDirs",
|
|
initFunc: InitDirs,
|
|
verifyFunc: func(t *testing.T, velaHome string) {
|
|
capDir := filepath.Join(velaHome, "capabilities")
|
|
centerDir := filepath.Join(velaHome, "centers", ".tmp")
|
|
_, err := os.Stat(capDir)
|
|
assert.NoError(t, err)
|
|
_, err = os.Stat(centerDir)
|
|
assert.NoError(t, err)
|
|
},
|
|
},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
velaHome := t.TempDir()
|
|
t.Setenv(VelaHomeEnv, velaHome)
|
|
|
|
err := tc.initFunc()
|
|
assert.NoError(t, err)
|
|
tc.verifyFunc(t, velaHome)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestBindEnvironmentVariables(t *testing.T) {
|
|
originalVelaNS := types.DefaultKubeVelaNS
|
|
originalDefNS := oam.SystemDefinitionNamespace
|
|
defer func() {
|
|
types.DefaultKubeVelaNS = originalVelaNS
|
|
oam.SystemDefinitionNamespace = originalDefNS
|
|
}()
|
|
|
|
testCases := []struct {
|
|
name string
|
|
setup func(t *testing.T)
|
|
wantVelaNS string
|
|
wantDefNS string
|
|
}{
|
|
{
|
|
name: "primary env vars",
|
|
setup: func(t *testing.T) {
|
|
t.Setenv(KubeVelaSystemNamespaceEnv, "vela-system-primary")
|
|
t.Setenv(KubeVelaDefinitionNamespaceEnv, "vela-def-primary")
|
|
t.Setenv(LegacyKubeVelaSystemNamespaceEnv, "vela-system-legacy")
|
|
},
|
|
wantVelaNS: "vela-system-primary",
|
|
wantDefNS: "vela-def-primary",
|
|
},
|
|
{
|
|
name: "legacy fallback for vela ns",
|
|
setup: func(t *testing.T) {
|
|
t.Setenv(KubeVelaSystemNamespaceEnv, "")
|
|
t.Setenv(LegacyKubeVelaSystemNamespaceEnv, "vela-system-legacy")
|
|
t.Setenv(KubeVelaDefinitionNamespaceEnv, "vela-def-primary")
|
|
},
|
|
wantVelaNS: "vela-system-legacy",
|
|
wantDefNS: "vela-def-primary",
|
|
},
|
|
{
|
|
name: "system ns fallback for definition ns",
|
|
setup: func(t *testing.T) {
|
|
t.Setenv(KubeVelaSystemNamespaceEnv, "vela-system-fallback")
|
|
t.Setenv(KubeVelaDefinitionNamespaceEnv, "")
|
|
},
|
|
wantVelaNS: "vela-system-fallback",
|
|
wantDefNS: "vela-system-fallback",
|
|
},
|
|
{
|
|
name: "no env vars set",
|
|
setup: func(t *testing.T) {
|
|
t.Setenv(KubeVelaSystemNamespaceEnv, "")
|
|
t.Setenv(LegacyKubeVelaSystemNamespaceEnv, "")
|
|
t.Setenv(KubeVelaDefinitionNamespaceEnv, "")
|
|
},
|
|
wantVelaNS: "default-vela",
|
|
wantDefNS: "default-def",
|
|
},
|
|
}
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
// Reset to known state before each test
|
|
if tc.name == "no env vars set" {
|
|
types.DefaultKubeVelaNS = "default-vela"
|
|
oam.SystemDefinitionNamespace = "default-def"
|
|
} else {
|
|
types.DefaultKubeVelaNS = originalVelaNS
|
|
oam.SystemDefinitionNamespace = originalDefNS
|
|
}
|
|
|
|
tc.setup(t)
|
|
BindEnvironmentVariables()
|
|
|
|
assert.Equal(t, tc.wantVelaNS, types.DefaultKubeVelaNS)
|
|
assert.Equal(t, tc.wantDefNS, oam.SystemDefinitionNamespace)
|
|
})
|
|
}
|
|
}
|