Skip to content

Commit

Permalink
test: supplementary ResourceGroup-related unit tests (#451)
Browse files Browse the repository at this point in the history
## What type of PR is this?

/kind test

## What this PR does / why we need it:

Supplementary ResourceGroup-related unit tests. Increase coverage to
70%+.
  • Loading branch information
elliotxx committed May 23, 2024
1 parent ca5da5f commit 9ea61f0
Show file tree
Hide file tree
Showing 4 changed files with 330 additions and 12 deletions.
18 changes: 16 additions & 2 deletions pkg/core/entity/resource_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,24 @@ func (rg *ResourceGroup) ToSQL() string {
if rg.Name != "" {
conditions = append(conditions, fmt.Sprintf("name='%s'", rg.Name))
}
for k, v := range rg.Annotations {

annotationKeys := make([]string, 0, len(rg.Annotations))
for k := range rg.Annotations {
annotationKeys = append(annotationKeys, k)
}
sort.Strings(annotationKeys)
for _, k := range annotationKeys {
v := rg.Annotations[k]
conditions = append(conditions, fmt.Sprintf("`annotations.%s`='%s'", k, v))
}
for k, v := range rg.Labels {

labelKeys := make([]string, 0, len(rg.Labels))
for k := range rg.Labels {
labelKeys = append(labelKeys, k)
}
sort.Strings(labelKeys)
for _, k := range labelKeys {
v := rg.Labels[k]
conditions = append(conditions, fmt.Sprintf("`labels.%s`='%s'", k, v))
}

Expand Down
58 changes: 58 additions & 0 deletions pkg/core/entity/resource_group_rule_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright The Karpor 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 entity

import (
"fmt"
"github.com/stretchr/testify/require"
"testing"
)

func TestResourceGroupRule_Validate(t *testing.T) {
tests := []struct {
name string
rule *ResourceGroupRule
wantErr error
}{
{
name: "ValidRule",
rule: &ResourceGroupRule{
Name: "valid-rule",
},
wantErr: nil,
},
{
name: "NilRule",
rule: nil,
wantErr: fmt.Errorf("resource group rule is nil"),
},
{
name: "EmptyName",
rule: &ResourceGroupRule{},
wantErr: fmt.Errorf("resource group rule must have a name"),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotErr := tt.rule.Validate()
if tt.wantErr != nil {
require.EqualError(t, gotErr, tt.wantErr.Error())
} else {
require.NoError(t, gotErr)
}
})
}
}
221 changes: 211 additions & 10 deletions pkg/core/entity/resource_group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@

package entity

import "testing"
import (
"net/http"
"reflect"
"testing"

"github.com/stretchr/testify/require"
)

func TestResourceGroupHash(t *testing.T) {
tests := []struct {
Expand Down Expand Up @@ -78,20 +84,215 @@ func TestResourceGroupHash(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
gotHash := tt.rg.Hash()

if string(gotHash) != tt.wantHash {
t.Errorf("Hash() = %v, want %v", gotHash, tt.wantHash)
}
require.Equal(t, tt.wantHash, string(gotHash))

for _, equalRg := range tt.wantEqual {
if gotHash != equalRg.Hash() {
t.Errorf("Hash() of %v should be equal to %v", equalRg, tt.rg)
}
require.Equal(t, equalRg.Hash(), gotHash)
}

for _, notEqualRg := range tt.wantNotEqual {
if gotHash == notEqualRg.Hash() {
t.Errorf("Hash() of %v should not be equal to %v", notEqualRg, tt.rg)
}
require.NotEqual(t, notEqualRg.Hash(), gotHash)
}
})
}
}

func TestResourceGroupToSQL(t *testing.T) {
tests := []struct {
name string
rg ResourceGroup
wantSQL string
}{
{
name: "FullResourceGroup",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Pod",
Namespace: "default",
Name: "test-pod",
Labels: map[string]string{
"app": "myapp",
"env": "dev",
},
Annotations: map[string]string{
"note": "test",
},
},
wantSQL: "SELECT * from resources WHERE cluster='test-cluster' AND apiVersion='v1' AND kind='Pod' AND namespace='default' AND name='test-pod' AND `annotations.note`='test' AND `labels.app`='myapp' AND `labels.env`='dev'",
},
{
name: "ResourceGroupWithoutLabelsOrAnnotations",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Pod",
Namespace: "default",
Name: "test-pod",
},
wantSQL: "SELECT * from resources WHERE cluster='test-cluster' AND apiVersion='v1' AND kind='Pod' AND namespace='default' AND name='test-pod'",
},
{
name: "EmptyResourceGroup",
rg: ResourceGroup{},
wantSQL: "SELECT * from resources",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotSQL := tt.rg.ToSQL()
require.Equal(t, tt.wantSQL, gotSQL)
})
}
}

func TestResourceGroupGetType(t *testing.T) {
tests := []struct {
name string
rg ResourceGroup
want ResourceGroupType
success bool
}{
{
name: "Cluster",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "",
Kind: "",
Namespace: "",
Name: "",
},
want: Cluster,
success: true,
},
{
name: "GVK",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Pod",
Namespace: "",
Name: "",
},
want: GVK,
success: true,
},
{
name: "Namespace",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "",
Kind: "",
Namespace: "namespace-1",
Name: "",
},
want: Namespace,
success: true,
},
{
name: "ClusterGVKNamespace",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Namespace",
Namespace: "namespace-1",
},
want: ClusterGVKNamespace,
success: true,
},
{
name: "NamespaceScopedResource",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Pod",
Namespace: "default",
Name: "pod-1",
},
want: Resource,
success: true,
},
{
name: "ClusterScopedResource",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Node",
Namespace: "",
Name: "node-1",
},
want: NonNamespacedResource,
success: true,
},
{
name: "CustomResourceGroup",
rg: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Pod",
Labels: map[string]string{
"app": "myapp",
},
Annotations: map[string]string{
"note": "test",
},
},
want: Custom,
success: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, success := tt.rg.GetType()
require.Equal(t, tt.want, got)
require.Equal(t, tt.success, success)
})
}
}

func TestNewResourceGroupFromQuery(t *testing.T) {
tests := []struct {
name string
query string
want ResourceGroup
wantErr bool
}{
{
name: "ValidQuery",
query: "/api?cluster=test-cluster&apiVersion=v1&kind=Pod&namespace=default&name=test-pod&labels=app.kubernetes.io%2Fname=myapp,env=dev&annotations=note=test",
want: ResourceGroup{
Cluster: "test-cluster",
APIVersion: "v1",
Kind: "Pod",
Namespace: "default",
Name: "test-pod",
Labels: map[string]string{
"app.kubernetes.io/name": "myapp",
"env": "dev",
},
Annotations: map[string]string{
"note": "test",
},
},
wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r, err := http.NewRequest("GET", tt.query, nil)
if err != nil {
t.Fatal(err)
}
got, err := NewResourceGroupFromQuery(r)
if (err != nil) != tt.wantErr {
t.Errorf("NewResourceGroupFromQuery() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewResourceGroupFromQuery() got = %v, want %v", got, tt.want)
}
})
}
Expand Down
45 changes: 45 additions & 0 deletions pkg/core/manager/cluster/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,51 @@ func TestListCluster(t *testing.T) {
}
}

// TestListClusterName tests the ListClusterName method for retrieving a list of
// cluster names.
func TestListClusterName(t *testing.T) {
manager := NewClusterManager()
mockey.Mock((*dynamic.DynamicClient).Resource).Return(&mockNamespaceableResource{}).Build()
defer mockey.UnPatchAll()

testCases := []struct {
name string
orderBy SortCriteria
descending bool
expectError bool
}{
{
name: "List cluster names ordered by Name ascending",
orderBy: ByName,
descending: false,
expectError: false,
},
{
name: "List cluster names ordered by CreationDate descending",
orderBy: ByTimestamp,
descending: true,
expectError: false,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
names, err := manager.ListClusterName(
context.TODO(),
&multicluster.MultiClusterClient{},
tc.orderBy,
tc.descending,
)
if tc.expectError {
require.Error(t, err)
} else {
require.NoError(t, err)
require.NotNil(t, names)
}
})
}
}

// TestGetYAMLForCluster tests the GetYAMLForCluster method.
func TestGetYAMLForCluster(t *testing.T) {
manager := NewClusterManager()
Expand Down

0 comments on commit 9ea61f0

Please sign in to comment.