tcp_test.go 1.8 KB

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