tcp_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. "strings"
  20. "testing"
  21. "time"
  22. "k8s.io/kubernetes/pkg/probe"
  23. )
  24. func containsAny(s string, substrs []string) bool {
  25. for _, substr := range substrs {
  26. if strings.Contains(s, substr) {
  27. return true
  28. }
  29. }
  30. return false
  31. }
  32. func TestTcpHealthChecker(t *testing.T) {
  33. // Setup a test server that responds to probing correctly
  34. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  35. w.WriteHeader(http.StatusOK)
  36. }))
  37. defer server.Close()
  38. tHost, tPortStr, err := net.SplitHostPort(server.Listener.Addr().String())
  39. if err != nil {
  40. t.Errorf("unexpected error: %v", err)
  41. }
  42. tPort, err := strconv.Atoi(tPortStr)
  43. if err != nil {
  44. t.Errorf("unexpected error: %v", err)
  45. }
  46. tests := []struct {
  47. host string
  48. port int
  49. expectedStatus probe.Result
  50. expectedError error
  51. // Some errors are different depending on your system.
  52. // The test passes as long as the output matches one of them.
  53. expectedOutputs []string
  54. }{
  55. // A connection is made and probing would succeed
  56. {tHost, tPort, probe.Success, nil, []string{""}},
  57. // No connection can be made and probing would fail
  58. {tHost, -1, probe.Failure, nil, []string{
  59. "unknown port",
  60. "Servname not supported for ai_socktype",
  61. "nodename nor servname provided, or not known",
  62. "dial tcp: invalid port",
  63. }},
  64. }
  65. prober := New()
  66. for i, tt := range tests {
  67. status, output, err := prober.Probe(tt.host, tt.port, 1*time.Second)
  68. if status != tt.expectedStatus {
  69. t.Errorf("#%d: expected status=%v, get=%v", i, tt.expectedStatus, status)
  70. }
  71. if err != tt.expectedError {
  72. t.Errorf("#%d: expected error=%v, get=%v", i, tt.expectedError, err)
  73. }
  74. if !containsAny(output, tt.expectedOutputs) {
  75. t.Errorf("#%d: expected output=one of %#v, get=%s", i, tt.expectedOutputs, output)
  76. }
  77. }
  78. }