github.com/ncw/rclone@v1.48.1-0.20190724201158-a35aa1360e3e/cmd/serve/restic/restic_test_utils.go (about)

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