k8s.io/kubernetes@v1.29.3/pkg/probe/tcp/tcp_test.go (about) 1 /* 2 Copyright 2015 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tcp 18 19 import ( 20 "net" 21 "net/http" 22 "net/http/httptest" 23 "strconv" 24 "testing" 25 "time" 26 27 "k8s.io/kubernetes/pkg/probe" 28 ) 29 30 func TestTcpHealthChecker(t *testing.T) { 31 // Setup a test server that responds to probing correctly 32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 33 w.WriteHeader(http.StatusOK) 34 })) 35 defer server.Close() 36 tHost, tPortStr, err := net.SplitHostPort(server.Listener.Addr().String()) 37 if err != nil { 38 t.Errorf("unexpected error: %v", err) 39 } 40 tPort, err := strconv.Atoi(tPortStr) 41 if err != nil { 42 t.Errorf("unexpected error: %v", err) 43 } 44 45 tests := []struct { 46 host string 47 port int 48 49 expectedStatus probe.Result 50 expectedError error 51 }{ 52 // A connection is made and probing would succeed 53 {tHost, tPort, probe.Success, nil}, 54 // No connection can be made and probing would fail 55 {tHost, -1, probe.Failure, nil}, 56 } 57 58 prober := New() 59 for i, tt := range tests { 60 status, _, err := prober.Probe(tt.host, tt.port, 1*time.Second) 61 if status != tt.expectedStatus { 62 t.Errorf("#%d: expected status=%v, get=%v", i, tt.expectedStatus, status) 63 } 64 if err != tt.expectedError { 65 t.Errorf("#%d: expected error=%v, get=%v", i, tt.expectedError, err) 66 } 67 } 68 }