From bdd1e598baf9d4a90371dccc39a2ac3b3a485cb7 Mon Sep 17 00:00:00 2001 From: mengze zhu Date: Thu, 2 Jan 2025 02:41:43 +0000 Subject: [PATCH] test: add UT for gen-disk-skus-map_tes --- pkg/tool/gen-disk-skus-map.go | 9 ++++-- pkg/tool/gen-disk-skus-map_test.go | 49 ++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 pkg/tool/gen-disk-skus-map_test.go diff --git a/pkg/tool/gen-disk-skus-map.go b/pkg/tool/gen-disk-skus-map.go index 4bd6eb7d03..460f80aeaf 100644 --- a/pkg/tool/gen-disk-skus-map.go +++ b/pkg/tool/gen-disk-skus-map.go @@ -49,6 +49,11 @@ func init() { klog.InitFlags(nil) } +// exit is a separate function to handle program termination +var exit = func(code int) { + os.Exit(code) +} + func main() { boilerPlate := `/* @@ -137,7 +142,7 @@ import ( diskSkuInfoMap[account][diskSize], err = getDiskCapabilities(sku) if err != nil { klog.Errorf("populateSkuMap: Failed to get disk capabilities for disk %s %s %s. Error: %v", *sku.Name, *sku.Size, *sku.Tier, err) - os.Exit(1) + exit(1) } } else if resType == "virtualmachines" { @@ -146,7 +151,7 @@ import ( err = populateNodeCapabilities(sku, &nodeInfo) if err != nil { klog.Errorf("populateSkuMap: Failed to populate node capabilities. Error: %v", err) - os.Exit(1) + exit(1) } vmSkuInfoMap[strings.ToLower(*sku.Name)] = nodeInfo } diff --git a/pkg/tool/gen-disk-skus-map_test.go b/pkg/tool/gen-disk-skus-map_test.go new file mode 100644 index 0000000000..96030558dd --- /dev/null +++ b/pkg/tool/gen-disk-skus-map_test.go @@ -0,0 +1,49 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package main + +import ( + "os" + "testing" +) + +func TestMain(t *testing.T) { + // Capture stdout + old := os.Stdout + _, w, _ := os.Pipe() + os.Stdout = w + + // Replace exit function with mock function + var exitCode int + exit = func(code int) { + exitCode = code + } + + // Call main function + main() + + // Restore stdout + w.Close() + os.Stdout = old + exit = func(code int) { + os.Exit(code) + } + + if exitCode != 0 { + t.Errorf("Expected exit code 0, but got %d", exitCode) + } +}