Files
kubevela/references/common/workload_test.go
AshvinBambhaniya2003 1d7b186664
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 26s
Feat: Enhance unit test coverage for references/common package (#6918)
* feat(common): Enhance unit test coverage for common utilities

This commit significantly enhances the unit test coverage for the `references/common` package, covering a wide range of utilities related to application management, metrics, registry operations, traits, and workloads. Existing tests have also been refactored to improve readability and maintainability.

Key additions and improvements include:
- **Application Utilities**: New tests for `ExportFromAppFile`, `ApplyApp`, `IsAppfile`, `Info`, `SonLeafResource`, `LoadAppFile`, and `ApplyApplication` in `application_test.go`.
- **Metrics Utilities**: Expanded tests for `ToPercentage`, `GetPodStorage`, and `GetPodOfManagedResource` in `metrics_test.go`, with existing tests refactored to use `testify/assert` and table-driven formats.
- **Registry Operations**: New tests for `InstallComponentDefinition` and `InstallTraitDefinition` in `registry_test.go`.
- **Trait Definitions**: New `trait_test.go` file with tests for `ListRawWorkloadDefinitions`.
- **Workload Initialization**: New `workload_test.go` file with tests for `InitApplication` and `BaseComplete`.

These changes collectively improve the robustness, reliability, and maintainability of the `references/common` package by providing a more comprehensive and standardized testing approach.

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

* test(common): Improve test assertions and error handling

This commit improves the quality and reliability of unit tests in the `references/common` package by addressing several inconsistencies and potential issues.

Key changes include:

- Asserts the error returned by `v1beta1.AddToScheme` across multiple test files (`application_test.go`, `registry_test.go`, `workload_test.go`) to prevent masking scheme registration failures.
- Replaces `strings.Contains` with the more idiomatic `assert.Contains` in `application_test.go`.
- Adds an assertion to check the error returned by `tmpFile.Close()` in `application_test.go`.
- Uses `assert.EqualError` instead of `assert.Equal` for comparing error messages in `registry_test.go` for more precise error checking.
- Removes an unused `strings` import from `application_test.go`.

These changes lead to more robust, readable, and consistent tests.

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

* fix(common): Fix flaky test in TestExportFromAppFile

The `TestExportFromAppFile` test was passing locally but failing in CI with a "no matches for kind" error.

This was caused by passing an uninitialized `common.Args` object to the `ExportFromAppFile` function. The function was using the client from this object, which was not the correctly configured fake client.

This commit fixes the issue by explicitly setting the fake client on the `common.Args` object before it is used, making the test hermetic and reliable.

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

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-14 11:33:21 -07:00

107 lines
3.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 common
import (
"testing"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
corecommon "github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/utils/common"
)
func TestInitApplication(t *testing.T) {
c := common.Args{}
c.SetClient(fake.NewClientBuilder().Build())
t.Run("with appGroup", func(t *testing.T) {
app, err := InitApplication("default", c, "my-workload", "my-app")
assert.NoError(t, err)
assert.NotNil(t, app)
assert.Equal(t, "my-app", app.Name)
})
t.Run("without appGroup", func(t *testing.T) {
app, err := InitApplication("default", c, "my-workload", "")
assert.NoError(t, err)
assert.NotNil(t, app)
assert.Equal(t, "my-workload", app.Name)
})
}
func TestBaseComplete(t *testing.T) {
s := runtime.NewScheme()
assert.NoError(t, v1beta1.AddToScheme(s))
template := &v1beta1.ComponentDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: "worker",
Namespace: oam.SystemDefinitionNamespace,
},
Spec: v1beta1.ComponentDefinitionSpec{
Workload: corecommon.WorkloadTypeDescriptor{
Type: types.AutoDetectWorkloadDefinition,
},
Schematic: &corecommon.Schematic{
CUE: &corecommon.CUE{
Template: `
parameter: {
image: string
port: *8080 | int
}
`,
},
},
},
}
k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(template).Build()
c := common.Args{}
c.SetClient(k8sClient)
t.Run("success", func(t *testing.T) {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.String("image", "my-image", "")
flagSet.Int64("port", 80, "")
app, err := BaseComplete(oam.SystemDefinitionNamespace, c, "my-workload", "my-app", flagSet, "worker")
assert.NoError(t, err)
assert.NotNil(t, app)
workload, ok := app.Services["my-workload"]
assert.True(t, ok)
assert.Equal(t, "my-image", workload["image"])
assert.Equal(t, int64(80), workload["port"])
})
t.Run("missing required flag", func(t *testing.T) {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
// not setting the required "image" flag
_, err := BaseComplete(oam.SystemDefinitionNamespace, c, "my-workload", "my-app", flagSet, "worker")
assert.Error(t, err)
assert.Contains(t, err.Error(), `required flag(s) "image" not set`)
})
}