blob: 0abcf10022a5cb107a62722a1f388586d03391f6 [file] [log] [blame]
Benjamin Prosnitz4d71d342014-10-15 13:35:06 -07001// +build linux,!android
Cosmos Nicolaou6c6fa112014-08-19 13:22:33 -07002
Robin Thellendc06b64c2014-07-25 16:50:27 -07003package gce
4
5import (
6 "fmt"
7 "net"
8 "net/http"
9 "testing"
10)
11
12func startServer(t *testing.T) (net.Addr, func()) {
13 l, err := net.Listen("tcp", "127.0.0.1:0")
14 if err != nil {
15 t.Fatal(err)
16 }
17 http.HandleFunc("/404", func(w http.ResponseWriter, r *http.Request) {
18 w.WriteHeader(http.StatusNotFound)
19 })
20 http.HandleFunc("/200_not_gce", func(w http.ResponseWriter, r *http.Request) {
21 fmt.Fprintf(w, "Hello")
22 })
23 http.HandleFunc("/gce_no_ip", func(w http.ResponseWriter, r *http.Request) {
24 // When a GCE instance doesn't have an external IP address, the
25 // request returns a 200 with an empty body.
26 w.Header().Add("Metadata-Flavor", "Google")
27 if m := r.Header["Metadata-Flavor"]; len(m) != 1 || m[0] != "Google" {
28 w.WriteHeader(http.StatusForbidden)
29 return
30 }
31 })
32 http.HandleFunc("/gce_with_ip", func(w http.ResponseWriter, r *http.Request) {
33 // When a GCE instance has an external IP address, the request
34 // returns the IP address as body.
35 w.Header().Add("Metadata-Flavor", "Google")
36 if m := r.Header["Metadata-Flavor"]; len(m) != 1 || m[0] != "Google" {
37 w.WriteHeader(http.StatusForbidden)
38 return
39 }
40 fmt.Fprintf(w, "1.2.3.4")
41 })
42
43 go http.Serve(l, nil)
44 return l.Addr(), func() { l.Close() }
45}
46
47func TestGCE(t *testing.T) {
48 addr, stop := startServer(t)
49 defer stop()
50 baseURL := "http://" + addr.String()
51
Cosmos Nicolaou6c6fa112014-08-19 13:22:33 -070052 if ip, err := gceTest(baseURL + "/404"); err == nil || ip != nil {
53 t.Errorf("expected error, but not got nil")
Robin Thellendc06b64c2014-07-25 16:50:27 -070054 }
Cosmos Nicolaou6c6fa112014-08-19 13:22:33 -070055 if ip, err := gceTest(baseURL + "/200_not_gce"); err == nil || ip != nil {
56 t.Errorf("expected error, but not got nil")
Robin Thellendc06b64c2014-07-25 16:50:27 -070057 }
Cosmos Nicolaou6c6fa112014-08-19 13:22:33 -070058 if ip, err := gceTest(baseURL + "/gce_no_ip"); err != nil || ip != nil {
59 t.Errorf("Unexpected result. Got (%v, %v), want nil:nil", ip, err)
Robin Thellendc06b64c2014-07-25 16:50:27 -070060 }
Cosmos Nicolaou6c6fa112014-08-19 13:22:33 -070061 if ip, err := gceTest(baseURL + "/gce_with_ip"); err != nil || ip.String() != "1.2.3.4" {
62 t.Errorf("Unexpected result. Got (%v, %v), want nil:1.2.3.4", ip, err)
Robin Thellendc06b64c2014-07-25 16:50:27 -070063 }
64}