Skip to content

Commit

Permalink
Add Unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
mjasion committed Jun 22, 2023
1 parent 0fd0d30 commit bff1511
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 9 deletions.
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.20
require (
github.com/caitlinelfring/go-env-default v1.1.0
github.com/gin-gonic/gin v1.9.1
github.com/stretchr/testify v1.8.3
k8s.io/apimachinery v0.27.3
k8s.io/client-go v0.27.3
)
Expand All @@ -14,6 +15,7 @@ require (
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emicklei/go-restful/v3 v3.9.0 // indirect
github.com/evanphx/json-patch v4.12.0+incompatible // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-logr/logr v1.2.3 // indirect
Expand All @@ -40,6 +42,8 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/evanphx/json-patch v4.12.0+incompatible h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84=
github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
Expand Down Expand Up @@ -190,6 +191,7 @@ github.com/onsi/gomega v1.27.4 h1:Z2AnStgsdSayCMDiCU42qIz+HLqEPcgiOCXjAU/w+8E=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
Expand Down
22 changes: 13 additions & 9 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,23 @@ func main() {
leaderelection.RunOrDie(ctx, leaderElectionConfig)
}()
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"hostname": os.Getenv("HOSTNAME"),
})
})
r.GET("/", rootPage())
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")

cancel()

wg.Wait()
}

func updatePodLabel(clientset *kubernetes.Clientset) {
func rootPage() func(c *gin.Context) {
return func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"hostname": os.Getenv("HOSTNAME"),
})
}
}

func updatePodLabel(clientset kubernetes.Interface) {
// Retrieve the pod
hostname := os.Getenv("HOSTNAME")
pod, err := clientset.CoreV1().Pods(metav1.NamespaceDefault).Get(context.TODO(), hostname, metav1.GetOptions{})
Expand All @@ -106,7 +110,8 @@ func updatePodLabel(clientset *kubernetes.Clientset) {

func onStartedLeading(ctx context.Context) {
log.Println("Became leader: ", os.Getenv("HOSTNAME"))
updateServiceSelectorToCurrentPod()
clientset := getKubeConfig()
updateServiceSelectorToCurrentPod(clientset)
go func() {
for {
select {
Expand All @@ -122,8 +127,7 @@ func onStartedLeading(ctx context.Context) {
}()
}

func updateServiceSelectorToCurrentPod() {
clientset := getKubeConfig()
func updateServiceSelectorToCurrentPod(clientset kubernetes.Interface) {
service, err := clientset.CoreV1().Services(leaseNamespace).Get(context.TODO(), leaseName, metav1.GetOptions{})
if err != nil {
log.Fatal(err)
Expand Down
104 changes: 104 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package main

import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"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"
"net/http"
"net/http/httptest"
"os"
"testing"
)

func TestUpdatePodLabel(t *testing.T) {
clientset := fake.NewSimpleClientset()
os.Setenv("HOSTNAME", "test-pod")

// Create a test pod
pod := createTestPod()

// Add the pod to the fake clientset
_, err := clientset.CoreV1().Pods("default").Create(context.TODO(), pod, metav1.CreateOptions{})
assert.NoError(t, err, "Failed to create test pod")

// Update the pod label
updatePodLabel(clientset)

// Retrieve the updated pod
updatedPod, err := clientset.CoreV1().Pods("default").Get(context.TODO(), "test-pod", metav1.GetOptions{})
assert.NoError(t, err, "Failed to get updated pod")

// Verify the updated label
assert.Equal(t, "test-pod", updatedPod.Labels["pod"], "Incorrect pod label")
}

func TestUpdateServiceSelectorToCurrentPod(t *testing.T) {
clientset := fake.NewSimpleClientset()
os.Setenv("HOSTNAME", "test-pod")

// Create a test service
service := createTestService()

// Add the service to the fake clientset
_, err := clientset.CoreV1().Services("default").Create(context.TODO(), service, metav1.CreateOptions{})
assert.NoError(t, err, "Failed to create test service")

// Update the service selector
updateServiceSelectorToCurrentPod(clientset)

// Retrieve the updated service
updatedService, err := clientset.CoreV1().Services("default").Get(context.TODO(), "k8s-leader-example", metav1.GetOptions{})
assert.NoError(t, err, "Failed to get updated service")

// Verify the updated selector
assert.Equal(t, "test-pod", updatedService.Spec.Selector["pod"], "Incorrect service selector")
}

func TestStatusPageHandler(t *testing.T) {
// Create a test HTTP request
req := httptest.NewRequest("GET", "/", nil)

// Create a test HTTP response recorder
res := httptest.NewRecorder()

// Create a Gin router
router := gin.Default()
router.GET("/", rootPage())

// Serve the HTTP request
router.ServeHTTP(res, req)

// Verify the HTTP response status code
assert.Equal(t, http.StatusOK, res.Code, "Incorrect status code")

// Verify the response body
expectedBody := fmt.Sprintf(`{"hostname":"%s"}`, os.Getenv("HOSTNAME"))
assert.Equal(t, expectedBody, res.Body.String(), "Incorrect response body")
}

func createTestPod() *corev1.Pod {
return &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
Namespace: "default",
Labels: map[string]string{},
},
}
}

func createTestService() *corev1.Service {
return &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "k8s-leader-example",
Namespace: "default",
Labels: map[string]string{},
},
Spec: corev1.ServiceSpec{
Selector: map[string]string{},
},
}
}

0 comments on commit bff1511

Please sign in to comment.