"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Create Simple Tests for Client-Go Using a Fake Client?

How to Create Simple Tests for Client-Go Using a Fake Client?

Published on 2024-11-13
Browse:799

How to Create Simple Tests for Client-Go Using a Fake Client?

How to Write Simple Tests for Client-Go Using a Fake Client

Problem Overview

In this case, we aim to compose a test function for the GetNamespaceCreationTime function, which is meant to retrieve the creation timestamp for a particular Kubernetes namespace. However, you face difficulty finding a suitable approach to incorporate the initialization logic and interact with the fake client.

Test Implementation

To effectively test the GetNamespaceCreationTime function, the initialization process should not reside within the function itself. Instead, the Kubernetes client interface should be passed as a parameter to the function.

Replace the existing code in the GetNamespaceCreationTime function with the following:

import (
  "fmt"
  "k8s.io/api/core/v1"
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  "time"
)

func GetNamespaceCreationTime(kubeClient kubernetes.Interface, namespace string) int64 {
  ns, err := kubeClient.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%v \n", ns.CreationTimestamp)
  return ns.GetCreationTimestamp().Unix()
}

Next, define a function to obtain the client set:

func GetClientSet() kubernetes.Interface {
  config, err := rest.InClusterConfig()
  if err != nil {
    log.Warnf("Could not get in-cluster config: %s", err)
    return nil, err
  }

  client, err := kubernetes.NewForConfig(config)
  if err != nil {
    log.Warnf("Could not connect to in-cluster API server: %s", err)
    return nil, err
  }

  return client, err
}

Test Function

Within the TestGetNamespaceCreationTime function, instantiate the fake client and invoke the GetNamespaceCreationTIme method:

func TestGetNamespaceCreationTime(t *testing.T) {
  kubeClient := fake.NewSimpleClientset()
  got := GetNamespaceCreationTime(kubeClient, "default")
  want := int64(1257894000)

  nsMock := config.CoreV1().Namespaces()
  nsMock.Create(&v1.Namespace{
    ObjectMeta: metav1.ObjectMeta{
      Name:              "default",
      CreationTimestamp: metav1.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
    },
  })

  if got != want {
    t.Errorf("got %q want %q", got, want)
  }
}

This test ensures that the expected creation timestamp for the "default" namespace is accurately retrieved using the fake client.

Additional Testability Enhancements

Consider introducing mock functions to enhance the testability and flexibility of the code, such as:

func fakeGetInclusterConfig() (*rest.Config, error) {
  return nil, nil
}

func fakeGetInclusterConfigWithError() (*rest.Config, error) {
  return nil, errors.New("fake error getting in-cluster config")
}

These methods allow for more robust testing scenarios, where you can assert behaviors for both successful and failed in-cluster configuration retrieval.

Release Statement This article is reproduced at: 1729745300 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3