Skip to content

Commit

Permalink
use namespace arg
Browse files Browse the repository at this point in the history
  • Loading branch information
bdrennz committed Sep 20, 2024
1 parent 111fb71 commit 51908cf
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 148 deletions.
2 changes: 1 addition & 1 deletion pkg/cmd/config/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func NewCommand(ctx context.Context) *cli.Command {
return err
}

kubeStateMetricsURL, nodeExporterURL, err := k8s.GetServiceURLs(ctx, clientset)
kubeStateMetricsURL, nodeExporterURL, err := k8s.GetServiceURLs(ctx, clientset, namespace)
if err != nil {
return err
}
Expand Down
13 changes: 8 additions & 5 deletions pkg/cmd/config/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@ import (
)

func TestGenerate(t *testing.T) {
// Define the namespace to be used in the test
namespace := "test-namespace"

// Create a fake clientset with some services
clientset := fake.NewSimpleClientset(
&corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-state-metrics",
Namespace: "default",
Namespace: namespace,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
Expand All @@ -31,7 +34,7 @@ func TestGenerate(t *testing.T) {
&corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "node-exporter",
Namespace: "default",
Namespace: namespace,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
Expand All @@ -44,7 +47,7 @@ func TestGenerate(t *testing.T) {
ctx, _ := context.WithCancel(context.Background())

// Fetch service URLs
kubeStateMetricsURL, nodeExporterURL, err := k8s.GetServiceURLs(ctx, clientset)
kubeStateMetricsURL, nodeExporterURL, err := k8s.GetServiceURLs(ctx, clientset, namespace)
assert.NoError(t, err)

// Define the scrape config data
Expand Down Expand Up @@ -73,11 +76,11 @@ func TestGenerate(t *testing.T) {
}

// Update the ConfigMap
err = k8s.UpdateConfigMap(ctx, clientset, "default", "test-configmap", configMapData)
err = k8s.UpdateConfigMap(ctx, clientset, namespace, "test-configmap", configMapData)
assert.NoError(t, err)

// Verify the ConfigMap was updated
updatedConfigMap, err := clientset.CoreV1().ConfigMaps("default").Get(ctx, "test-configmap", metav1.GetOptions{})
updatedConfigMap, err := clientset.CoreV1().ConfigMaps(namespace).Get(ctx, "test-configmap", metav1.GetOptions{})
assert.NoError(t, err)
assert.Equal(t, configContent, updatedConfigMap.Data["prometheus.yml"])

Expand Down
4 changes: 2 additions & 2 deletions pkg/k8s/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ func BuildKubeClient(kubeconfigPath string) (kubernetes.Interface, error) {
}

// GetServiceURLs fetches the URLs for services containing the substrings "kube-state-metrics" and "node-exporter"
func GetServiceURLs(ctx context.Context, clientset kubernetes.Interface) (string, string, error) {
services, err := clientset.CoreV1().Services("default").List(ctx, metav1.ListOptions{})
func GetServiceURLs(ctx context.Context, clientset kubernetes.Interface, namespace string) (string, string, error) {
services, err := clientset.CoreV1().Services(namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return "", "", errors.Wrap(err, "listing services")
}
Expand Down
229 changes: 89 additions & 140 deletions pkg/k8s/services_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,174 +2,123 @@ package k8s_test

import (
"context"
"os"
"testing"

"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"

"github.com/cloudzero/cloudzero-agent-validator/pkg/k8s"
)

// TestGetServiceURLs tests the GetServiceURLs function
func TestGetServiceURLs(t *testing.T) {
tests := []struct {
name string
services []corev1.Service
expectedKubeStateURL string
expectedNodeExporterURL string
expectError bool
}{
{
name: "Both services found",
services: []corev1.Service{
{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-state-metrics",
Namespace: "default",
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{Port: 8080},
},
},
},
{
ObjectMeta: metav1.ObjectMeta{
Name: "node-exporter",
Namespace: "default",
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{Port: 9100},
},
},
},
},
expectedKubeStateURL: "http://kube-state-metrics.default.svc.cluster.local:8080",
expectedNodeExporterURL: "http://node-exporter.default.svc.cluster.local:9100",
expectError: false,
clientset := fake.NewSimpleClientset()
ctx := context.TODO()
namespace := "test-namespace"

// Create fake services in the test namespace
_, err := clientset.CoreV1().Services(namespace).Create(ctx, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-state-metrics",
Namespace: namespace,
},
{
name: "Kube-state-metrics service not found",
services: []corev1.Service{
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
ObjectMeta: metav1.ObjectMeta{
Name: "node-exporter",
Namespace: "default",
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{Port: 9100},
},
},
Port: 8080,
},
},
expectedKubeStateURL: "",
expectedNodeExporterURL: "",
expectError: true,
},
{
name: "Node-exporter service not found",
services: []corev1.Service{
}, metav1.CreateOptions{})
assert.NoError(t, err)

_, err = clientset.CoreV1().Services(namespace).Create(ctx, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "node-exporter",
Namespace: namespace,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-state-metrics",
Namespace: "default",
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{Port: 8080},
},
},
Port: 9100,
},
},
expectedKubeStateURL: "",
expectedNodeExporterURL: "",
expectError: true,
},
}
}, metav1.CreateOptions{})
assert.NoError(t, err)

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clientset := fake.NewSimpleClientset(&corev1.ServiceList{Items: tt.services})

kubeStateMetricsURL, nodeExporterURL, err := k8s.GetServiceURLs(context.Background(), clientset)
if (err != nil) != tt.expectError {
t.Errorf("GetServiceURLs() error = %v, expectError %v", err, tt.expectError)
return
}
if kubeStateMetricsURL != tt.expectedKubeStateURL {
t.Errorf("GetServiceURLs() kubeStateMetricsURL = %v, expected %v", kubeStateMetricsURL, tt.expectedKubeStateURL)
}
if nodeExporterURL != tt.expectedNodeExporterURL {
t.Errorf("GetServiceURLs() nodeExporterURL = %v, expected %v", nodeExporterURL, tt.expectedNodeExporterURL)
}
})
}
kubeStateMetricsURL, nodeExporterURL, err := k8s.GetServiceURLs(ctx, clientset, namespace)
assert.NoError(t, err)
assert.Contains(t, kubeStateMetricsURL, "kube-state-metrics")
assert.Contains(t, nodeExporterURL, "node-exporter")
}

// TestUpdateConfigMap tests the UpdateConfigMap function
func TestUpdateConfigMap(t *testing.T) {
tests := []struct {
name string
initialConfigMap *corev1.ConfigMap
updatedData map[string]string
expectError bool
}{
{
name: "Update ConfigMap successfully",
initialConfigMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "test-configmap",
Namespace: "default",
},
Data: map[string]string{
"key1": "value1",
},
},
updatedData: map[string]string{
"key1": "new-value1",
"key2": "value2",
},
expectError: false,
clientset := fake.NewSimpleClientset()
ctx := context.TODO()
namespace := "test-namespace"

// Create a ConfigMap
configMap := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "test-configmap",
Namespace: namespace,
},
{
name: "Create ConfigMap successfully",
initialConfigMap: nil,
updatedData: map[string]string{
"key1": "value1",
"key2": "value2",
},
expectError: false,
Data: map[string]string{
"key1": "value1",
},
}
_, err := clientset.CoreV1().ConfigMaps(namespace).Create(ctx, configMap, metav1.CreateOptions{})
assert.NoError(t, err)

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clientset := fake.NewSimpleClientset()
if tt.initialConfigMap != nil {
clientset = fake.NewSimpleClientset(tt.initialConfigMap)
}
// Update the ConfigMap
newData := map[string]string{
"key1": "new-value1",
"key2": "value2",
}
err = k8s.UpdateConfigMap(ctx, clientset, namespace, "test-configmap", newData)
assert.NoError(t, err)

err := k8s.UpdateConfigMap(context.Background(), clientset, "default", "test-configmap", tt.updatedData)
if (err != nil) != tt.expectError {
t.Errorf("UpdateConfigMap() error = %v, expectError %v", err, tt.expectError)
return
}
// Verify the ConfigMap was updated
updatedConfigMap, err := clientset.CoreV1().ConfigMaps(namespace).Get(ctx, "test-configmap", metav1.GetOptions{})
assert.NoError(t, err)
assert.Equal(t, newData, updatedConfigMap.Data)
}

// Verify the ConfigMap was updated or created
updatedConfigMap, err := clientset.CoreV1().ConfigMaps("default").Get(context.Background(), "test-configmap", metav1.GetOptions{})
if err != nil {
t.Errorf("GetConfigMap() error = %v", err)
return
}
func TestBuildKubeClient(t *testing.T) {
// Create a temporary kubeconfig file
kubeconfigContent := `
apiVersion: v1
clusters:
- cluster:
server: https://127.0.0.1:6443
name: test-cluster
contexts:
- context:
cluster: test-cluster
user: test-user
name: test-context
current-context: test-context
kind: Config
preferences: {}
users:
- name: test-user
user:
token: test-token
`
tmpfile, err := os.CreateTemp("", "kubeconfig")
assert.NoError(t, err)
defer os.Remove(tmpfile.Name()) // clean up

for key, expectedValue := range tt.updatedData {
if updatedConfigMap.Data[key] != expectedValue {
t.Errorf("ConfigMap data mismatch for key %s: got %v, expected %v", key, updatedConfigMap.Data[key], expectedValue)
}
}
})
}
_, err = tmpfile.Write([]byte(kubeconfigContent))
assert.NoError(t, err)
err = tmpfile.Close()
assert.NoError(t, err)

// Build the kube client using the temporary kubeconfig file
clientset, err := k8s.BuildKubeClient(tmpfile.Name())
assert.NoError(t, err)
assert.NotNil(t, clientset)
}

0 comments on commit 51908cf

Please sign in to comment.