Robin Thellend | c06b64c | 2014-07-25 16:50:27 -0700 | [diff] [blame] | 1 | package gce |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net" |
| 6 | "net/http" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | func startServer(t *testing.T) (net.Addr, func()) { |
| 11 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 12 | if err != nil { |
| 13 | t.Fatal(err) |
| 14 | } |
| 15 | http.HandleFunc("/404", func(w http.ResponseWriter, r *http.Request) { |
| 16 | w.WriteHeader(http.StatusNotFound) |
| 17 | }) |
| 18 | http.HandleFunc("/200_not_gce", func(w http.ResponseWriter, r *http.Request) { |
| 19 | fmt.Fprintf(w, "Hello") |
| 20 | }) |
| 21 | http.HandleFunc("/gce_no_ip", func(w http.ResponseWriter, r *http.Request) { |
| 22 | // When a GCE instance doesn't have an external IP address, the |
| 23 | // request returns a 200 with an empty body. |
| 24 | w.Header().Add("Metadata-Flavor", "Google") |
| 25 | if m := r.Header["Metadata-Flavor"]; len(m) != 1 || m[0] != "Google" { |
| 26 | w.WriteHeader(http.StatusForbidden) |
| 27 | return |
| 28 | } |
| 29 | }) |
| 30 | http.HandleFunc("/gce_with_ip", func(w http.ResponseWriter, r *http.Request) { |
| 31 | // When a GCE instance has an external IP address, the request |
| 32 | // returns the IP address as body. |
| 33 | w.Header().Add("Metadata-Flavor", "Google") |
| 34 | if m := r.Header["Metadata-Flavor"]; len(m) != 1 || m[0] != "Google" { |
| 35 | w.WriteHeader(http.StatusForbidden) |
| 36 | return |
| 37 | } |
| 38 | fmt.Fprintf(w, "1.2.3.4") |
| 39 | }) |
| 40 | |
| 41 | go http.Serve(l, nil) |
| 42 | return l.Addr(), func() { l.Close() } |
| 43 | } |
| 44 | |
| 45 | func TestGCE(t *testing.T) { |
| 46 | addr, stop := startServer(t) |
| 47 | defer stop() |
| 48 | baseURL := "http://" + addr.String() |
| 49 | |
| 50 | if isGCE, ip := googleComputeEngineTest(baseURL + "/404"); isGCE != false || ip != nil { |
| 51 | t.Errorf("Unexpected result. Got %v:%v, want false:nil", isGCE, ip) |
| 52 | } |
| 53 | if isGCE, ip := googleComputeEngineTest(baseURL + "/200_not_gce"); isGCE != false || ip != nil { |
| 54 | t.Errorf("Unexpected result. Got %v:%v, want false:nil", isGCE, ip) |
| 55 | } |
| 56 | if isGCE, ip := googleComputeEngineTest(baseURL + "/gce_no_ip"); isGCE != true || ip != nil { |
| 57 | t.Errorf("Unexpected result. Got %v:%v, want true:nil", isGCE, ip) |
| 58 | } |
| 59 | if isGCE, ip := googleComputeEngineTest(baseURL + "/gce_with_ip"); isGCE != true || ip.String() != "1.2.3.4" { |
| 60 | t.Errorf("Unexpected result. Got %v:%v, want true:1.2.3.4", isGCE, ip) |
| 61 | } |
| 62 | } |