如何使用假客戶端為Client-Go 編寫簡單測試
問題概述
在本例中,我們的目標是編寫一個測試函數GetNamespaceCreationTime 函數,用於檢索特定Kubernetes 命名空間的建立時間戳記。但是,您很難找到合適的方法來合併初始化邏輯並與假客戶端互動。
測試實作
為了有效測試 GetNamespaceCreationTime 函數,初始化過程不應駐留在函數本身。相反,Kubernetes 用戶端介面應作為參數傳遞給該函數。
將GetNamespaceCreationTime 函數中的現有程式碼替換為以下內容:
<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>
接下來,定義一個函數來取得客戶端設定:
<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>
測試函數
在TestGetNamespaceCreationTime 函數中,實例化假客戶端並呼叫GetNamespaceCreationTIme 方法:
<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>
此測試確保使用假客戶端準確檢索「預設」命名空間的預期建立時間戳空間的預期建立時間戳空間。
其他可測試性增強
考慮引入模擬函數來增強程式碼的可測試性和靈活性,例如:
<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>
這些方法允許更強大的測試場景,您可以在其中斷言成功和失敗的叢集內配置檢索的行為。
以上是如何使用假客戶端為 Client-Go 建立簡單的測試?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。