فهرست منبع

Add tests for GetAPIPort() and make it an int

Signed-off-by: Matt Ray <github@mattray.dev>
Matt Ray 2 سال پیش
والد
کامیت
20dd1cbdf1
3فایلهای تغییر یافته به همراه41 افزوده شده و 3 حذف شده
  1. 1 1
      pkg/cmd/costmodel/costmodel.go
  2. 2 2
      pkg/env/costmodelenv.go
  3. 38 0
      pkg/env/costmodelenv_test.go

+ 1 - 1
pkg/cmd/costmodel/costmodel.go

@@ -78,7 +78,7 @@ func Execute(opts *CostModelOpts) error {
 	telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
 	handler := cors.AllowAll().Handler(telemetryHandler)
 
-	return http.ListenAndServe(":"+env.GetAPIPort(), errors.PanicHandlerMiddleware(handler))
+	return http.ListenAndServe(fmt.Sprint(":", env.GetAPIPort()), errors.PanicHandlerMiddleware(handler))
 }
 
 func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) error {

+ 2 - 2
pkg/env/costmodelenv.go

@@ -151,8 +151,8 @@ func GetExportCSVMaxDays() int {
 
 // GetAPIPort returns the environment variable value for APIPortEnvVar which
 // is the port number the API is available on.
-func GetAPIPort() string {
-	return Get(APIPortEnvVar, "9003")
+func GetAPIPort() int {
+	return GetInt(APIPortEnvVar, 9003)
 }
 
 // GetKubecostConfigBucket returns a file location for a mounted bucket configuration which is used to store

+ 38 - 0
pkg/env/costmodelenv_test.go

@@ -5,6 +5,44 @@ import (
 	"testing"
 )
 
+func TestGetAPIPort(t *testing.T) {
+	tests := []struct {
+		name string
+		want int
+		pre  func()
+	}{
+		{
+			name: "Ensure the default API port '9003'",
+			want: 9003,
+		},
+		{
+			name: "Ensure the default API port '9003' when API_PORT is set to ''",
+			want: 9003,
+			pre: func() {
+				os.Setenv("API_PORT", "")
+			},
+		},
+		{
+			name: "Ensure the API port '9004' when API_PORT is set to '9004'",
+			want: 9004,
+			pre: func() {
+				os.Setenv("API_PORT", "9004")
+			},
+		},
+	}
+	for _, tt := range tests {
+		if tt.pre != nil {
+			tt.pre()
+		}
+		t.Run(tt.name, func(t *testing.T) {
+			if got := GetAPIPort(); got != tt.want {
+				t.Errorf("GetAPIPort() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+
+}
+
 func TestIsCacheDisabled(t *testing.T) {
 	tests := []struct {
 		name string