目次
Kubernetes の偽クライアントを使用した単体テスト
問題
解決策
クラスター内構成スタブによるテストの完了
ホームページ バックエンド開発 Golang Kubernetes 統合コードの単体テストに偽のクライアントを使用する方法

Kubernetes 統合コードの単体テストに偽のクライアントを使用する方法

Oct 27, 2024 am 03:14 AM

How to Use Fake Clients for Unit Testing Kubernetes-Integrated Code?

Kubernetes の偽クライアントを使用した単体テスト

Kubernetes と対話するコードのテストを作成する場合、テスト環境を実際のクラスターから分離すると有益です。これは、ライブ クラスターを必要とせずに Kubernetes API の動作をシミュレートする偽のクライアントを利用することで実現できます。

問題

次の方法を検討してください。

<code class="go">import (
  "fmt"
  "k8s.io/api/core/v1"
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  fake "k8s.io/client-go/kubernetes/fake"
  "time"
)

func GetNamespaceCreationTime(namespace string) int64 {
  clientset, err := kubernetes.NewForConfig(rest.InClusterConfig())
  if err != nil {
    panic(err.Error())
  }
  
  ns, err := clientset.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
  if err != nil {
    panic(err.Error())
  }
  
  fmt.Printf("%v \n", ns.CreationTimestamp)
  return (ns.GetCreationTimestamp().Unix())
}</code>
ログイン後にコピー

目標は、偽のクライアントを使用してこのメ​​ソッドの単体テストを作成することです。

解決策

偽のクライアントを使用するには、パラメーターとして kubernetes.Interface を受け入れるように GetNamespaceCreationTime 関数を変更する必要があります。 :

<code class="go">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>
ログイン後にコピー

テスト関数では、次のように偽のクライアントセットを作成し、それを GetNamespaceCreationTime メソッドに渡すことができます:

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

  nsMock :=kubeClient.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>
ログイン後にコピー

クラスター内構成スタブによるテストの完了

クラスター内構成のスタブを使用した完全なテストは次のようになります:

<code class="go">import (
  "fmt"
  "k8s.io/api/core/v1"
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  fake "k8s.io/client-go/kubernetes/fake"
  "k8s.io/client-go/kubernetes"
  "k8s.io/client-go/rest"
  "time"
)

var getInclusterConfigFunc = rest.InClusterConfig
var getNewKubeClientFunc = dynamic.NewForConfig

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())
}

func GetClientSet() kubernetes.Interface {

  config, err := getInclusterConfigFunc()
  if err != nil {
    log.Warnf("Could not get in-cluster config: %s", err)
    return nil, err
  }

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

  return client, err
}

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

  nsMock :=kubeClient.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)
  }
}

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

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

func TestGetInclusterKubeClient(t *testing.T) {
  origGetInclusterConfig := getInclusterConfigFunc
  getInclusterConfigFunc = fakeGetInclusterConfig
  origGetNewKubeClient := getNewKubeClientFunc
  getNewKubeClientFunc = fakeGetNewKubeClient

  defer func() {
    getInclusterConfigFunc = origGetInclusterConfig
    getNewKubeClientFunc = origGetNewKubeClient
  }()

  client, err := GetClientSet()
  assert.Nil(t, client, "Client is not nil")
  assert.Nil(t, err, "error is not nil")
}

func TestGetInclusterKubeClient_ConfigError(t *testing.T) {
  origGetInclusterConfig := getInclusterConfigFunc
  getInclusterConfigFunc = fakeGetInclusterConfigWithError

  defer func() {
    getInclusterConfigFunc = origGetInclusterConfig
  }()

  client, err := GetClientSet()
  assert.Nil(t, client, "Client is not nil")
  assert.NotNil(t, err, "error is nil")
}</code>
ログイン後にコピー

以上がKubernetes 統合コードの単体テストに偽のクライアントを使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Golang vs. Python:パフォーマンスとスケーラビリティ Golang vs. Python:パフォーマンスとスケーラビリティ Apr 19, 2025 am 12:18 AM

Golangは、パフォーマンスとスケーラビリティの点でPythonよりも優れています。 1)Golangのコンピレーションタイプの特性と効率的な並行性モデルにより、高い並行性シナリオでうまく機能します。 2)Pythonは解釈された言語として、ゆっくりと実行されますが、Cythonなどのツールを介してパフォーマンスを最適化できます。

Golang and C:Concurrency vs. Raw Speed Golang and C:Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golangは並行性がCよりも優れていますが、Cは生の速度ではGolangよりも優れています。 1)Golangは、GoroutineとChannelを通じて効率的な並行性を達成します。これは、多数の同時タスクの処理に適しています。 2)Cコンパイラの最適化と標準ライブラリを介して、極端な最適化を必要とするアプリケーションに適したハードウェアに近い高性能を提供します。

ゴーを始めましょう:初心者のガイド ゴーを始めましょう:初心者のガイド Apr 26, 2025 am 12:21 AM

goisidealforforbeginnersandsutable forcloudnetworkservicesduetoitssimplicity、andconcurrencyfeatures.1)installgofromtheofficialwebsiteandverify with'goversion'.2)

Golang vs. C:パフォーマンスと速度の比較 Golang vs. C:パフォーマンスと速度の比較 Apr 21, 2025 am 12:13 AM

Golangは迅速な発展と同時シナリオに適しており、Cは極端なパフォーマンスと低レベルの制御が必要なシナリオに適しています。 1)Golangは、ごみ収集と並行機関のメカニズムを通じてパフォーマンスを向上させ、高配列Webサービス開発に適しています。 2)Cは、手動のメモリ管理とコンパイラの最適化を通じて究極のパフォーマンスを実現し、埋め込みシステム開発に適しています。

Golang vs. Python:重要な違​​いと類似点 Golang vs. Python:重要な違​​いと類似点 Apr 17, 2025 am 12:15 AM

GolangとPythonにはそれぞれ独自の利点があります。Golangは高性能と同時プログラミングに適していますが、PythonはデータサイエンスとWeb開発に適しています。 Golangは同時性モデルと効率的なパフォーマンスで知られていますが、Pythonは簡潔な構文とリッチライブラリエコシステムで知られています。

GolangとC:パフォーマンスのトレードオフ GolangとC:パフォーマンスのトレードオフ Apr 17, 2025 am 12:18 AM

GolangとCのパフォーマンスの違いは、主にメモリ管理、コンピレーションの最適化、ランタイム効率に反映されています。 1)Golangのゴミ収集メカニズムは便利ですが、パフォーマンスに影響を与える可能性があります。

パフォーマンスレース:ゴラン対c パフォーマンスレース:ゴラン対c Apr 16, 2025 am 12:07 AM

GolangとCにはそれぞれパフォーマンス競争において独自の利点があります。1)Golangは、高い並行性と迅速な発展に適しており、2)Cはより高いパフォーマンスと微細な制御を提供します。選択は、プロジェクトの要件とチームテクノロジースタックに基づいている必要があります。

Golang vs. Python:長所と短所 Golang vs. Python:長所と短所 Apr 21, 2025 am 12:17 AM

GolangisidealforBuildingsCalables Systemsduetoitsefficiency andConcurrency、Whilepythonexcelsinquickscriptinganddataanalysisduetoitssimplicityand vastecosystem.golang'ssignencouragesclean、readisinediteNeditinesinedinediseNabletinedinedinedisedisedioncourase

See all articles