github.com/google/cloudprober@v0.11.3/cloudprober_test.go (about) 1 // Copyright 2019-2020 The Cloudprober Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cloudprober 16 17 import ( 18 "os" 19 "testing" 20 21 configpb "github.com/google/cloudprober/config/proto" 22 "google.golang.org/protobuf/proto" 23 ) 24 25 func TestGetDefaultServerPort(t *testing.T) { 26 tests := []struct { 27 desc string 28 configPort int32 29 envVar string 30 wantPort int 31 wantErr bool 32 }{ 33 { 34 desc: "use port from config", 35 configPort: 9316, 36 envVar: "3141", 37 wantPort: 9316, 38 }, 39 { 40 desc: "use default port", 41 configPort: 0, 42 envVar: "", 43 wantPort: DefaultServerPort, 44 }, 45 { 46 desc: "use port from env", 47 configPort: 0, 48 envVar: "3141", 49 wantPort: 3141, 50 }, 51 { 52 desc: "ignore kubernetes port", 53 configPort: 0, 54 envVar: "tcp://100.101.102.103:3141", 55 wantPort: 9313, 56 }, 57 { 58 desc: "error due to bad env var", 59 configPort: 0, 60 envVar: "a3141", 61 wantErr: true, 62 }, 63 } 64 65 for _, test := range tests { 66 t.Run(test.desc, func(t *testing.T) { 67 os.Setenv(ServerPortEnvVar, test.envVar) 68 port, err := getDefaultServerPort(&configpb.ProberConfig{ 69 Port: proto.Int32(test.configPort), 70 }, nil) 71 72 if err != nil { 73 if !test.wantErr { 74 t.Errorf("Got unexpected error: %v", err) 75 } else { 76 return 77 } 78 } 79 80 if port != test.wantPort { 81 t.Errorf("got port: %d, want port: %d", port, test.wantPort) 82 } 83 }) 84 } 85 86 }