github.com/10XDev/rclone@v1.52.3-0.20200626220027-16af9ab76b2a/cmd/serve/restic/restic_utils_test.go (about) 1 package restic 2 3 import ( 4 "io" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 ) 12 13 // declare a few helper functions 14 15 // wantFunc tests the HTTP response in res and marks the test as errored if something is incorrect. 16 type wantFunc func(t testing.TB, res *httptest.ResponseRecorder) 17 18 // newRequest returns a new HTTP request with the given params. On error, the 19 // test is marked as failed. 20 func newRequest(t testing.TB, method, path string, body io.Reader) *http.Request { 21 req, err := http.NewRequest(method, path, body) 22 require.NoError(t, err) 23 return req 24 } 25 26 // wantCode returns a function which checks that the response has the correct HTTP status code. 27 func wantCode(code int) wantFunc { 28 return func(t testing.TB, res *httptest.ResponseRecorder) { 29 assert.Equal(t, code, res.Code) 30 } 31 } 32 33 // wantBody returns a function which checks that the response has the data in the body. 34 func wantBody(body string) wantFunc { 35 return func(t testing.TB, res *httptest.ResponseRecorder) { 36 assert.NotNil(t, res.Body) 37 assert.Equal(t, res.Body.Bytes(), []byte(body)) 38 } 39 } 40 41 // checkRequest uses f to process the request and runs the checker functions on the result. 42 func checkRequest(t testing.TB, f http.HandlerFunc, req *http.Request, want []wantFunc) { 43 rr := httptest.NewRecorder() 44 f(rr, req) 45 46 for _, fn := range want { 47 fn(t, rr) 48 } 49 } 50 51 // TestRequest is a sequence of HTTP requests with (optional) tests for the response. 52 type TestRequest struct { 53 req *http.Request 54 want []wantFunc 55 }