tcp_test.go 2.3 KB

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