Home  >  Article  >  Backend Development  >  How to Create Simple Tests for Client-Go Using a Fake Client?

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

DDD
DDDOriginal
2024-10-24 14:20:02839browse

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:

<code class="go">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()
}</code>

Next, define a function to obtain the client set:

<code class="go">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
}</code>

Test Function

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

<code class="go">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)
  }
}</code>

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:

<code class="go">func fakeGetInclusterConfig() (*rest.Config, error) {
  return nil, nil
}

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

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

The above is the detailed content of How to Create Simple Tests for Client-Go Using a Fake Client?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn