internal_vm_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // +build !appengine
  5. package internal
  6. import (
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/http/httptest"
  11. "testing"
  12. )
  13. func TestInstallingHealthChecker(t *testing.T) {
  14. try := func(desc string, mux *http.ServeMux, wantCode int, wantBody string) {
  15. installHealthChecker(mux)
  16. srv := httptest.NewServer(mux)
  17. defer srv.Close()
  18. resp, err := http.Get(srv.URL + "/_ah/health")
  19. if err != nil {
  20. t.Errorf("%s: http.Get: %v", desc, err)
  21. return
  22. }
  23. defer resp.Body.Close()
  24. body, err := ioutil.ReadAll(resp.Body)
  25. if err != nil {
  26. t.Errorf("%s: reading body: %v", desc, err)
  27. return
  28. }
  29. if resp.StatusCode != wantCode {
  30. t.Errorf("%s: got HTTP %d, want %d", desc, resp.StatusCode, wantCode)
  31. return
  32. }
  33. if wantBody != "" && string(body) != wantBody {
  34. t.Errorf("%s: got HTTP body %q, want %q", desc, body, wantBody)
  35. return
  36. }
  37. }
  38. // If there's no handlers, or only a root handler, a health checker should be installed.
  39. try("empty mux", http.NewServeMux(), 200, "ok")
  40. mux := http.NewServeMux()
  41. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  42. io.WriteString(w, "root handler")
  43. })
  44. try("mux with root handler", mux, 200, "ok")
  45. // If there's a custom health check handler, one should not be installed.
  46. mux = http.NewServeMux()
  47. mux.HandleFunc("/_ah/health", func(w http.ResponseWriter, r *http.Request) {
  48. w.WriteHeader(418)
  49. io.WriteString(w, "I'm short and stout!")
  50. })
  51. try("mux with custom health checker", mux, 418, "I'm short and stout!")
  52. }