internal_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2014 Google Inc. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package internal
  5. import (
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "net/http/httptest"
  10. "testing"
  11. )
  12. func TestInstallingHealthChecker(t *testing.T) {
  13. try := func(desc string, mux *http.ServeMux, wantCode int, wantBody string) {
  14. installHealthChecker(mux)
  15. srv := httptest.NewServer(mux)
  16. defer srv.Close()
  17. resp, err := http.Get(srv.URL + "/_ah/health")
  18. if err != nil {
  19. t.Errorf("%s: http.Get: %v", desc, err)
  20. return
  21. }
  22. defer resp.Body.Close()
  23. body, err := ioutil.ReadAll(resp.Body)
  24. if err != nil {
  25. t.Errorf("%s: reading body: %v", desc, err)
  26. return
  27. }
  28. if resp.StatusCode != wantCode {
  29. t.Errorf("%s: got HTTP %d, want %d", desc, resp.StatusCode, wantCode)
  30. return
  31. }
  32. if wantBody != "" && string(body) != wantBody {
  33. t.Errorf("%s: got HTTP body %q, want %q", desc, body, wantBody)
  34. return
  35. }
  36. }
  37. // If there's no handlers, or only a root handler, a health checker should be installed.
  38. try("empty mux", http.NewServeMux(), 200, "ok")
  39. mux := http.NewServeMux()
  40. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  41. io.WriteString(w, "root handler")
  42. })
  43. try("mux with root handler", mux, 200, "ok")
  44. // If there's a custom health check handler, one should not be installed.
  45. mux = http.NewServeMux()
  46. mux.HandleFunc("/_ah/health", func(w http.ResponseWriter, r *http.Request) {
  47. w.WriteHeader(418)
  48. io.WriteString(w, "I'm short and stout!")
  49. })
  50. try("mux with custom health checker", mux, 418, "I'm short and stout!")
  51. }