func TestSuperviceReadLimit(t *testing.T) { buf.Reset() var server *httptest.Server var h http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "0123456789") } server = httptest.NewServer(h) defer server.Close() s := make(Services) s["s 1"] = &Service{ Name: "s 1", URL: server.URL, ReadLimit: 5, Expect: Expect{ Status: 200, }, } ez := &Epazote{ Services: s, } ez.debug = true ez.Supervice(s["s 1"])() rc := s["s 1"].retryCount if rc != 0 { t.Errorf("Expecting retryCount = 0 got: %d", rc) } data := buf.String() re := regexp.MustCompile("(?m)[\r\n]+^01234$") match := re.FindString(data) if match == "" { t.Error("Expecting: 01234") } }
func doTestProxy(t *testing.T, origin *httptest.Server, server *httptest.Server, disableKeepAlives bool) { u, _ := url.Parse(server.URL) client := &http.Client{Transport: &http.Transport{ Dial: func(network, addr string) (net.Conn, error) { conn, err := net.Dial("tcp", u.Host) if err == nil { initReq, reqErr := http.NewRequest("GET", fmt.Sprintf("http://%v", addr), nil) if reqErr != nil { return nil, fmt.Errorf("Unable to construct initial request: %v", reqErr) } initReq.Header.Set(XLanternPersistent, "true") writeErr := initReq.Write(conn) if writeErr != nil { return nil, fmt.Errorf("Unable to write initial request: %v", writeErr) } } return conn, err }, DisableKeepAlives: disableKeepAlives, }} // Do a simple GET if !testGet(t, client, origin) { return } // Do another GET to test keepalive functionality if !testGet(t, client, origin) { return } // Forcibly close client connections and make sure we can still proxy origin.CloseClientConnections() testGet(t, client, origin) }
func TestHTTPAuth(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { from, err := HostPortToIP(r.RemoteAddr) if err != nil { t.Fatal(err) } to := ts.Listener.Addr() uid, err := AddrPairUserid(from, to) if err != nil { fmt.Fprintf(rw, "ERR: %v", err) return } fmt.Fprintf(rw, "uid=%d", uid) })) defer ts.Close() res, err := http.Get(ts.URL) if err != nil { t.Fatal(err) } body, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if g, e := string(body), fmt.Sprintf("uid=%d", os.Getuid()); g != e { t.Errorf("got body %q; want %q", g, e) } }
func TestGetData(t *testing.T) { var err error var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Write([]byte("1 2 3 4 5")) })) defer ts.Close() i := 0 writer := JsonWriteFunc(func(d json.RawMessage) error { i++ return nil }) n, err := getData(ts.URL, writer, nil) if err != nil { t.Error(err) } if n != 5 { t.Error("n != 5") } if i != 5 { t.Error("i != 5") } }
func TestSubmitTasks(t *testing.T) { var err error var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(201) })) defer ts.Close() TASKS_ADDRESS = ts.URL + "/%s/tasks" i := 0 reader := JsonReaderFunc(func(d *json.RawMessage) error { if i == 5 { return io.EOF } i++ data := json.RawMessage("1") d = &data return nil }) n, err := SubmitTasks("", reader) if err != nil { t.Error(err) } if n != 5 { t.Error("n != 5") } }
func TestListProjectsThroughChannel(t *testing.T) { page := 0 var ts *httptest.Server ts = httptest.NewServer(authenticated(t, "GET", "/projects", func(w http.ResponseWriter, r *http.Request) { page += 1 if page < 10 { w.Header().Set("Link", fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", ts.URL, r.URL.Path, page+1)) } response(array_of_projects)(w, r) })) defer ts.Close() f := letsTestFreckle(ts) pp, err := f.ProjectsAPI().ListProjects() assert.Nil(t, err, "Error should be nil") projects := 0 // reading through the channel should do 10 HTTP request, yielding 1 project each for _ = range pp.AllProjects() { projects += 1 } assert.Equal(t, 10, projects, "Should have read 10 projects") assert.Equal(t, 10, page, "We should have read up to page 10") }
func init() { suite := &routertest.RouterSuite{ SetUpSuiteFunc: func(c *check.C) { config.Set("routers:galeb:username", "myusername") config.Set("routers:galeb:password", "mypassword") config.Set("routers:galeb:domain", "galeb.com") config.Set("routers:galeb:type", "galeb") config.Set("database:url", "127.0.0.1:27017") config.Set("database:name", "router_galebv2_tests") }, } var server *httptest.Server suite.SetUpTestFunc = func(c *check.C) { handler, err := NewFakeGalebServer() c.Assert(err, check.IsNil) server = httptest.NewServer(handler) config.Set("routers:galeb:api-url", server.URL+"/api") gRouter, err := createRouter("routers:galeb") c.Assert(err, check.IsNil) suite.Router = gRouter conn, err := db.Conn() c.Assert(err, check.IsNil) defer conn.Close() dbtest.ClearAllCollections(conn.Collection("router_galebv2_tests").Database) } suite.TearDownTestFunc = func(c *check.C) { server.Close() } check.Suite(suite) }
func teardown(server *httptest.Server) { server.Close() // Cleanup cache files. er := os.RemoveAll("./raincollector") if er != nil { panic(er.Error()) } }
func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) { defer afterTest(t) var log struct { sync.Mutex bytes.Buffer } var ts *httptest.Server ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { log.Lock() slurp, _ := ioutil.ReadAll(r.Body) fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp) log.Unlock() urlQuery := r.URL.Query() if v := urlQuery.Get("code"); v != "" { location := ts.URL if final := urlQuery.Get("next"); final != "" { splits := strings.Split(final, ",") first, rest := splits[0], splits[1:] location = fmt.Sprintf("%s?code=%s", location, first) if len(rest) > 0 { location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ",")) } } code, _ := strconv.Atoi(v) if code/100 == 3 { w.Header().Set("Location", location) } w.WriteHeader(code) } })) defer ts.Close() for _, tt := range table { content := tt.redirectBody req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content)) req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil } res, err := DefaultClient.Do(req) if err != nil { t.Fatal(err) } if res.StatusCode != tt.want { t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want) } } log.Lock() got := log.String() log.Unlock() got = strings.TrimSpace(got) want = strings.TrimSpace(want) if got != want { t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want) } }
func TestRedirectCookiesJar(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(echoCookiesRedirectHandler) defer ts.Close() c := &Client{} c.Jar = &TestJar{perURL: make(map[string][]*Cookie)} u, _ := url.Parse(ts.URL) c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]}) resp, _ := c.Get(ts.URL) matchReturnedCookies(t, expectedCookies, resp.Cookies()) }
func TestFeedManagerDetection(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.RequestURI == "/link" { w.WriteHeader(http.StatusOK) w.Write([]byte(strings.Replace(atomXml, "{{ .FeedLink }}", ts.URL+"/link", -1))) } else if r.RequestURI == "/html" { w.Write([]byte(` <html> <head> <link type="text/css" href="/foo.css"> <link rel="alternative" type="application/rss+xml" href="/link"/> </head> <body><main></main></body> </html> `)) } else { w.WriteHeader(http.StatusNotFound) } })) defer ts.Close() _, err := discoverParserFeeds(ts.URL) if err == nil { t.Fatalf("Expected an ErrNoFeed error, got nothing\n") } else if err != ErrNoFeed { t.Fatalf("Expected an ErrNoFeed error, got %v\n", err) } pf, err := discoverParserFeeds(ts.URL + "/link") if err != nil { t.Fatal(err) } expectedStr := ts.URL + "/link" if pf[0].Link != expectedStr { t.Fatalf("Expected '%s' for a url, got '%s'\n", expectedStr, pf[0].Link) } pf, err = discoverParserFeeds(ts.URL + "/html") if err != nil { t.Fatal(err) } expectedStr = ts.URL + "/link" if pf[0].Link != expectedStr { t.Fatalf("Expected '%s' for a url, got '%s'\n", expectedStr, pf[0].Link) } }
func TestFetchCertBreadth(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for i := 0; i < maxChainLen+1; i++ { w.Header().Add("link", fmt.Sprintf("<%s>;rel=up", ts.URL)) } w.Write([]byte{1}) })) defer ts.Close() _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true) if err == nil { t.Errorf("err is nil") } }
func TestWithHttptestWithSpecifiedPort(t *testing.T) { router := New() router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) l, _ := net.Listen("tcp", ":8033") ts := httptest.Server{ Listener: l, Config: &http.Server{Handler: router}, } ts.Start() defer ts.Close() testRequest(t, "http://localhost:8033/example") }
func TestRedirectCookiesJar(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(echoCookiesRedirectHandler) defer ts.Close() c := &http.Client{ Jar: new(TestJar), } u, _ := url.Parse(ts.URL) c.Jar.SetCookies(u, []*http.Cookie{expectedCookies[0]}) resp, err := c.Get(ts.URL) if err != nil { t.Fatalf("Get: %v", err) } matchReturnedCookies(t, expectedCookies, resp.Cookies()) }
func TestRedirectCookiesOnRequest(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(echoCookiesRedirectHandler) defer ts.Close() c := &Client{} req, _ := NewRequest("GET", ts.URL, nil) req.AddCookie(expectedCookies[0]) // TODO: Uncomment when an implementation of a RFC6265 cookie jar lands. _ = c // resp, _ := c.Do(req) // matchReturnedCookies(t, expectedCookies, resp.Cookies()) req, _ = NewRequest("GET", ts.URL, nil) // resp, _ = c.Do(req) // matchReturnedCookies(t, expectedCookies[1:], resp.Cookies()) }
func TestDeleteJobs(t *testing.T) { var err error var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })) defer ts.Close() JOBS_ADDRESS = ts.URL err = DeleteJobs() if err != nil { t.Error(err) } }
func TestPostRedirects(t *testing.T) { defer afterTest(t) var log struct { sync.Mutex bytes.Buffer } var ts *httptest.Server ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { log.Lock() fmt.Fprintf(&log.Buffer, "%s %s ", r.Method, r.RequestURI) log.Unlock() if v := r.URL.Query().Get("code"); v != "" { code, _ := strconv.Atoi(v) if code/100 == 3 { w.Header().Set("Location", ts.URL) } w.WriteHeader(code) } })) defer ts.Close() tests := []struct { suffix string want int // response code }{ {"/", 200}, {"/?code=301", 301}, {"/?code=302", 200}, {"/?code=303", 200}, {"/?code=404", 404}, } for _, tt := range tests { res, err := Post(ts.URL+tt.suffix, "text/plain", strings.NewReader("Some content")) if err != nil { t.Fatal(err) } if res.StatusCode != tt.want { t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want) } } log.Lock() got := log.String() log.Unlock() want := "POST / POST /?code=301 POST /?code=302 GET / POST /?code=303 GET / POST /?code=404 " if got != want { t.Errorf("Log differs.\n Got: %q\nWant: %q", got, want) } }
func (t *WebRuleTest) TestHandleHttpFailures(c *C) { var s *httptest.Server s = httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.CloseClientConnections() })) r := NewWebRule( "test rule", s.URL, "cats", "dogs") sane, triggered := r.TestTriggered() c.Check(sane, Equals, false) c.Check(triggered, Equals, false) }
func TestGoogleProviderGetEmailAddressInvalidEncoding(t *testing.T) { p := newGoogleProvider() body, err := json.Marshal(redeemResponse{ AccessToken: "a1234", IdToken: "ignored prefix." + `{"email": "*****@*****.**"}`, }) assert.Equal(t, nil, err) var server *httptest.Server p.RedeemUrl, server = newRedeemServer(body) defer server.Close() session, err := p.Redeem("http://redirect/", "code1234") assert.NotEqual(t, nil, err) if session != nil { t.Errorf("expect nill session %#v", session) } }
func TestCheckStatusEtcdNoHealthNoConnect(t *testing.T) { t.Skip("this test isn't working - hangs") var ts *httptest.Server var f func(http.ResponseWriter, *http.Request) f = func(w http.ResponseWriter, r *http.Request) { switch r.URL.String() { case "/v2/members": m1 := []memb{{ ClientURLs: []string{"http://" + r.Host}, ID: "fumble", Name: "newstuff", PeerURLs: []string{"http://" + r.Host}, }} m := &members{Members: m1} b, err := json.Marshal(m) if err != nil { t.Fatal("Marshal failed") } fmt.Fprintf(w, string(b)) return case "/health": ts.Close() return } fmt.Fprintln(w, "hello there etcd user") } ts = httptest.NewServer(http.HandlerFunc(f)) defer ts.Close() cfg := []*Config{{ Name: "SiteCheckTest", Type: "etcd", URL: []string{ts.URL}, Timeout: 20, }} s := &server{cfg: cfg} s.refresh(Wait) failCheck(t, cfg) }
func TestGoogleProviderGetEmailAddressEmailMissing(t *testing.T) { p := newGoogleProvider() body, err := json.Marshal(redeemResponse{ AccessToken: "a1234", IdToken: "ignored prefix." + base64.URLEncoding.EncodeToString([]byte(`{"not_email": "missing"}`)), }) assert.Equal(t, nil, err) var server *httptest.Server p.RedeemUrl, server = newRedeemServer(body) defer server.Close() session, err := p.Redeem("http://redirect/", "code1234") assert.NotEqual(t, nil, err) if session != nil { t.Errorf("expect nill session %#v", session) } }
func TestFetchCertDepth(t *testing.T) { var count byte var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { count++ if count > maxChainLen+1 { t.Errorf("count = %d; want at most %d", count, maxChainLen+1) w.WriteHeader(http.StatusInternalServerError) } w.Header().Set("link", fmt.Sprintf("<%s>;rel=up", ts.URL)) w.Write([]byte{count}) })) defer ts.Close() _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true) if err == nil { t.Errorf("err is nil") } }
func TestClientRedirectUseResponse(t *testing.T) { setParallel(t) defer afterTest(t) const body = "Hello, world." var ts *httptest.Server ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { if strings.Contains(r.URL.Path, "/other") { io.WriteString(w, "wrong body") } else { w.Header().Set("Location", ts.URL+"/other") w.WriteHeader(StatusFound) io.WriteString(w, body) } })) defer ts.Close() tr := &Transport{} defer tr.CloseIdleConnections() c := &Client{ Transport: tr, CheckRedirect: func(req *Request, via []*Request) error { if req.Response == nil { t.Error("expected non-nil Request.Response") } return ErrUseLastResponse }, } res, err := c.Get(ts.URL) if err != nil { t.Fatal(err) } if res.StatusCode != StatusFound { t.Errorf("status = %d; want %d", res.StatusCode, StatusFound) } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatal(err) } if string(slurp) != body { t.Errorf("body = %q; want %q", slurp, body) } }
// ExpectS3Artifact will setup queue to expect an S3 artifact with given // name to be created for taskID and runID using m and returns // a channel which will receive the artifact. func (m *MockQueue) ExpectS3Artifact(taskID string, runID int, name string) <-chan []byte { // make channel size 100 so we don't have to handle synchronously c := make(chan []byte, 100) var s *httptest.Server s = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { d, err := ioutil.ReadAll(r.Body) if err != nil { close(c) w.WriteHeader(500) return } if r.Header.Get("Content-Encoding") == "gzip" { reader, err := gzip.NewReader(bytes.NewReader(d)) if err != nil { close(c) w.WriteHeader(500) return } d, err = ioutil.ReadAll(reader) if err != nil { close(c) w.WriteHeader(500) return } } w.WriteHeader(200) c <- d go s.Close() // Close when all requests are done (don't block the request) })) data, _ := json.Marshal(queue.S3ArtifactResponse{ StorageType: "s3", PutURL: s.URL, ContentType: "application/octet", Expires: tcclient.Time(time.Now().Add(30 * time.Minute)), }) result := queue.PostArtifactResponse(data) m.On( "CreateArtifact", taskID, fmt.Sprintf("%d", runID), name, PostS3ArtifactRequest, ).Return(&result, nil) return c }
func TestGoogleProviderGetEmailAddress(t *testing.T) { p := newGoogleProvider() body, err := json.Marshal(redeemResponse{ AccessToken: "a1234", ExpiresIn: 10, RefreshToken: "refresh12345", IdToken: "ignored prefix." + base64.URLEncoding.EncodeToString([]byte(`{"email": "*****@*****.**", "email_verified":true}`)), }) assert.Equal(t, nil, err) var server *httptest.Server p.RedeemUrl, server = newRedeemServer(body) defer server.Close() session, err := p.Redeem("http://redirect/", "code1234") assert.Equal(t, nil, err) assert.NotEqual(t, session, nil) assert.Equal(t, "*****@*****.**", session.Email) assert.Equal(t, "a1234", session.AccessToken) assert.Equal(t, "refresh12345", session.RefreshToken) }
func TestFetchCert(t *testing.T) { var count byte var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { count++ if count < 3 { up := fmt.Sprintf("<%s>;rel=up", ts.URL) w.Header().Set("link", up) } w.Write([]byte{count}) })) defer ts.Close() res, err := (&Client{}).FetchCert(context.Background(), ts.URL, true) if err != nil { t.Fatalf("FetchCert: %v", err) } cert := [][]byte{{1}, {2}, {3}} if !reflect.DeepEqual(res, cert) { t.Errorf("res = %v; want %v", res, cert) } }
func TestListJobs(t *testing.T) { var err error var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Write([]byte(`[ { "id": "job1" }, { "id": "job2" } ]`)) })) defer ts.Close() JOBS_ADDRESS = ts.URL jobs, err := ListJobs() if err != nil { t.Error(err) } if len(jobs) != 2 { t.Error("len(jobs) != 2") } }
func TestShowJob(t *testing.T) { var err error var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Write([]byte(`{ "id": "jobId" }`)) })) defer ts.Close() JOBS_ADDRESS = ts.URL job, err := ShowJob("jobId") if err != nil { t.Error(err) } if job.Id != "jobId" { t.Error("job.Id != 'jobId'") } }
func TestRedirectCookiesJar(t *testing.T) { setParallel(t) defer afterTest(t) var ts *httptest.Server ts = httptest.NewServer(echoCookiesRedirectHandler) defer ts.Close() tr := &Transport{} defer tr.CloseIdleConnections() c := &Client{ Transport: tr, Jar: new(TestJar), } u, _ := url.Parse(ts.URL) c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]}) resp, err := c.Get(ts.URL) if err != nil { t.Fatalf("Get: %v", err) } resp.Body.Close() matchReturnedCookies(t, expectedCookies, resp.Cookies()) }
func GetTestServerMessage(p *Proxy, ts *httptest.Server, path string) (string, error) { echoProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p.ServeHTTP(w, r) })) // *httptest.Server is passed so it can be `defer`red properly defer ts.Close() defer echoProxy.Close() res, err := http.Get(echoProxy.URL + path) if err != nil { return "", fmt.Errorf("Unable to GET: %v", err) } greeting, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { return "", fmt.Errorf("Unable to read body: %v", err) } return fmt.Sprintf("%s", greeting), nil }