package httpbin import ( "bufio" "bytes" "compress/gzip" "compress/zlib" "context" "encoding/json" "errors" "fmt" "io/ioutil" "log" "math/rand" "mime/multipart" "net/http" "net/http/httptest" "net/url" "reflect" "regexp" "strconv" "strings" "testing" "time" ) const maxBodySize int64 = 1024 * 1024 const maxDuration time.Duration = 1 * time.Second const alphanumLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var testDefaultParams = DefaultParams{ DripDelay: 0, DripDuration: 100 * time.Millisecond, DripNumBytes: 10, } var app = New( WithDefaultParams(testDefaultParams), WithMaxBodySize(maxBodySize), WithMaxDuration(maxDuration), WithObserver(StdLogObserver(log.New(ioutil.Discard, "", 0))), ) var handler = app.Handler() func assertStatusCode(t *testing.T, w *httptest.ResponseRecorder, code int) { if w.Code != code { t.Fatalf("expected status code %d, got %d", code, w.Code) } } func assertHeader(t *testing.T, w *httptest.ResponseRecorder, key, val string) { if w.Header().Get(key) != val { t.Fatalf("expected header %s=%#v, got %#v", key, val, w.Header().Get(key)) } } func assertContentType(t *testing.T, w *httptest.ResponseRecorder, contentType string) { assertHeader(t, w, "Content-Type", contentType) } func assertBodyContains(t *testing.T, w *httptest.ResponseRecorder, needle string) { if !strings.Contains(w.Body.String(), needle) { t.Fatalf("expected string %q in body %q", needle, w.Body.String()) } } func assertBodyEquals(t *testing.T, w *httptest.ResponseRecorder, want string) { have := w.Body.String() if want != have { t.Fatalf("expected body = %v, got %v", want, have) } } func randStringBytes(n int) string { rand.Seed(time.Now().UnixNano()) b := make([]byte, n) for i := range b { b[i] = alphanumLetters[rand.Intn(len(alphanumLetters))] } return string(b) } func TestIndex(t *testing.T) { r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() handler.ServeHTTP(w, r) assertContentType(t, w, htmlContentType) assertHeader(t, w, "Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' camo.githubusercontent.com") assertBodyContains(t, w, "go-httpbin") } func TestIndex__NotFound(t *testing.T) { r, _ := http.NewRequest("GET", "/foo", nil) w := httptest.NewRecorder() handler.ServeHTTP(w, r) assertStatusCode(t, w, http.StatusNotFound) } func TestFormsPost(t *testing.T) { r, _ := http.NewRequest("GET", "/forms/post", nil) w := httptest.NewRecorder() handler.ServeHTTP(w, r) assertContentType(t, w, htmlContentType) assertBodyContains(t, w, `