pax_global_header00006660000000000000000000000064142351013460014511gustar00rootroot0000000000000052 comment=70f2cf5ffd8b222de3cec3dea52e4da458f6a7b0 golang-github-juju-qthttptest-0.1.3/000077500000000000000000000000001423510134600174365ustar00rootroot00000000000000golang-github-juju-qthttptest-0.1.3/.travis.yml000066400000000000000000000002351423510134600215470ustar00rootroot00000000000000language: go go_import_path: "github.com/juju/qthttptest" go: - "1.11.x" - "1.12.x" - "1.13.x" - 1.x - master script: GO111MODULE=on go test ./... golang-github-juju-qthttptest-0.1.3/LICENCE000066400000000000000000000215011423510134600204220ustar00rootroot00000000000000All files in this repository are licensed as follows. If you contribute to this repository, it is assumed that you license your contribution under the same license unless you state otherwise. All files Copyright (C) 2015 Canonical Ltd. unless otherwise specified in the file. This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. golang-github-juju-qthttptest-0.1.3/README.md000066400000000000000000000004141423510134600207140ustar00rootroot00000000000000# qthttptest: check JSON HTTP responses This package adds some [quicktest](https://godoc.org/github.com/frankban/quicktest)-compatible checks that check the result of HTTP responses. It also provides some checkers that check unmarshaled data from other formats too. golang-github-juju-qthttptest-0.1.3/codec.go000066400000000000000000000026621423510134600210500ustar00rootroot00000000000000// Copyright 2012-2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package qthttptest import ( qt "github.com/frankban/quicktest" "gopkg.in/mgo.v2/bson" yaml "gopkg.in/yaml.v3" ) // BSONEquals defines a checker that checks whether a byte slice, when // unmarshaled as BSON, is equal to the given value. Rather than // unmarshaling into something of the expected body type, we reform // the expected body in BSON and back to interface{} so we can check // the whole content. Otherwise we lose information when unmarshaling. var BSONEquals = qt.CodecEquals(bson.Marshal, bson.Unmarshal) // JSONEquals defines a checker that checks whether a byte slice, when // unmarshaled as JSON, is equal to the given value. // Rather than unmarshaling into something of the expected // body type, we reform the expected body in JSON and // back to interface{}, so we can check the whole content. // Otherwise we lose information when unmarshaling. // // Deprecated: use qt.JSONEquals instead. var JSONEquals = qt.JSONEquals // YAMLEquals defines a checker that checks whether a byte slice, when // unmarshaled as YAML, is equal to the given value. // Rather than unmarshaling into something of the expected // body type, we reform the expected body in YAML and // back to interface{}, so we can check the whole content. // Otherwise we lose information when unmarshaling. var YAMLEquals = qt.CodecEquals(yaml.Marshal, yaml.Unmarshal) golang-github-juju-qthttptest-0.1.3/go.mod000066400000000000000000000006701423510134600205470ustar00rootroot00000000000000module github.com/juju/qthttptest go 1.17 require ( github.com/frankban/quicktest v1.7.2 gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b ) require ( github.com/google/go-cmp v0.3.1 // indirect github.com/kr/pretty v0.2.1 // indirect github.com/kr/text v0.1.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) golang-github-juju-qthttptest-0.1.3/go.sum000066400000000000000000000032451423510134600205750ustar00rootroot00000000000000github.com/frankban/quicktest v1.7.2 h1:2QxQoC1TS09S7fhCPsrvqYdvP1H5M1P1ih5ABm3BTYk= github.com/frankban/quicktest v1.7.2/go.mod h1:jaStnuzAqU1AJdCO0l53JDCJrVDKcS03DbaAcR7Ks/o= github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 h1:VpOs+IwYnYBaFnrNAeB8UUWtL3vEUnzSCL1nVjPhqrw= gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang-github-juju-qthttptest-0.1.3/http.go000066400000000000000000000246061423510134600207540ustar00rootroot00000000000000// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package qthttptest import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" "net/http/httptest" "net/textproto" "net/url" "strings" qt "github.com/frankban/quicktest" ) // BodyAsserter represents a function that can assert the correctness of // a JSON reponse. type BodyAsserter func(c *qt.C, body json.RawMessage) // JSONCallParams holds parameters for AssertJSONCall. // If left empty, some fields will automatically be filled with defaults. type JSONCallParams struct { // Do is used to make the HTTP request. // If it is nil, http.DefaultClient.Do will be used. // If the body reader implements io.Seeker, // req.Body will also implement that interface. Do func(req *http.Request) (*http.Response, error) // ExpectError holds the error regexp to match // against the error returned from the HTTP Do // request. If it is empty, the error is expected to be // nil. ExpectError string // Method holds the HTTP method to use for the call. // GET is assumed if this is empty. Method string // URL holds the URL to pass when making the request. // If the URL does not contain a host, a temporary // HTTP server is started running the Handler below // which is used for the host. URL string // Handler holds the handler to use to make the request. // It is ignored if the above URL field has a host part. Handler http.Handler // JSONBody specifies a JSON value to marshal to use // as the body of the request. If this is specified, Body will // be ignored and the Content-Type header will // be set to application/json. The request // body will implement io.Seeker. JSONBody interface{} // Body holds the body to send in the request. Body io.Reader // Header specifies the HTTP headers to use when making // the request. Header http.Header // ContentLength specifies the length of the body. // It may be zero, in which case the default net/http // content-length behaviour will be used. ContentLength int64 // Username, if specified, is used for HTTP basic authentication. Username string // Password, if specified, is used for HTTP basic authentication. Password string // ExpectStatus holds the expected HTTP status code. // http.StatusOK is assumed if this is zero. ExpectStatus int // ExpectBody holds the expected JSON body. // This may be a function of type BodyAsserter in which case it // will be called with the http response body to check the // result. ExpectBody interface{} // ExpectHeader holds any HTTP headers that must be present in the response. // Note that the response may also contain headers not in this field. ExpectHeader http.Header // Cookies, if specified, are added to the request. Cookies []*http.Cookie } // AssertJSONCall asserts that when the given handler is called with // the given parameters, the result is as specified. func AssertJSONCall(c *qt.C, p JSONCallParams) { c.Logf("JSON call, url %q", p.URL) if p.ExpectStatus == 0 { p.ExpectStatus = http.StatusOK } rec := DoRequest(c, DoRequestParams{ Do: p.Do, ExpectError: p.ExpectError, Handler: p.Handler, Method: p.Method, URL: p.URL, Body: p.Body, JSONBody: p.JSONBody, Header: p.Header, ContentLength: p.ContentLength, Username: p.Username, Password: p.Password, Cookies: p.Cookies, }) if p.ExpectError != "" { return } AssertJSONResponse(c, rec, p.ExpectStatus, p.ExpectBody) for k, v := range p.ExpectHeader { c.Assert(rec.HeaderMap[textproto.CanonicalMIMEHeaderKey(k)], qt.DeepEquals, v, qt.Commentf("header %q", k)) } } // AssertJSONResponse asserts that the given response recorder has // recorded the given HTTP status, response body and content type. If // expectBody is of type BodyAsserter it will be called with the response // body to ensure the response is correct. func AssertJSONResponse(c *qt.C, rec *httptest.ResponseRecorder, expectStatus int, expectBody interface{}) { c.Assert(rec.Code, qt.Equals, expectStatus, qt.Commentf("body: %s", rec.Body.Bytes())) // Ensure the response includes the expected body. if expectBody == nil { c.Assert(rec.Body.Bytes(), qt.HasLen, 0) return } c.Assert(rec.Header().Get("Content-Type"), qt.Equals, "application/json") if assertBody, ok := expectBody.(BodyAsserter); ok { var data json.RawMessage err := json.Unmarshal(rec.Body.Bytes(), &data) c.Assert(err, qt.Equals, nil, qt.Commentf("body: %s", rec.Body.Bytes())) assertBody(c, data) return } c.Assert(rec.Body.String(), JSONEquals, expectBody) } // DoRequestParams holds parameters for DoRequest. // If left empty, some fields will automatically be filled with defaults. type DoRequestParams struct { // Do is used to make the HTTP request. // If it is nil, http.DefaultClient.Do will be used. // If the body reader implements io.Seeker, // req.Body will also implement that interface. Do func(req *http.Request) (*http.Response, error) // ExpectError holds the error regexp to match // against the error returned from the HTTP Do // request. If it is empty, the error is expected to be // nil. ExpectError string // Method holds the HTTP method to use for the call. // GET is assumed if this is empty. Method string // URL holds the URL to pass when making the request. // If the URL does not contain a host, a temporary // HTTP server is started running the Handler below // which is used for the host. URL string // Handler holds the handler to use to make the request. // It is ignored if the above URL field has a host part. Handler http.Handler // JSONBody specifies a JSON value to marshal to use // as the body of the request. If this is specified, Body will // be ignored and the Content-Type header will // be set to application/json. The request // body will implement io.Seeker. JSONBody interface{} // Body holds the body to send in the request. Body io.Reader // Header specifies the HTTP headers to use when making // the request. Header http.Header // ContentLength specifies the length of the body. // It may be zero, in which case the default net/http // content-length behaviour will be used. ContentLength int64 // Username, if specified, is used for HTTP basic authentication. Username string // Password, if specified, is used for HTTP basic authentication. Password string // Cookies, if specified, are added to the request. Cookies []*http.Cookie } // DoRequest is the same as Do except that it returns // an httptest.ResponseRecorder instead of an http.Response. // This function exists for backward compatibility reasons. func DoRequest(c *qt.C, p DoRequestParams) *httptest.ResponseRecorder { resp := Do(c, p) if p.ExpectError != "" { return nil } defer resp.Body.Close() rec := httptest.NewRecorder() h := rec.Header() for k, v := range resp.Header { h[k] = v } rec.WriteHeader(resp.StatusCode) _, err := io.Copy(rec.Body, resp.Body) c.Assert(err, qt.Equals, nil) return rec } // Do invokes a request on the given handler with the given // parameters and returns the resulting HTTP response. // Note that, as with http.Client.Do, the response body // must be closed. func Do(c *qt.C, p DoRequestParams) *http.Response { if p.Method == "" { p.Method = "GET" } if p.Do == nil { p.Do = http.DefaultClient.Do } if reqURL, err := url.Parse(p.URL); err == nil && reqURL.Host == "" { srv := httptest.NewServer(p.Handler) defer srv.Close() p.URL = srv.URL + p.URL } if p.JSONBody != nil { data, err := json.Marshal(p.JSONBody) c.Assert(err, qt.Equals, nil) p.Body = bytes.NewReader(data) } // Note: we avoid NewRequest's odious reader wrapping by using // a custom nopCloser function. req, err := http.NewRequest(p.Method, p.URL, nopCloser(p.Body)) c.Assert(err, qt.Equals, nil) if p.JSONBody != nil { req.Header.Set("Content-Type", "application/json") } for key, val := range p.Header { req.Header[key] = val } if p.ContentLength != 0 { req.ContentLength = p.ContentLength } else { req.ContentLength = bodyContentLength(p.Body) } if p.Username != "" || p.Password != "" { req.SetBasicAuth(p.Username, p.Password) } for _, cookie := range p.Cookies { req.AddCookie(cookie) } resp, err := p.Do(req) if p.ExpectError != "" { c.Assert(err, qt.ErrorMatches, p.ExpectError) return nil } c.Assert(err, qt.Equals, nil) return resp } // bodyContentLength returns the Content-Length // to use for the given body. Usually http.NewRequest // would infer this (and the cases here come directly // from the logic in that function) but unfortunately // there's no way to avoid the NopCloser wrapping // for any of the types mentioned here. func bodyContentLength(body io.Reader) int64 { n := 0 switch v := body.(type) { case *bytes.Buffer: n = v.Len() case *bytes.Reader: n = v.Len() case *strings.Reader: n = v.Len() } return int64(n) } // nopCloser is like ioutil.NopCloser except that // the returned value implements io.Seeker if // r implements io.Seeker func nopCloser(r io.Reader) io.ReadCloser { if r == nil { return nil } rc, ok := r.(io.ReadCloser) if ok { return rc } rs, ok := r.(io.ReadSeeker) if ok { return readSeekNopCloser{rs} } return ioutil.NopCloser(r) } type readSeekNopCloser struct { io.ReadSeeker } func (readSeekNopCloser) Close() error { return nil } // URLRewritingTransport is an http.RoundTripper that can rewrite request // URLs. If the request URL has the prefix specified in Match that part // will be changed to the value specified in Replace. RoundTripper will // then be used to perform the resulting request. If RoundTripper is nil // http.DefaultTransport will be used. // // This can be used in tests that, for whatever reason, need to make a // call to a URL that's not in our control but we want to control the // results of HTTP requests to that URL. type URLRewritingTransport struct { MatchPrefix string Replace string RoundTripper http.RoundTripper } // RoundTrip implements http.RoundTripper. func (t URLRewritingTransport) RoundTrip(req *http.Request) (*http.Response, error) { rt := t.RoundTripper if rt == nil { rt = http.DefaultTransport } if !strings.HasPrefix(req.URL.String(), t.MatchPrefix) { return rt.RoundTrip(req) } req1 := *req var err error req1.URL, err = url.Parse(t.Replace + strings.TrimPrefix(req.URL.String(), t.MatchPrefix)) if err != nil { panic(err) } resp, err := rt.RoundTrip(&req1) if resp != nil { resp.Request = req } return resp, err } golang-github-juju-qthttptest-0.1.3/http_test.go000066400000000000000000000221351423510134600220060ustar00rootroot00000000000000// Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package qthttptest_test import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/juju/qthttptest" ) // handlerResponse holds the body of a testing handler response. type handlerResponse struct { URL string Method string Body string Auth bool Header http.Header } func makeHandler(c *qt.C, status int, ctype string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) c.Assert(err, qt.Equals, nil) hasAuth := req.Header.Get("Authorization") != "" for _, h := range []string{"User-Agent", "Content-Length", "Accept-Encoding", "Authorization"} { delete(req.Header, h) } // Create the response. response := handlerResponse{ URL: req.URL.String(), Method: req.Method, Body: string(body), Header: req.Header, Auth: hasAuth, } // Write the response. w.Header().Set("Content-Type", ctype) w.WriteHeader(status) enc := json.NewEncoder(w) err = enc.Encode(response) c.Assert(err, qt.Equals, nil) }) } var assertJSONCallTests = []struct { about string params qthttptest.JSONCallParams }{{ about: "simple request", params: qthttptest.JSONCallParams{ Method: "GET", URL: "/", }, }, { about: "method not specified", params: qthttptest.JSONCallParams{ URL: "/", }, }, { about: "POST request with a body", params: qthttptest.JSONCallParams{ Method: "POST", URL: "/my/url", Body: strings.NewReader("request body"), }, }, { about: "GET request with custom headers", params: qthttptest.JSONCallParams{ Method: "GET", URL: "/my/url", Header: http.Header{ "Custom1": {"header1", "header2"}, "Custom2": {"foo"}, }, }, }, { about: "POST request with a JSON body", params: qthttptest.JSONCallParams{ Method: "POST", URL: "/my/url", JSONBody: map[string]int{"hello": 99}, }, }, { about: "authentication", params: qthttptest.JSONCallParams{ URL: "/", Method: "PUT", Username: "who", Password: "bad-wolf", ExpectStatus: http.StatusOK, }, }, { about: "test for ExceptHeader in response", params: qthttptest.JSONCallParams{ URL: "/", Do: func(req *http.Request) (*http.Response, error) { resp, err := http.DefaultClient.Do(req) resp.StatusCode = http.StatusOK resp.Header["Custom"] = []string{"value1", "value2"} resp.Header["Ignored"] = []string{"value3", "value3"} return resp, err }, ExpectStatus: http.StatusOK, ExpectHeader: http.Header{ "Custom": {"value1", "value2"}, }, }, }, { about: "test case insensitive for ExceptHeader in response", params: qthttptest.JSONCallParams{ URL: "/", Do: func(req *http.Request) (*http.Response, error) { resp, err := http.DefaultClient.Do(req) resp.StatusCode = http.StatusOK resp.Header["Custom"] = []string{"value1", "value2"} resp.Header["Ignored"] = []string{"value3", "value3"} return resp, err }, ExpectStatus: http.StatusOK, ExpectHeader: http.Header{ "CUSTOM": {"value1", "value2"}, }, }, }, { about: "error status", params: qthttptest.JSONCallParams{ URL: "/", ExpectStatus: http.StatusBadRequest, }, }, { about: "custom Do", params: qthttptest.JSONCallParams{ URL: "/", ExpectStatus: http.StatusTeapot, Do: func(req *http.Request) (*http.Response, error) { resp, err := http.DefaultClient.Do(req) resp.StatusCode = http.StatusTeapot return resp, err }, }, }, { about: "custom Do with seekable JSON body", params: qthttptest.JSONCallParams{ URL: "/", ExpectStatus: http.StatusTeapot, JSONBody: 123, Do: func(req *http.Request) (*http.Response, error) { r, ok := req.Body.(io.ReadSeeker) if !ok { return nil, fmt.Errorf("body is not seeker") } data, err := ioutil.ReadAll(r) if err != nil { panic(err) } if string(data) != "123" { panic(fmt.Errorf(`unexpected body content, got %q want "123"`, data)) } r.Seek(0, 0) resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } resp.StatusCode = http.StatusTeapot return resp, err }, }, }, { about: "expect error", params: qthttptest.JSONCallParams{ URL: "/", ExpectStatus: http.StatusTeapot, Do: func(req *http.Request) (*http.Response, error) { return nil, fmt.Errorf("some error") }, ExpectError: "some error", }, }, { about: "expect error regexp", params: qthttptest.JSONCallParams{ URL: "/", ExpectStatus: http.StatusTeapot, Do: func(req *http.Request) (*http.Response, error) { return nil, fmt.Errorf("some bad error") }, ExpectError: "some .* error", }, }} func TestAssertJSONCall(t *testing.T) { c := qt.New(t) for _, test := range assertJSONCallTests { c.Run(test.about, func(c *qt.C) { params := test.params // A missing status is assumed to be http.StatusOK. status := params.ExpectStatus if status == 0 { status = http.StatusOK } // Create the HTTP handler for this test. params.Handler = makeHandler(c, status, "application/json") // Populate the expected body parameter. expectBody := handlerResponse{ URL: params.URL, Method: params.Method, Header: params.Header, } // A missing method is assumed to be "GET". if expectBody.Method == "" { expectBody.Method = "GET" } expectBody.Header = make(http.Header) if params.JSONBody != nil { expectBody.Header.Set("Content-Type", "application/json") } for k, v := range params.Header { expectBody.Header[k] = v } if params.JSONBody != nil { data, err := json.Marshal(params.JSONBody) c.Assert(err, qt.Equals, nil) expectBody.Body = string(data) params.Body = bytes.NewReader(data) } else if params.Body != nil { // Handle the request body parameter. body, err := ioutil.ReadAll(params.Body) c.Assert(err, qt.Equals, nil) expectBody.Body = string(body) params.Body = bytes.NewReader(body) } // Handle basic HTTP authentication. if params.Username != "" || params.Password != "" { expectBody.Auth = true } params.ExpectBody = expectBody qthttptest.AssertJSONCall(c, params) }) } } func TestAssertJSONCallWithBodyAsserter(t *testing.T) { c := qt.New(t) called := false params := qthttptest.JSONCallParams{ URL: "/", Handler: makeHandler(c, http.StatusOK, "application/json"), ExpectBody: qthttptest.BodyAsserter(func(c1 *qt.C, body json.RawMessage) { c.Assert(c1, qt.Equals, c) c.Assert(string(body), qthttptest.JSONEquals, handlerResponse{ URL: "/", Method: "GET", Header: make(http.Header), }) called = true }), } qthttptest.AssertJSONCall(c, params) c.Assert(called, qt.Equals, true) } func TestAssertJSONCallWithHostedURL(t *testing.T) { c := qt.New(t) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(fmt.Sprintf("%q", "ok "+req.URL.Path))) })) defer srv.Close() qthttptest.AssertJSONCall(c, qthttptest.JSONCallParams{ URL: srv.URL + "/foo", ExpectBody: "ok /foo", }) } var bodyReaderFuncs = []func(string) io.Reader{ func(s string) io.Reader { return strings.NewReader(s) }, func(s string) io.Reader { return bytes.NewBufferString(s) }, func(s string) io.Reader { return bytes.NewReader([]byte(s)) }, } func TestDoRequestWithInferrableContentLength(t *testing.T) { c := qt.New(t) text := "hello, world" for i, f := range bodyReaderFuncs { c.Logf("test %d", i) called := false qthttptest.DoRequest(c, qthttptest.DoRequestParams{ Handler: http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) { c.Check(req.ContentLength, qt.Equals, int64(len(text))) called = true }), Body: f(text), }) c.Assert(called, qt.Equals, true) } } // The TestAssertJSONCall above exercises the testing.AssertJSONCall succeeding // calls. Failures are already massively tested in practice. DoRequest and // AssertJSONResponse are also indirectly tested as they are called by // AssertJSONCall. func TestTransport(t *testing.T) { c := qt.New(t) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(r.URL.String())) })) defer server.Close() transport := qthttptest.URLRewritingTransport{ MatchPrefix: "http://example.com", Replace: server.URL, } client := http.Client{ Transport: &transport, } resp, err := client.Get("http://example.com/path") c.Assert(err, qt.Equals, nil) body, err := ioutil.ReadAll(resp.Body) c.Assert(err, qt.Equals, nil) resp.Body.Close() c.Assert(resp.Request.URL.String(), qt.Equals, "http://example.com/path") c.Assert(string(body), qt.Equals, "/path") transport.RoundTripper = &http.Transport{} resp, err = client.Get(server.URL + "/otherpath") c.Assert(err, qt.Equals, nil) body, err = ioutil.ReadAll(resp.Body) c.Assert(err, qt.Equals, nil) resp.Body.Close() c.Assert(resp.Request.URL.String(), qt.Equals, server.URL+"/otherpath") c.Assert(string(body), qt.Equals, "/otherpath") }