github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/apiserver/testing/http.go (about) 1 // Copyright 2018 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package testing 5 6 import ( 7 "io" 8 "io/ioutil" 9 "net/http" 10 11 jc "github.com/juju/testing/checkers" 12 "github.com/juju/testing/httptesting" 13 "github.com/juju/utils" 14 gc "gopkg.in/check.v1" 15 16 "github.com/juju/juju/apiserver/params" 17 ) 18 19 // httpRequestParams holds parameters for the sendHTTPRequest methods. 20 type HTTPRequestParams struct { 21 // do is used to make the HTTP request. 22 // If it is nil, utils.GetNonValidatingHTTPClient().Do will be used. 23 // If the body reader implements io.Seeker, 24 // req.Body will also implement that interface. 25 Do func(req *http.Request) (*http.Response, error) 26 27 // expectError holds the error regexp to match 28 // against the error returned from the HTTP Do 29 // request. If it is empty, the error is expected to be 30 // nil. 31 ExpectError string 32 33 // tag holds the tag to authenticate as. 34 Tag string 35 36 // password holds the password associated with the tag. 37 Password string 38 39 // method holds the HTTP method to use for the request. 40 Method string 41 42 // url holds the URL to send the HTTP request to. 43 URL string 44 45 // contentType holds the content type of the request. 46 ContentType string 47 48 // body holds the body of the request. 49 Body io.Reader 50 51 // extra headers are added to the http header 52 ExtraHeaders map[string]string 53 54 // jsonBody holds an object to be marshaled as JSON 55 // as the body of the request. If this is specified, body will 56 // be ignored and the Content-Type header will 57 // be set to application/json. 58 JSONBody interface{} 59 60 // nonce holds the machine nonce to provide in the header. 61 Nonce string 62 } 63 64 func SendHTTPRequest(c *gc.C, p HTTPRequestParams) *http.Response { 65 c.Logf("sendRequest: %s", p.URL) 66 hp := httptesting.DoRequestParams{ 67 Do: p.Do, 68 Method: p.Method, 69 URL: p.URL, 70 Body: p.Body, 71 JSONBody: p.JSONBody, 72 Header: make(http.Header), 73 Username: p.Tag, 74 Password: p.Password, 75 ExpectError: p.ExpectError, 76 } 77 if p.ContentType != "" { 78 hp.Header.Set("Content-Type", p.ContentType) 79 } 80 for key, value := range p.ExtraHeaders { 81 hp.Header.Set(key, value) 82 } 83 if p.Nonce != "" { 84 hp.Header.Set(params.MachineNonceHeader, p.Nonce) 85 } 86 if hp.Do == nil { 87 hp.Do = utils.GetNonValidatingHTTPClient().Do 88 } 89 return httptesting.Do(c, hp) 90 } 91 92 func AssertResponse(c *gc.C, resp *http.Response, expHTTPStatus int, expContentType string) []byte { 93 body, err := ioutil.ReadAll(resp.Body) 94 resp.Body.Close() 95 c.Assert(err, jc.ErrorIsNil) 96 c.Check(resp.StatusCode, gc.Equals, expHTTPStatus, gc.Commentf("body: %s", body)) 97 ctype := resp.Header.Get("Content-Type") 98 c.Assert(ctype, gc.Equals, expContentType) 99 return body 100 }