Files
kubevela/pkg/config/factory_test.go
AshvinBambhaniya2003 72d5c2f0a5 Feat(tests): Add unit test coverage for core packages (#6880)
* feat(config): add unit test for config pkg

- add unit test cases for writer.go file
- add unit test cases for factory.go file

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

* feat(auth): add unit tests for auth package

This commit introduces a comprehensive suite of unit tests for the `pkg/auth` package, significantly improving test coverage and ensuring the correctness of the authentication and authorization logic.

The following key areas are now covered:
- **Identity:** Tests for identity creation, validation, matching, and subject generation.
- **Kubeconfig:** Tests for kubeconfig generation options, certificate creation, and identity reading from kubeconfig.
- **Privileges:** Tests for privilege description implementations, listing privileges, and pretty-printing.

By adding these tests, we increase the robustness of the auth package and make future refactoring safer.

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

* feat(oam): add unit tests for auxiliary functions

This commit adds comprehensive unit tests for the auxiliary functions in the pkg/oam package. The new tests cover the following functions:

- GetPublishVersion / SetPublishVersion
- GetDeployVersion
- GetLastAppliedTime
- GetControllerRequirement / SetControllerRequirement
- GetCluster / SetCluster / SetClusterIfEmpty

These tests address the lack of coverage for these functions and ensure their behavior is correct, including edge cases like handling missing annotations or removing annotations when set to an empty string.

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

* feat(cue): add unit tests for cue packages

This commit enhances the test coverage of the `pkg/cue` directory by adding unit tests for the `definition`, `script`, and `task` packages.

The new tests cover the following areas:
- `pkg/cue/definition`:
  - `TestWorkloadGetTemplateContext`: Verifies the template context retrieval for workloads.
  - `TestTraitGetTemplateContext`: Ensures correct template context retrieval for traits.
  - `TestGetCommonLabels`: Checks the conversion of context labels to OAM labels.
  - `TestGetBaseContextLabels`: Validates the creation of base context labels.
- `pkg/cue/script`:
  - Adds tests for `ParseToValue`, `ParseToValueWithCueX`, `ParseToTemplateValue`, and `ParseToTemplateValueWithCueX` to ensure CUE scripts are parsed correctly.
- `pkg/cue/task`:
  - Refactors the existing test for `Process` to use a table-driven approach, improving readability and covering more cases.

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

* fix(tests): address PR comments and improve test reliability

This commit addresses several comments from a pull request review, improving the reliability and correctness of tests in various packages.

The following changes are included:

- **`pkg/config/writer`**:
  - Renamed `writter_test.go` to `writer_test.go` to fix a typo.

- **`pkg/cue/task`**:
  - Replaced the use of an external invalid URL with a local unreachable endpoint (`http://127.0.0.1:3000`) in `process_test.go` to prevent network flakiness.
  - Switched to using `assert.ErrorContains` for safer error message assertions, avoiding potential panics.
  - Corrected an assertion to compare a byte slice with a string by converting the byte slice to a string first.

- **`pkg/oam`**:
  - Updated `auxliary_test.go` to use `time.Time.Equal` for time comparisons, making the test robust against timezone differences.

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

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-09-03 05:58:58 +08:00

265 lines
9.5 KiB
Go

/*
Copyright 2022 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 config
import (
"context"
"os"
"testing"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/stretchr/testify/require"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/oam-dev/kubevela/apis/types"
nacosmock "github.com/oam-dev/kubevela/test/mock/nacos"
)
func TestParseConfigTemplate(t *testing.T) {
r := require.New(t)
content, err := os.ReadFile("testdata/helm-repo.cue")
r.Equal(err, nil)
var inf = &kubeConfigFactory{}
template, err := inf.ParseTemplate(context.Background(), "default", content)
r.Equal(err, nil)
r.NotEqual(template, nil)
r.Equal(template.Name, "default")
r.NotEqual(template.Schema, nil)
r.Equal(len(template.Schema.Properties), 4)
}
var _ = Describe("test config factory", func() {
var fac Factory
BeforeEach(func() {
fac = NewConfigFactory(k8sClient)
})
It("apply the nacos server template", func() {
data, err := os.ReadFile("./testdata/nacos-server.cue")
Expect(err).Should(BeNil())
t, err := fac.ParseTemplate(context.Background(), "", data)
Expect(err).Should(BeNil())
Expect(fac.CreateOrUpdateConfigTemplate(context.TODO(), "default", t)).Should(BeNil())
})
It("apply a config to the nacos server", func() {
By("create a nacos server config")
nacos, err := fac.ParseConfig(context.TODO(), NamespacedName{Name: "nacos-server", Namespace: "default"}, Metadata{NamespacedName: NamespacedName{Name: "nacos", Namespace: "default"}, Properties: map[string]interface{}{
"servers": []map[string]interface{}{{
"ipAddr": "127.0.0.1",
"port": 8849,
}},
}})
Expect(err).Should(BeNil())
Expect(len(nacos.Secret.Data[SaveInputPropertiesKey]) > 0).Should(BeTrue())
Expect(fac.CreateOrUpdateConfig(context.Background(), nacos, "default")).Should(BeNil())
config, err := fac.ReadConfig(context.TODO(), "default", "nacos")
Expect(err).Should(BeNil())
servers, ok := config["servers"].([]interface{})
Expect(ok).Should(BeTrue())
Expect(len(servers)).Should(Equal(1))
By("apply a template that with the nacos writer")
data, err := os.ReadFile("./testdata/mysql-db-nacos.cue")
Expect(err).Should(BeNil())
t, err := fac.ParseTemplate(context.Background(), "", data)
Expect(err).Should(BeNil())
Expect(t.ExpandedWriter.Nacos).ShouldNot(BeNil())
Expect(t.ExpandedWriter.Nacos.Endpoint.Name).Should(Equal("nacos"))
Expect(fac.CreateOrUpdateConfigTemplate(context.TODO(), "default", t)).Should(BeNil())
db, err := fac.ParseConfig(context.TODO(), NamespacedName{Name: "nacos", Namespace: "default"}, Metadata{NamespacedName: NamespacedName{Name: "db-config", Namespace: "default"}, Properties: map[string]interface{}{
"dataId": "dbconfig",
"appName": "db",
"content": map[string]interface{}{
"mysqlHost": "127.0.0.1:3306",
"mysqlPort": 3306,
"username": "test",
"password": "string",
},
}})
Expect(err).Should(BeNil())
Expect(db.Template.ExpandedWriter).ShouldNot(BeNil())
Expect(db.ExpandedWriterData).ShouldNot(BeNil())
Expect(len(db.ExpandedWriterData.Nacos.Content) > 0).Should(BeTrue())
Expect(db.ExpandedWriterData.Nacos.Metadata.DataID).Should(Equal("dbconfig"))
Expect(len(db.OutputObjects)).Should(Equal(1))
nacosClient := nacosmock.NewMockIConfigClient(ctl)
db.ExpandedWriterData.Nacos.Client = nacosClient
nacosClient.EXPECT().PublishConfig(gomock.Any()).Return(true, nil)
Expect(err).Should(BeNil())
Expect(fac.CreateOrUpdateConfig(context.Background(), db, "default")).Should(BeNil())
})
It("list all templates", func() {
templates, err := fac.ListTemplates(context.TODO(), "", "")
Expect(err).Should(BeNil())
Expect(len(templates)).Should(Equal(2))
})
It("list all configs", func() {
configs, err := fac.ListConfigs(context.TODO(), "", "", "", true)
Expect(err).Should(BeNil())
Expect(len(configs)).Should(Equal(2))
})
It("distribute a config", func() {
err := fac.CreateOrUpdateDistribution(context.TODO(), "default", "distribute-db-config", &CreateDistributionSpec{
Configs: []*NamespacedName{
{Name: "db-config", Namespace: "default"},
},
Targets: []*ClusterTarget{
{ClusterName: "local", Namespace: "test"},
},
})
Expect(err).Should(BeNil())
})
It("get the config", func() {
config, err := fac.GetConfig(context.TODO(), "default", "db-config", true)
Expect(err).Should(BeNil())
Expect(len(config.ObjectReferences)).ShouldNot(BeNil())
Expect(config.ObjectReferences[0].Kind).Should(Equal("ConfigMap"))
Expect(len(config.Targets)).Should(Equal(1))
})
It("check if the config exist", func() {
exist, err := fac.IsExist(context.TODO(), "default", "db-config")
Expect(err).Should(BeNil())
Expect(exist).Should(BeTrue())
})
It("list the distributions", func() {
distributions, err := fac.ListDistributions(context.TODO(), "default")
Expect(err).Should(BeNil())
Expect(len(distributions)).Should(Equal(1))
})
It("delete the distribution", func() {
err := fac.DeleteDistribution(context.TODO(), "default", "distribute-db-config")
Expect(err).Should(BeNil())
})
It("delete the config", func() {
err := fac.DeleteConfig(context.TODO(), "default", "db-config")
Expect(err).Should(BeNil())
})
It("delete the config template", func() {
err := fac.DeleteTemplate(context.TODO(), "default", "nacos")
Expect(err).Should(BeNil())
})
It("should fail to parse template with invalid CUE syntax", func() {
_, err := fac.ParseTemplate(context.Background(), "invalid-cue", []byte("metadata: { name: }"))
Expect(err).To(HaveOccurred())
})
It("should fail to parse template missing template block", func() {
_, err := fac.ParseTemplate(context.Background(), "missing-template", []byte(`metadata: { name: "t" }`))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("template"))
})
It("should fail to parse config when template not found", func() {
_, err := fac.ParseConfig(context.TODO(), NamespacedName{Name: "non-existent-template", Namespace: "default"}, Metadata{})
Expect(err).To(Equal(ErrTemplateNotFound))
})
It("should parse a template-less config", func() {
config, err := fac.ParseConfig(context.TODO(), NamespacedName{}, Metadata{
NamespacedName: NamespacedName{Name: "template-less-config", Namespace: "default"},
Properties: map[string]interface{}{"key": "value"},
})
Expect(err).ShouldNot(HaveOccurred())
Expect(config.Name).To(Equal("template-less-config"))
Expect(config.Secret.Labels[types.LabelConfigType]).To(Equal(""))
})
It("should fail to update config when changing the template", func() {
nacos, err := fac.ParseConfig(context.TODO(), NamespacedName{Name: "nacos-server", Namespace: "default"}, Metadata{NamespacedName: NamespacedName{Name: "config-to-change", Namespace: "default"}, Properties: map[string]interface{}{
"servers": []map[string]interface{}{{
"ipAddr": "127.0.0.1",
"port": 8849,
}},
}})
Expect(err).ShouldNot(HaveOccurred())
Expect(fac.CreateOrUpdateConfig(context.Background(), nacos, "default")).ShouldNot(HaveOccurred())
nacos.Template.Name = "another-template"
err = fac.CreateOrUpdateConfig(context.Background(), nacos, "default")
Expect(err).To(Equal(ErrChangeTemplate))
})
It("should return error when getting a sensitive config", func() {
sensitiveTpl, err := fac.ParseTemplate(context.Background(), "", []byte(`
metadata: { name: "sensitive-tpl", sensitive: true }
template: { parameter: { key: string } }
`))
Expect(err).ShouldNot(HaveOccurred())
Expect(fac.CreateOrUpdateConfigTemplate(context.TODO(), "default", sensitiveTpl)).ShouldNot(HaveOccurred())
sensitiveConfig, err := fac.ParseConfig(context.TODO(), NamespacedName{Name: "sensitive-tpl", Namespace: "default"}, Metadata{
NamespacedName: NamespacedName{Name: "sensitive-config", Namespace: "default"},
Properties: map[string]interface{}{"key": "secret-value"},
})
Expect(err).ShouldNot(HaveOccurred())
Expect(fac.CreateOrUpdateConfig(context.Background(), sensitiveConfig, "default")).ShouldNot(HaveOccurred())
_, err = fac.GetConfig(context.TODO(), "default", "sensitive-config", false)
Expect(err).To(Equal(ErrSensitiveConfig))
})
It("should fail to delete a secret that is not a KubeVela config", func() {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{Name: "not-a-config", Namespace: "default"},
Data: map[string][]byte{"key": []byte("value")},
}
Expect(k8sClient.Create(context.TODO(), secret)).ShouldNot(HaveOccurred())
err := fac.DeleteConfig(context.TODO(), "default", "not-a-config")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("is not a config"))
})
It("should fail to convert configmap to template if labels are missing", func() {
cm := v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{Name: "no-labels"},
}
_, err := convertConfigMap2Template(cm)
Expect(err).To(HaveOccurred())
})
It("should fail to convert secret to config if labels are missing", func() {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{Name: "no-labels"},
}
_, err := convertSecret2Config(secret)
Expect(err).To(HaveOccurred())
})
})