Skip to content

Commit

Permalink
test:add some test cases for kosmos
Browse files Browse the repository at this point in the history
Signed-off-by: qiuwei <qiuwei_yewu@cmss.chinamobile.com>
  • Loading branch information
qiuwei68 committed Sep 27, 2024
1 parent f826fe5 commit efb5bfe
Show file tree
Hide file tree
Showing 19 changed files with 6,470 additions and 1 deletion.
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ require (
github.com/spf13/cobra v1.6.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.12.0
github.com/stretchr/testify v1.9.0
github.com/vishvananda/netlink v1.2.1-beta.2.0.20220630165224-c591ada0fb2b
golang.org/x/sys v0.12.0
golang.org/x/term v0.12.0
Expand Down Expand Up @@ -139,6 +140,7 @@ require (
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/projectcalico/go-json v0.0.0-20161128004156-6219dc7339ba // indirect
github.com/projectcalico/go-yaml-wrapper v0.0.0-20191112210931-090425220c54 // indirect
github.com/prometheus/client_golang v1.14.0 // indirect
Expand All @@ -149,7 +151,6 @@ require (
github.com/spf13/afero v1.9.2 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/stoewer/go-strcase v1.2.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/subosito/gotenv v1.3.0 // indirect
github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f // indirect
github.com/xlab/treeprint v1.1.0 // indirect
Expand Down
92 changes: 92 additions & 0 deletions pkg/kubenest/util/api-client/check_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package util

import (
"fmt"
"testing"
"time"

"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake" // 使用 kubernetes 的 fake 客户端
)

// TestVirtualClusterChecker_WaitForSomePods 测试 WaitForSomePods 方法
func TestVirtualClusterChecker_WaitForSomePods(t *testing.T) {
// 创建一个 fake 客户端,包含一些 Pod
client := fake.NewSimpleClientset(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod-1",
Namespace: "default",
Labels: map[string]string{"app": "test"},
},
Status: corev1.PodStatus{
Phase: corev1.PodRunning,
Conditions: []corev1.PodCondition{
{Type: corev1.PodReady, Status: corev1.ConditionTrue},
},
},
}, &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod-2",
Namespace: "default",
Labels: map[string]string{"app": "test"},
},
Status: corev1.PodStatus{
Phase: corev1.PodRunning,
Conditions: []corev1.PodCondition{
{Type: corev1.PodReady, Status: corev1.ConditionTrue},
},
},
})

checker := NewVirtualClusterChecker(client, 10*time.Second)
err := checker.WaitForSomePods("app=test", "default", 2)
assert.NoError(t, err)
}

// TestVirtualClusterChecker_WaitForSomePods_Error 测试 WaitForSomePods 方法失败情况
func TestVirtualClusterChecker_WaitForSomePods_Error(t *testing.T) {
// 创建一个 fake 客户端,包含一些 Pod
client := fake.NewSimpleClientset(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod-1",
Namespace: "default",
Labels: map[string]string{"app": "test"},
},
Status: corev1.PodStatus{
Phase: corev1.PodRunning,
Conditions: []corev1.PodCondition{
{Type: corev1.PodReady, Status: corev1.ConditionFalse},
},
},
})

checker := NewVirtualClusterChecker(client, 10*time.Second)
err := checker.WaitForSomePods("app=test1", "default", 2)
assert.Error(t, err)
}

// TestTryRunCommand 测试 TryRunCommand 函数
func TestTryRunCommand(t *testing.T) {
count := 0
f := func() error {
count++
if count < 3 {
return fmt.Errorf("error")
}
return nil
}

err := TryRunCommand(f, 3)
assert.NoError(t, err)
}

func TestTryRunCommand_Error(t *testing.T) {
f := func() error {
return fmt.Errorf("error")
}

err := TryRunCommand(f, 1)
assert.Error(t, err)
}
85 changes: 85 additions & 0 deletions pkg/kubenest/util/cert/store_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package cert

import (
"testing"

"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"

"github.com/kosmos.io/kosmos/pkg/kubenest/constants"
)

func TestVirtualClusterCertStore_AddCert(t *testing.T) {
store := NewCertStore()
cert := &VirtualClusterCert{pairName: "test-cert", cert: []byte("test-cert-data"), key: []byte("test-key-data")}
store.AddCert(cert)

// 确保添加的证书可以被正确获取
retrievedCert := store.GetCert("test-cert")
assert.NotNil(t, retrievedCert, "Expected to retrieve the added certificate")
assert.Equal(t, cert, retrievedCert, "Retrieved certificate should match the added certificate")
}

func TestVirtualClusterCertStore_GetCert(t *testing.T) {
store := NewCertStore()
cert := &VirtualClusterCert{pairName: "test-cert", cert: []byte("test-cert-data"), key: []byte("test-key-data")}
store.AddCert(cert)

// 测试获取存在的证书
retrievedCert := store.GetCert("test-cert")
assert.NotNil(t, retrievedCert, "Expected to retrieve the added certificate")
assert.Equal(t, cert, retrievedCert, "Retrieved certificate should match the added certificate")

// 测试获取不存在的证书
retrievedCert = store.GetCert("nonexistent-cert")
assert.Nil(t, retrievedCert, "Expected no certificate for a nonexistent name")
}

func TestVirtualClusterCertStore_CertList(t *testing.T) {
store := NewCertStore()
cert1 := &VirtualClusterCert{pairName: "cert1"}
cert2 := &VirtualClusterCert{pairName: "cert2"}
store.AddCert(cert1)
store.AddCert(cert2)

certs := store.CertList()
assert.Len(t, certs, 2, "Expected the certificate list to contain 2 certificates")
assert.Contains(t, certs, cert1, "Expected cert1 to be in the certificate list")
assert.Contains(t, certs, cert2, "Expected cert2 to be in the certificate list")
}

func TestVirtualClusterCertStore_LoadCertFromSecret(t *testing.T) {
store := NewCertStore()

// 创建一个包含证书和密钥的 secret
secret := &corev1.Secret{
Data: map[string][]byte{
"test-cert" + constants.CertExtension: []byte("test-cert-data"),
"test-cert" + constants.KeyExtension: []byte("test-key-data"),
},
}

// 加载证书
err := store.LoadCertFromSecret(secret)
assert.NoError(t, err, "Expected no error when loading cert from secret")

// 确保可以成功获取证书
cert := store.GetCert("test-cert")
assert.NotNil(t, cert, "Expected to retrieve the certificate after loading from secret")
assert.Equal(t, []byte("test-cert-data"), cert.cert, "Expected cert data to match")
assert.Equal(t, []byte("test-key-data"), cert.key, "Expected key data to match")
}

func TestVirtualClusterCertStore_LoadCertFromEmptySecret(t *testing.T) {
store := NewCertStore()

// 创建一个空的 secret
secret := &corev1.Secret{
Data: map[string][]byte{},
}

// 尝试加载证书,应该返回错误
err := store.LoadCertFromSecret(secret)
assert.Error(t, err, "Expected error when loading cert from empty secret")
assert.Equal(t, "cert data is empty", err.Error(), "Expected error message to match")
}
118 changes: 118 additions & 0 deletions pkg/utils/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package utils

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
)

func TestContainsStringInUtils(t *testing.T) {
tests := []struct {
arr []string
s string
expect bool
}{
{[]string{"apple", "banana", "cherry"}, "ban", true},
{[]string{"apple", "banana", "cherry"}, "berry", false},
{[]string{"apple", "banana", "cherry"}, "apple", true},
{[]string{"apple", "banana", "cherry"}, "plum", false},
}

for _, test := range tests {
result := ContainsString(test.arr, test.s)
assert.Equal(t, test.expect, result, "Expected ContainsString(%v, %s) to be %v", test.arr, test.s, test.expect)
}
}

func TestIsIPv6InUtils(t *testing.T) {
tests := []struct {
ip string
expect bool
}{
{"192.168.1.1", false},
{"::1", true},
{"2001:db8::1", true},
{"127.0.0.1", false},
}

for _, test := range tests {
result := IsIPv6(test.ip)
assert.Equal(t, test.expect, result, "Expected IsIPv6(%s) to be %v", test.ip, test.expect)
}
}

func TestGetEnvWithDefaultValueInUtils(t *testing.T) {
os.Setenv("EXISTING_ENV", "value")
defer os.Unsetenv("EXISTING_ENV")

tests := []struct {
envName string
defaultValue string
expected string
}{
{"EXISTING_ENV", "default", "value"},
{"NON_EXISTING_ENV", "default", "default"},
}

for _, test := range tests {
result := GetEnvWithDefaultValue(test.envName, test.defaultValue)
assert.Equal(t, test.expected, result, "Expected GetEnvWithDefaultValue(%s, %s) to be %s", test.envName, test.defaultValue, test.expected)
}
}

func TestGenerateAddrStrInUtils(t *testing.T) {
tests := []struct {
addr string
port string
expect string
}{
{"192.168.1.1", "8080", "192.168.1.1:8080"},
{"::1", "8080", "[::1]:8080"},
{"2001:db8::1", "8080", "[2001:db8::1]:8080"},
}

for _, test := range tests {
result := GenerateAddrStr(test.addr, test.port)
assert.Equal(t, test.expect, result, "Expected GenerateAddrStr(%s, %s) to be %s", test.addr, test.port, test.expect)
}
}

func TestIPFamilyGeneratorInUtils(t *testing.T) {
tests := []struct {
apiServerServiceSubnet string
expect []corev1.IPFamily
}{
{"192.168.0.0/16", []corev1.IPFamily{corev1.IPv4Protocol}},
{"2001:db8::/32", []corev1.IPFamily{corev1.IPv6Protocol}},
{"192.168.0.0/16,2001:db8::/32", []corev1.IPFamily{corev1.IPv4Protocol, corev1.IPv6Protocol}},
}

for _, test := range tests {
result := IPFamilyGenerator(test.apiServerServiceSubnet)
assert.Equal(t, test.expect, result, "Expected IPFamilyGenerator(%s) to be %v", test.apiServerServiceSubnet, test.expect)
}
}

func TestFormatCIDRInUtils(t *testing.T) {
tests := []struct {
cidr string
expect string
hasError bool
}{
{"192.168.0.0/16", "192.168.0.0/16", false},
{"2001:db8::/32", "2001:db8::/32", false},
{"invalid_cidr", "", true},
}

for _, test := range tests {
result, err := FormatCIDR(test.cidr)
if test.hasError {
assert.Error(t, err, "Expected FormatCIDR(%s) to return an error", test.cidr)
} else {
assert.NoError(t, err, "Expected FormatCIDR(%s) to not return an error", test.cidr)
assert.Equal(t, test.expect, result, "Expected FormatCIDR(%s) to be %s", test.cidr, test.expect)
}
}
}
27 changes: 27 additions & 0 deletions vendor/github.com/pmezard/go-difflib/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit efb5bfe

Please sign in to comment.