~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/github.com/joyent/gocommon/http/client_test.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package http
 
2
 
 
3
import (
 
4
        "bytes"
 
5
        "fmt"
 
6
        "io/ioutil"
 
7
        gc "launchpad.net/gocheck"
 
8
        "net/http"
 
9
        "testing"
 
10
 
 
11
        httpsuite "github.com/joyent/gocommon/testing"
 
12
        "github.com/joyent/gosign/auth"
 
13
)
 
14
 
 
15
const (
 
16
        Signature = "yK0J17CQ04ZvMsFLoH163Sjyg8tE4BoIeCsmKWLQKN3BYgSpR0XyqrecheQ2A0o4L99oSumYSKIscBSiH5rqdf4/1zC/FEkYOI2UzcIHYb1MPNzO3g/5X44TppYE+8dxoH99V+Ts8RT3ZurEYjQ8wmK0TnxdirAevSpbypZJaBOFXUZSxx80m5BD4QE/MSGo/eaVdJI/Iw+nardHNvimVCr6pRNycX1I4FdyRR6kgrAl2NkY2yxx/CAY21Ir+dmbG3A1x4GiIE485LLheAL5/toPo7Gh8G5fkrF9dXWVyX0k9AZXqXNWn5AZxc32dKL2enH09j/X86RtwiR1IEuPww=="
 
17
        key       = `-----BEGIN RSA PRIVATE KEY-----
 
18
MIIEowIBAAKCAQEAyLOtVh8qXjdwfjZZYwkEgg1yoSzmpKKpmzYW745lBGtPH87F
 
19
spHVHeqjmgFnBsARsD7CHzYyQTho7oLrAEbuF7tKdGRK25wJIenPKKuL+UVwZNeJ
 
20
VEXSiMNmX3Y4IqRteqRIjhw3DmXYHEWvBc2JVy8lWtyK+o6o8jlO0aRTTT2+dETp
 
21
yqKqNJyHVNz2u6XVtm7jqyLU7tAqW+qpr5zSoNmuUAyz6JDCRnlWvwp1qzuS1LV3
 
22
2HK9yfq8TGriDVPyPRpFRmiRGWGIrIKrmm4sIm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D
 
38
1GWrWav/sB3rQhpzCsRnNyj/mUn9T2bcnRX58C1gWY9zmpQ3QZhoXnZvf0+ltFNi
 
39
I36tcIMk5DixQgQ0Sm4iQalXdGGi4bMbqeaB3HWoZaNVc5XJwPYy6mNqOjuU657F
 
40
pcdLAoGBAOQRc5kaZ3APKGHu64DzKh5TOam9J2gpRSD5kF2fIkAeaYWU0bE9PlqV
 
41
MUxNRzxbIC16eCKFUoDkErIXGQfIMUOm+aCT/qpoAdXIvuO7H0OYRjMDmbscSDEV
 
42
cQYaFsx8Z1KwMVBTwDtiGXhd+82+dKnXxH4bZC+WAKs7L79HqhER
 
43
-----END RSA PRIVATE KEY-----`
 
44
)
 
45
 
 
46
func Test(t *testing.T) {
 
47
        gc.TestingT(t)
 
48
}
 
49
 
 
50
type LoopingHTTPSuite struct {
 
51
        httpsuite.HTTPSuite
 
52
        creds *auth.Credentials
 
53
}
 
54
 
 
55
func (s *LoopingHTTPSuite) SetUpSuite(c *gc.C) {
 
56
        s.HTTPSuite.SetUpSuite(c)
 
57
        authCreds, err := auth.NewAuth("test_user", key, "rsa-sha256")
 
58
        c.Assert(err, gc.IsNil)
 
59
        s.creds = &auth.Credentials{
 
60
                UserAuthentication: authCreds,
 
61
                SdcKeyId:           "test_key",
 
62
                SdcEndpoint:        auth.Endpoint{URL: "http://gotest.api.joyentcloud.com"},
 
63
        }
 
64
}
 
65
 
 
66
func (s *LoopingHTTPSuite) setupLoopbackRequest() (*http.Header, chan string, *Client) {
 
67
        var headers http.Header
 
68
        bodyChan := make(chan string, 1)
 
69
        handler := func(resp http.ResponseWriter, req *http.Request) {
 
70
                headers = req.Header
 
71
                bodyBytes, _ := ioutil.ReadAll(req.Body)
 
72
                req.Body.Close()
 
73
                bodyChan <- string(bodyBytes)
 
74
                resp.Header().Add("Content-Length", "0")
 
75
                resp.WriteHeader(http.StatusNoContent)
 
76
                resp.Write([]byte{})
 
77
        }
 
78
        s.Mux.HandleFunc("/", handler)
 
79
        client := New(s.creds, "", nil)
 
80
 
 
81
        return &headers, bodyChan, client
 
82
}
 
83
 
 
84
type HTTPClientTestSuite struct {
 
85
        LoopingHTTPSuite
 
86
}
 
87
 
 
88
type HTTPSClientTestSuite struct {
 
89
        LoopingHTTPSuite
 
90
}
 
91
 
 
92
var _ = gc.Suite(&HTTPClientTestSuite{})
 
93
var _ = gc.Suite(&HTTPSClientTestSuite{})
 
94
 
 
95
func (s *HTTPClientTestSuite) assertHeaderValues(c *gc.C, apiVersion string) {
 
96
        emptyHeaders := http.Header{}
 
97
        date := "Mon, 14 Oct 2013 18:49:29 GMT"
 
98
        headers, _ := createHeaders(emptyHeaders, s.creds, "content-type", date, apiVersion, false)
 
99
        contentTypes := []string{"content-type"}
 
100
        dateHeader := []string{"Mon, 14 Oct 2013 18:49:29 GMT"}
 
101
        authorizationHeader := []string{"Signature keyId=\"/test_user/keys/test_key\",algorithm=\"rsa-sha256\" " + Signature}
 
102
        headerData := map[string][]string{
 
103
                "Date": dateHeader, "Authorization": authorizationHeader,
 
104
                "Content-Type": contentTypes, "Accept": contentTypes, "User-Agent": []string{gojoyentAgent()}}
 
105
        if apiVersion != "" {
 
106
                headerData["X-Api-Version"] = []string{apiVersion}
 
107
        }
 
108
        expectedHeaders := http.Header(headerData)
 
109
        c.Assert(headers, gc.DeepEquals, expectedHeaders)
 
110
        c.Assert(emptyHeaders, gc.DeepEquals, http.Header{})
 
111
}
 
112
 
 
113
func (s *HTTPClientTestSuite) TestCreateHeadersNoApiVersion(c *gc.C) {
 
114
        s.assertHeaderValues(c, "")
 
115
}
 
116
 
 
117
func (s *HTTPClientTestSuite) TestCreateHeadersWithApiVersion(c *gc.C) {
 
118
        s.assertHeaderValues(c, "token")
 
119
}
 
120
 
 
121
func (s *HTTPClientTestSuite) TestCreateHeadersCopiesSupplied(c *gc.C) {
 
122
        initialHeaders := make(http.Header)
 
123
        date := "Mon, 14 Oct 2013 18:49:29 GMT"
 
124
        initialHeaders["Foo"] = []string{"Bar"}
 
125
        contentType := contentTypeJSON
 
126
        contentTypes := []string{contentType}
 
127
        dateHeader := []string{"Mon, 14 Oct 2013 18:49:29 GMT"}
 
128
        authorizationHeader := []string{"Signature keyId=\"/test_user/keys/test_key\",algorithm=\"rsa-sha256\" " + Signature}
 
129
        headers, _ := createHeaders(initialHeaders, s.creds, contentType, date, "", false)
 
130
        // it should not change the headers passed in
 
131
        c.Assert(initialHeaders, gc.DeepEquals, http.Header{"Foo": []string{"Bar"}})
 
132
        // The initial headers should be in the output
 
133
        c.Assert(headers, gc.DeepEquals,
 
134
                http.Header{"Foo": []string{"Bar"}, "Date": dateHeader, "Authorization": authorizationHeader,
 
135
                        "Content-Type": contentTypes, "Accept": contentTypes, "User-Agent": []string{gojoyentAgent()}})
 
136
}
 
137
 
 
138
func (s *HTTPClientTestSuite) TestBinaryRequestSetsUserAgent(c *gc.C) {
 
139
        headers, _, client := s.setupLoopbackRequest()
 
140
        req := RequestData{}
 
141
        resp := ResponseData{ExpectedStatus: []int{http.StatusNoContent}}
 
142
        err := client.BinaryRequest("POST", s.Server.URL, "", &req, &resp)
 
143
        c.Assert(err, gc.IsNil)
 
144
        agent := headers.Get("User-Agent")
 
145
        c.Check(agent, gc.Not(gc.Equals), "")
 
146
        c.Check(agent, gc.Equals, gojoyentAgent())
 
147
}
 
148
 
 
149
func (s *HTTPClientTestSuite) TestJSONRequestSetsUserAgent(c *gc.C) {
 
150
        headers, _, client := s.setupLoopbackRequest()
 
151
        req := RequestData{}
 
152
        resp := ResponseData{ExpectedStatus: []int{http.StatusNoContent}}
 
153
        err := client.JsonRequest("POST", s.Server.URL, "", &req, &resp)
 
154
        c.Assert(err, gc.IsNil)
 
155
        agent := headers.Get("User-Agent")
 
156
        c.Check(agent, gc.Not(gc.Equals), "")
 
157
        c.Check(agent, gc.Equals, gojoyentAgent())
 
158
}
 
159
 
 
160
func (s *HTTPClientTestSuite) TestBinaryRequestSetsContentLength(c *gc.C) {
 
161
        headers, bodyChan, client := s.setupLoopbackRequest()
 
162
        content := "binary\ncontent\n"
 
163
        req := RequestData{
 
164
                ReqReader: bytes.NewBufferString(content),
 
165
                ReqLength: len(content),
 
166
        }
 
167
        resp := ResponseData{ExpectedStatus: []int{http.StatusNoContent}}
 
168
        err := client.BinaryRequest("POST", s.Server.URL, "", &req, &resp)
 
169
        c.Assert(err, gc.IsNil)
 
170
        encoding := headers.Get("Transfer-Encoding")
 
171
        c.Check(encoding, gc.Equals, "")
 
172
        length := headers.Get("Content-Length")
 
173
        c.Check(length, gc.Equals, fmt.Sprintf("%d", len(content)))
 
174
        body, ok := <-bodyChan
 
175
        c.Assert(ok, gc.Equals, true)
 
176
        c.Check(body, gc.Equals, content)
 
177
}
 
178
 
 
179
func (s *HTTPClientTestSuite) TestJSONRequestSetsContentLength(c *gc.C) {
 
180
        headers, bodyChan, client := s.setupLoopbackRequest()
 
181
        reqMap := map[string]string{"key": "value"}
 
182
        req := RequestData{
 
183
                ReqValue: reqMap,
 
184
        }
 
185
        resp := ResponseData{ExpectedStatus: []int{http.StatusNoContent}}
 
186
        err := client.JsonRequest("POST", s.Server.URL, "", &req, &resp)
 
187
        c.Assert(err, gc.IsNil)
 
188
        encoding := headers.Get("Transfer-Encoding")
 
189
        c.Check(encoding, gc.Equals, "")
 
190
        length := headers.Get("Content-Length")
 
191
        body, ok := <-bodyChan
 
192
        c.Assert(ok, gc.Equals, true)
 
193
        c.Check(body, gc.Not(gc.Equals), "")
 
194
        c.Check(length, gc.Equals, fmt.Sprintf("%d", len(body)))
 
195
}
 
196
 
 
197
func (s *HTTPSClientTestSuite) TestDefaultClientRejectSelfSigned(c *gc.C) {
 
198
        _, _, client := s.setupLoopbackRequest()
 
199
        req := RequestData{}
 
200
        resp := ResponseData{ExpectedStatus: []int{http.StatusNoContent}}
 
201
        err := client.BinaryRequest("POST", s.Server.URL, "", &req, &resp)
 
202
        c.Assert(err, gc.NotNil)
 
203
        c.Check(err, gc.ErrorMatches, "(.|\\n)*x509: certificate signed by unknown authority")
 
204
}