validator_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. Copyright 2014 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 apiserver
  14. import (
  15. "errors"
  16. "fmt"
  17. "testing"
  18. "net/http"
  19. "net/url"
  20. "time"
  21. "k8s.io/kubernetes/pkg/probe"
  22. )
  23. type fakeHttpProber struct {
  24. result probe.Result
  25. body string
  26. err error
  27. }
  28. func (f *fakeHttpProber) Probe(*url.URL, http.Header, time.Duration) (probe.Result, string, error) {
  29. return f.result, f.body, f.err
  30. }
  31. func alwaysError([]byte) error { return errors.New("test error") }
  32. func matchError(data []byte) error {
  33. if string(data) != "bar" {
  34. return errors.New("match error")
  35. }
  36. return nil
  37. }
  38. func TestValidate(t *testing.T) {
  39. tests := []struct {
  40. probeResult probe.Result
  41. probeData string
  42. probeErr error
  43. expectResult probe.Result
  44. expectData string
  45. expectErr bool
  46. validator ValidatorFn
  47. }{
  48. {probe.Unknown, "", fmt.Errorf("probe error"), probe.Unknown, "", true, nil},
  49. {probe.Failure, "", nil, probe.Failure, "", false, nil},
  50. {probe.Success, "foo", nil, probe.Failure, "foo", true, matchError},
  51. {probe.Success, "foo", nil, probe.Success, "foo", false, nil},
  52. }
  53. s := Server{Addr: "foo.com", Port: 8080, Path: "/healthz"}
  54. for _, test := range tests {
  55. fakeProber := &fakeHttpProber{
  56. result: test.probeResult,
  57. body: test.probeData,
  58. err: test.probeErr,
  59. }
  60. s.Validate = test.validator
  61. result, data, err := s.DoServerCheck(fakeProber)
  62. if test.expectErr && err == nil {
  63. t.Error("unexpected non-error")
  64. }
  65. if !test.expectErr && err != nil {
  66. t.Errorf("unexpected error: %v", err)
  67. }
  68. if data != test.expectData {
  69. t.Errorf("expected %s, got %s", test.expectData, data)
  70. }
  71. if result != test.expectResult {
  72. t.Errorf("expected %s, got %s", test.expectResult, result)
  73. }
  74. }
  75. }