func TestProxyUpgrade(t *testing.T) { backendServer := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) { defer ws.Close() body := make([]byte, 5) ws.Read(body) ws.Write([]byte("hello " + string(body))) })) defer backendServer.Close() serverURL, _ := url.Parse(backendServer.URL) proxyHandler := &UpgradeAwareProxyHandler{ Location: serverURL, } proxy := httptest.NewServer(proxyHandler) defer proxy.Close() ws, err := websocket.Dial("ws://"+proxy.Listener.Addr().String()+"/some/path", "", "http://127.0.0.1/") if err != nil { t.Fatalf("websocket dial err: %s", err) } defer ws.Close() if _, err := ws.Write([]byte("world")); err != nil { t.Fatalf("write err: %s", err) } response := make([]byte, 20) n, err := ws.Read(response) if err != nil { t.Fatalf("read err: %s", err) } if e, a := "hello world", string(response[0:n]); e != a { t.Fatalf("expected '%#v', got '%#v'", e, a) } }
func TestServerHappyPathSingleServer(t *testing.T) { originServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("hey")) })) defer originServer.Close() originURL, _ := url.Parse(originServer.URL) handler := httptransport.NewServer( context.Background(), originURL, ) proxyServer := httptest.NewServer(handler) defer proxyServer.Close() resp, _ := http.Get(proxyServer.URL) if want, have := http.StatusOK, resp.StatusCode; want != have { t.Errorf("want %d, have %d", want, have) } responseBody, _ := ioutil.ReadAll(resp.Body) if want, have := "hey", string(responseBody); want != have { t.Errorf("want %q, have %q", want, have) } }
func TestCotacao(t *testing.T) { Convey("Ao executar o comando cotação", t, func() { cmd := &bot.Cmd{} Convey("Deve responder com a cotação do dólar e euro", func() { ts := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, expectedJSON) })) defer ts.Close() url = ts.URL c, err := cotacao(cmd) So(err, ShouldBeNil) So(c, ShouldEqual, "Dólar: 2.2430 (+0.36), Euro: 2.9018 (-1.21)") }) Convey("Quando o webservice retornar algo inválido deve retornar erro", func() { ts := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "invalid") })) defer ts.Close() url = ts.URL _, err := cotacao(cmd) So(err, ShouldNotBeNil) }) }) }
func NewSignatureTest() *SignatureTest { opts := NewOptions() opts.CookieSecret = "cookie secret" opts.ClientID = "client ID" opts.ClientSecret = "client secret" opts.EmailDomains = []string{"acm.org"} authenticator := &SignatureAuthenticator{} upstream := httptest.NewServer( http.HandlerFunc(authenticator.Authenticate)) upstream_url, _ := url.Parse(upstream.URL) opts.Upstreams = append(opts.Upstreams, upstream.URL) providerHandler := func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"access_token": "my_auth_token"}`)) } provider := httptest.NewServer(http.HandlerFunc(providerHandler)) provider_url, _ := url.Parse(provider.URL) opts.provider = NewTestProvider(provider_url, "*****@*****.**") return &SignatureTest{ opts, upstream, upstream_url.Host, provider, make(http.Header), httptest.NewRecorder(), authenticator, } }
func TestTransportCircuitOpenWith5PercentError(t *testing.T) { pass := httptest.NewServer(code(200)) defer pass.Close() fail := httptest.NewServer(code(500)) defer fail.Close() c := http.Client{ Transport: Transport(NewBreaker(0.05), DefaultResponseValidator, http.DefaultTransport), } var lastError error for i := 1; i <= 100; i++ { url := pass.URL if i >= 95 { url = fail.URL } _, lastError = c.Get(url) } if lastError == nil { t.Fatalf("expected %q after 5%% error rate, got no error", ErrCircuitOpen) } urlError, ok := lastError.(*url.Error) if !ok { t.Fatalf("expected url.Error after 5%% error rate, got %s", reflect.TypeOf(lastError)) } if err := urlError.Err; err != ErrCircuitOpen { t.Fatalf("expected %q after 5%% error rate, got %q", ErrCircuitOpen, err) } }
func TestCustomPrefix(t *testing.T) { Convey("Given the App running with PREFIX", t, func() { uc := make(chan string, 0) bc := make(chan string, 0) f := Flag f.Prefix = "BETA" ctx, _ := context.WithCancel(context.Background()) ctx = context.WithValue(ctx, "Flag", f) app := NewApp(ctx, GetMockPerformJsonPost(uc, bc)) v1httpapi := V1HttpApi{ App: app, } v1httpapi.registerRoutes(app.Router) Convey("When posting a message", func() { ts := httptest.NewServer(app.Router) defer ts.Close() post_body := bytes.NewReader([]byte("")) http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body) So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/") body := <-bc So(body, ShouldContainSubstring, "\"__prefix\":\"BETA\"") So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"") So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"") So(body, ShouldContainSubstring, "\"__namespace\"") So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"") }) }) Convey("Given the App running WITHOUT prefix", t, func() { uc := make(chan string, 0) bc := make(chan string, 0) f := Flag ctx, _ := context.WithCancel(context.Background()) ctx = context.WithValue(ctx, "Flag", f) app := NewApp(ctx, GetMockPerformJsonPost(uc, bc)) v1httpapi := V1HttpApi{ App: app, } v1httpapi.registerRoutes(app.Router) Convey("When posting a message", func() { ts := httptest.NewServer(app.Router) defer ts.Close() post_body := bytes.NewReader([]byte("")) http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body) So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/") body := <-bc So(body, ShouldNotContainSubstring, "\"__prefix\"") So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"") So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"") So(body, ShouldContainSubstring, "\"__namespace\"") So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"") }) }) }
// TODO: more tests on redirect func TestRedirectPolicyFunc(t *testing.T) { redirectSuccess := false redirectFuncGetCalled := false tsRedirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { redirectSuccess = true })) defer tsRedirect.Close() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, tsRedirect.URL, http.StatusMovedPermanently) })) defer ts.Close() New(). Get(ts.URL). RedirectPolicy(func(req Request, via []Request) error { redirectFuncGetCalled = true return nil }).End() if !redirectSuccess { t.Errorf("Expected reaching another redirect url not original one") } if !redirectFuncGetCalled { t.Errorf("Expected redirect policy func to get called") } }
func TestPrintKubernetesVersions(t *testing.T) { // test that no kubernetes version text is printed if there are no versions being served // TODO(aprindle) or should this be an error?!?! handlerNone := &URLHandlerNone{} server := httptest.NewServer(handlerNone) var outputBuffer bytes.Buffer PrintKubernetesVersions(&outputBuffer, server.URL) if len(outputBuffer.String()) != 0 { t.Fatalf("Expected PrintKubernetesVersions to not output text as there are no versioned served at the current URL but output was [%s]", outputBuffer.String()) } // test that update text is printed if the latest version is greater than the current version // k8sVersionsFromURL = "100.0.0-dev" version0 := "0.0.0" version1 := "1.0.0" handlerCorrect := &URLHandlerCorrect{ K8sReleases: []k8sRelease{{Version: version0}, {Version: version1}}, } server = httptest.NewServer(handlerCorrect) PrintKubernetesVersions(&outputBuffer, server.URL) if len(outputBuffer.String()) == 0 { t.Fatalf("Expected PrintKubernetesVersion to output text as %d versions were served from URL but output was [%s]", 2, outputBuffer.String()) //TODO(aprindle) change the 2 } }
func TestUpdateClusterStatusOK(t *testing.T) { clusterName := "foobarCluster" // create dummy httpserver testClusterServer := httptest.NewServer(createHttptestFakeHandlerForCluster(true)) defer testClusterServer.Close() federationCluster := newCluster(clusterName, testClusterServer.URL) federationClusterList := newClusterList(federationCluster) testFederationServer := httptest.NewServer(createHttptestFakeHandlerForFederation(federationClusterList, true)) defer testFederationServer.Close() restClientCfg, err := clientcmd.BuildConfigFromFlags(testFederationServer.URL, "") if err != nil { t.Errorf("Failed to build client config") } federationClientSet := federationclientset.NewForConfigOrDie(restclient.AddUserAgent(restClientCfg, "cluster-controller")) manager := NewclusterController(federationClientSet, 5) err = manager.UpdateClusterStatus() if err != nil { t.Errorf("Failed to Update Cluster Status: %v", err) } clusterStatus, found := manager.clusterClusterStatusMap[clusterName] if !found { t.Errorf("Failed to Update Cluster Status") } else { if (clusterStatus.Conditions[1].Status != v1.ConditionFalse) || (clusterStatus.Conditions[1].Type != federation_v1alpha1.ClusterOffline) { t.Errorf("Failed to Update Cluster Status") } } }
func TestServerOriginServerUnreachable(t *testing.T) { // create a server, then promptly shut it down originServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) originURL, _ := url.Parse(originServer.URL) originServer.Close() handler := httptransport.NewServer( context.Background(), originURL, ) proxyServer := httptest.NewServer(handler) defer proxyServer.Close() resp, _ := http.Get(proxyServer.URL) switch resp.StatusCode { case http.StatusBadGateway: // go1.7 and beyond break case http.StatusInternalServerError: // to go1.7 break default: t.Errorf("want %d or %d, have %d", http.StatusBadGateway, http.StatusInternalServerError, resp.StatusCode) } }
func TestInspectContainerNoSuchContainer(t *testing.T) { server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "No such container", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "No such container", http.StatusNotFound) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } id := "e90302" container, err := cluster.InspectContainer(id) if container != nil { t.Errorf("InspectContainer(%q): Expected <nil> container, got %#v.", id, container) } expected := &dclient.NoSuchContainer{ID: id} if !reflect.DeepEqual(err, expected) { t.Errorf("InspectContainer(%q): Wrong error. Want %#v. Got %#v.", id, expected, err) } }
func TestEncodedSlashes(t *testing.T) { var seen string backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) seen = r.RequestURI })) defer backend.Close() b, _ := url.Parse(backend.URL) proxyHandler := NewReverseProxy(b) setProxyDirector(proxyHandler) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() f, _ := url.Parse(frontend.URL) encodedPath := "/a%2Fb/?c=1" getReq := &http.Request{URL: &url.URL{Scheme: "http", Host: f.Host, Opaque: encodedPath}} _, err := http.DefaultClient.Do(getReq) if err != nil { t.Fatalf("err %s", err) } if seen != encodedPath { t.Errorf("got bad request %q expected %q", seen, encodedPath) } }
func TestRedirectOnMissingTrailingSlash(t *testing.T) { table := []struct { // The requested path path string // The path requested on the proxy server. proxyServerPath string // query string query string }{ {"/trailing/slash/", "/trailing/slash/", ""}, {"/", "/", "test1=value1&test2=value2"}, // "/" should be added at the end. {"", "/", "test1=value1&test2=value2"}, // "/" should not be added at a non-root path. {"/some/path", "/some/path", ""}, } for _, item := range table { proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path != item.proxyServerPath { t.Errorf("Unexpected request on path: %s, expected path: %s, item: %v", req.URL.Path, item.proxyServerPath, item) } if req.URL.RawQuery != item.query { t.Errorf("Unexpected query on url: %s, expected: %s", req.URL.RawQuery, item.query) } })) defer proxyServer.Close() serverURL, _ := url.Parse(proxyServer.URL) simpleStorage := &SimpleRESTStorage{ errors: map[string]error{}, resourceLocation: serverURL, expectedResourceNamespace: "ns", } handler := handleNamespaced(map[string]rest.Storage{"foo": simpleStorage}) server := httptest.NewServer(handler) defer server.Close() proxyTestPattern := "/api/version2/proxy/namespaces/ns/foo/id" + item.path req, err := http.NewRequest( "GET", server.URL+proxyTestPattern+"?"+item.query, strings.NewReader(""), ) if err != nil { t.Errorf("unexpected error %v", err) continue } // Note: We are using a default client here, that follows redirects. resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("unexpected error %v", err) continue } if resp.StatusCode != http.StatusOK { t.Errorf("Unexpected errorCode: %v, expected: 200. Response: %v, item: %v", resp.StatusCode, resp, item) } } }
func TestReverseProxyQuery(t *testing.T) { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Got-Query", r.URL.RawQuery) w.Write([]byte("hi")) })) defer backend.Close() for i, tt := range proxyQueryTests { backendURL, err := url.Parse(backend.URL + tt.baseSuffix) if err != nil { t.Fatal(err) } frontend := httptest.NewServer(NewSingleHostReverseProxy(backendURL)) req, _ := http.NewRequest("GET", frontend.URL+tt.reqSuffix, nil) req.Close = true res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("%d. Get: %v", i, err) } if g, e := res.Header.Get("X-Got-Query"), tt.want; g != e { t.Errorf("%d. got query %q; expected %q", i, g, e) } res.Body.Close() frontend.Close() } }
// Issue 12344 func TestNilBody(t *testing.T) { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hi")) })) defer backend.Close() frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { backURL, _ := url.Parse(backend.URL) rp := NewSingleHostReverseProxy(backURL) r := req(t, "GET / HTTP/1.0\r\n\r\n") r.Body = nil // this accidentally worked in Go 1.4 and below, so keep it working rp.ServeHTTP(w, r) })) defer frontend.Close() res, err := http.Get(frontend.URL) if err != nil { t.Fatal(err) } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if string(slurp) != "hi" { t.Errorf("Got %q; want %q", slurp, "hi") } }
func TestAttachToContainerWithStorage(t *testing.T) { var called bool server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true http.Error(w, "No such container", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } id := "abcdef" storage := mapStorage{cMap: map[string]string{id: "handler1"}} cluster.SetStorage(&storage) opts := dclient.AttachToContainerOptions{ Container: id, OutputStream: &safe.Buffer{}, Logs: true, Stdout: true, } err = cluster.AttachToContainer(opts) if err != nil { t.Fatal(err) } if called { t.Error("AttachToContainer(): should not call the node server") } }
func TestCommitContainer(t *testing.T) { var called bool server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "container not found", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true w.Write([]byte(`{"Id":"596069db4bf5"}`)) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } opts := dclient.CommitContainerOptions{ Container: "abcdef", } image, err := cluster.CommitContainer(opts) if err != nil { t.Fatal(err) } if image.ID != "596069db4bf5" { t.Errorf("CommitContainer: the image container is %s, expected: '596069db4bf5'", image.ID) } if !called { t.Error("CommitContainer: Did not call the remote HTTP API") } }
func Test_HTTPClient_Check(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(http.StatusOK) if req.URL.Path == "/api/functions.json" { res.Write([]byte(functionsListJSON)) } })) defer server.Close() successClient := NewHTTPClient(server.URL) err := successClient.Check() if err != nil { t.Errorf("Check() failed: got %s, expected nil", err.Error()) } failServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(http.StatusNotFound) })) defer failServer.Close() failClient := NewHTTPClient(failServer.URL) err = failClient.Check() if err == nil { t.Errorf("Check() failed: got nil error, expected an error") } }
func TestAttachToContainer(t *testing.T) { var called bool server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "container not found", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true w.Write([]byte("something happened")) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } opts := dclient.AttachToContainerOptions{ Container: "abcdef", OutputStream: &safe.Buffer{}, Logs: true, Stdout: true, } err = cluster.AttachToContainer(opts) if err != nil { t.Errorf("AttachToContainer: unexpected error. Want <nil>. Got %#v.", err) } if !called { t.Error("AttachToContainer: Did not call the remote HTTP API") } }
func TestCreateContainerWithStorage(t *testing.T) { body := `{"Id":"e90302"}` handler := []bool{false, false} server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler[0] = true w.Header().Set("Content-Type", "application/json") w.Write([]byte(body)) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler[1] = true w.Header().Set("Content-Type", "application/json") w.Write([]byte(body)) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } var storage mapStorage cluster.SetStorage(&storage) config := docker.Config{Memory: 67108864} _, _, err = cluster.CreateContainer(&config) if err != nil { t.Fatal(err) } expected := map[string]string{"e90302": "handler0"} if storage.cMap["e90302"] != "handler0" { t.Errorf("Cluster.CreateContainer() with storage: wrong data. Want %#v. Got %#v.", expected, storage.cMap) } }
func TestWaitContainerNotFound(t *testing.T) { server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "No such container", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "No such container", http.StatusNotFound) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } id := "abc123" expected := -1 status, err := cluster.WaitContainer(id) if err == nil { t.Errorf("WaitContainer(%q): unexpected <nil> error", id) } if status != expected { t.Errorf("WaitContainer(%q): Wrong status. Want %d. Got %d.", id, expected, status) } }
func TestRestartContainer(t *testing.T) { var called bool server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "No such container", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true w.Write([]byte("ok")) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } id := "abc123" err = cluster.RestartContainer(id, 10) if err != nil { t.Fatal(err) } if !called { t.Errorf("RestartContainer(%q, 10): Did not call node HTTP server", id) } }
func TestRestartContainerWithStorage(t *testing.T) { var called bool server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true http.Error(w, "No such container", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } id := "abc123" storage := mapStorage{cMap: map[string]string{id: "handler1"}} cluster.SetStorage(&storage) err = cluster.RestartContainer(id, 10) if err != nil { t.Fatal(err) } if called { t.Errorf("RestartContainer(%q): should not call the node server", id) } }
func TestCreateContainer(t *testing.T) { body := `{"Id":"e90302"}` handler := []bool{false, false} server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler[0] = true w.Header().Set("Content-Type", "application/json") w.Write([]byte(body)) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler[1] = true w.Header().Set("Content-Type", "application/json") w.Write([]byte(body)) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } config := docker.Config{Memory: 67108864} nodeID, container, err := cluster.CreateContainer(&config) if err != nil { t.Fatal(err) } if nodeID != "handler0" { t.Errorf("CreateContainer: wrong node ID. Want %q. Got %q.", "handler0", nodeID) } if container.ID != "e90302" { t.Errorf("CreateContainer: wrong container ID. Want %q. Got %q.", "e90302", container.ID) } }
func TestRootHandler(t *testing.T) { // Setup response handler for outbound request proxyServer := httptest.NewServer(http.HandlerFunc(handler)) defer proxyServer.Close() os.Setenv("PROXY_HOST", proxyServer.URL) // Setup route wrapper routeServer := httptest.NewServer(http.HandlerFunc(wrapper)) defer routeServer.Close() // Request uri := routeServer.URL + "/root" client := &http.Client{} req, err := http.NewRequest("GET", uri, nil) if err != nil { t.Error(err) } req.Header.Set("Authorization", "---") resp, err := client.Do(req) if err != nil { t.Error(err) } defer resp.Body.Close() if resp.StatusCode != 200 { t.Errorf("Expected StatusCode=200, recieved %v", resp.StatusCode) } }
func TestInspectContainer(t *testing.T) { body := `{"Id":"e90302","Path":"date","Args":[]}` server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "No such container", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(body)) })) defer server2.Close() server3 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "No such container", http.StatusNotFound) })) defer server3.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, Node{ID: "handler2", Address: server3.URL}, ) if err != nil { t.Fatal(err) } id := "e90302" container, err := cluster.InspectContainer(id) if err != nil { t.Fatal(err) } if container.ID != id { t.Errorf("InspectContainer(%q): Wrong ID. Want %q. Got %q.", id, id, container.ID) } if container.Path != "date" { t.Errorf("InspectContainer(%q): Wrong Path. Want %q. Got %q.", id, "date", container.Path) } }
func TestNewReverseProxy(t *testing.T) { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) hostname, _, _ := net.SplitHostPort(r.Host) w.Write([]byte(hostname)) })) defer backend.Close() backendURL, _ := url.Parse(backend.URL) backendHostname, backendPort, _ := net.SplitHostPort(backendURL.Host) backendHost := net.JoinHostPort(backendHostname, backendPort) proxyURL, _ := url.Parse(backendURL.Scheme + "://" + backendHost + "/") proxyHandler := NewReverseProxy(proxyURL) setProxyUpstreamHostHeader(proxyHandler, proxyURL) frontend := httptest.NewServer(proxyHandler) defer frontend.Close() getReq, _ := http.NewRequest("GET", frontend.URL, nil) res, _ := http.DefaultClient.Do(getReq) bodyBytes, _ := ioutil.ReadAll(res.Body) if g, e := string(bodyBytes), backendHostname; g != e { t.Errorf("got body %q; expected %q", g, e) } }
func TestWaitContainerWithStorage(t *testing.T) { var called bool server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true http.Error(w, "No such container", http.StatusNotFound) })) defer server1.Close() server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body := `{"StatusCode":34}` w.Write([]byte(body)) })) defer server2.Close() cluster, err := New(nil, Node{ID: "handler0", Address: server1.URL}, Node{ID: "handler1", Address: server2.URL}, ) if err != nil { t.Fatal(err) } id := "abc123" storage := mapStorage{cMap: map[string]string{id: "handler1"}} cluster.SetStorage(&storage) expected := 34 status, err := cluster.WaitContainer(id) if err != nil { t.Fatal(err) } if status != expected { t.Errorf("WaitContainer(%q): Wrong status. Want %d. Got %d.", id, expected, status) } if called { t.Errorf("WaitContainer(%q): should not call the all node servers.", id) } }
func (s *S) TestStickyHTTPRoute(c *C) { srv1 := httptest.NewServer(httpTestHandler("1")) srv2 := httptest.NewServer(httpTestHandler("2")) defer srv1.Close() defer srv2.Close() l := s.newHTTPListener(c) defer l.Close() addStickyHTTPRoute(c, l) unregister := discoverdRegisterHTTP(c, l, srv1.Listener.Addr().String()) cookies := assertGet(c, "http://"+l.Addr, "example.com", "1") discoverdRegisterHTTP(c, l, srv2.Listener.Addr().String()) for i := 0; i < 10; i++ { resCookies := assertGetCookies(c, "http://"+l.Addr, "example.com", "1", cookies) c.Assert(resCookies, HasLen, 0) httpClient.Transport.(*http.Transport).CloseIdleConnections() } unregister() for i := 0; i < 10; i++ { resCookies := assertGetCookies(c, "http://"+l.Addr, "example.com", "2", cookies) c.Assert(resCookies, Not(HasLen), 0) } }
func TestMain(m *testing.M) { generateMetrics() masterRouter := http.NewServeMux() masterRouter.HandleFunc("/metrics/snapshot", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(masterMetrics) }) masterTestServer = httptest.NewServer(masterRouter) slaveRouter := http.NewServeMux() slaveRouter.HandleFunc("/metrics/snapshot", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(slaveMetrics) }) slaveRouter.HandleFunc("/monitor/statistics", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode([]map[string]interface{}{slaveTaskMetrics}) }) slaveTestServer = httptest.NewServer(slaveRouter) rc := m.Run() masterTestServer.Close() slaveTestServer.Close() os.Exit(rc) }