github.com/artpar/rclone@v1.67.3/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  )
    11  
    12  // declare a few helper functions
    13  
    14  // wantFunc tests the HTTP response in res and marks the test as errored if something is incorrect.
    15  type wantFunc func(t testing.TB, res *httptest.ResponseRecorder)
    16  
    17  // newRequest returns a new HTTP request with the given params
    18  func newRequest(t testing.TB, method, path string, body io.Reader) *http.Request {
    19  	req := httptest.NewRequest(method, path, body)
    20  	req.Header.Add("Accept", resticAPIV2)
    21  	return req
    22  }
    23  
    24  // wantCode returns a function which checks that the response has the correct HTTP status code.
    25  func wantCode(code int) wantFunc {
    26  	return func(t testing.TB, res *httptest.ResponseRecorder) {
    27  		assert.Equal(t, code, res.Code)
    28  	}
    29  }
    30  
    31  // wantBody returns a function which checks that the response has the data in the body.
    32  func wantBody(body string) wantFunc {
    33  	return func(t testing.TB, res *httptest.ResponseRecorder) {
    34  		assert.NotNil(t, res.Body)
    35  		assert.Equal(t, res.Body.Bytes(), []byte(body))
    36  	}
    37  }
    38  
    39  // checkRequest uses f to process the request and runs the checker functions on the result.
    40  func checkRequest(t testing.TB, f http.HandlerFunc, req *http.Request, want []wantFunc) {
    41  	rr := httptest.NewRecorder()
    42  	f(rr, req)
    43  
    44  	for _, fn := range want {
    45  		fn(t, rr)
    46  	}
    47  }
    48  
    49  // TestRequest is a sequence of HTTP requests with (optional) tests for the response.
    50  type TestRequest struct {
    51  	req  *http.Request
    52  	want []wantFunc
    53  }