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