Debian Codegraph @

oauth/oauth_test.go

raw symbols SCIP
1 // Copyright 2010 Gary Burd
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"): you may
4 // not use this file except in compliance with the License. You may obtain
5 // a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations
13 // under the License.
14
15 package oauth
16
17 import (
18 "bytes"
19 "crypto/x509"
20 "encoding/pem"
21 "io"
22 "io/ioutil"
23 "net/http"
24 "net/http/cookiejar"
25 "net/http/httptest"
26 "net/url"
27 "strings"
28 "testing"
29
30 "golang.org/x/net/context"
31 )
32
33 func parseURL(urlStr string) *url.URL {
34 u, err := url.Parse(urlStr)
35 if err != nil {
36 panic(err)
37 }
38 return u
39 }
40
41 var oauthTests = []struct {
42 method string
43 url *url.URL
44 form url.Values
45 nonce string
46 timestamp string
47
48 clientCredentials Credentials
49 credentials Credentials
50
51 signatureMethod SignatureMethod
52
53 base string
54 header string
55 }{
56 {
57 // Simple example from Twitter OAuth tool
58 method: "GET",
59 url: parseURL("https://api.twitter.com/1/"),
60 form: url.Values{"page": {"10"}},
61 nonce: "8067e8abc6bdca2006818132445c8f4c",
62 timestamp: "1355795903",
63 clientCredentials: Credentials{"kMViZR2MHk2mM7hUNVw9A", "56Fgl58yOfqXOhHXX0ybvOmSnPQFvR2miYmm30A"},
64 credentials: Credentials{"10212-JJ3Zc1A49qSMgdcAO2GMOpW9l7A348ESmhjmOBOU", "yF75mvq4LZMHj9O0DXwoC3ZxUnN1ptvieThYuOAYM"},
65 base: `GET&https%3A%2F%2Fapi.twitter.com%2F1%2F&oauth_consumer_key%3DkMViZR2MHk2mM7hUNVw9A%26oauth_nonce%3D8067e8abc6bdca2006818132445c8f4c%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1355795903%26oauth_token%3D10212-JJ3Zc1A49qSMgdcAO2GMOpW9l7A348ESmhjmOBOU%26oauth_version%3D1.0%26page%3D10`,
66 header: `OAuth oauth_consumer_key="kMViZR2MHk2mM7hUNVw9A", oauth_nonce="8067e8abc6bdca2006818132445c8f4c", oauth_signature="o5cx1ggJrY9ognZuVVeUwglKV8U%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1355795903", oauth_token="10212-JJ3Zc1A49qSMgdcAO2GMOpW9l7A348ESmhjmOBOU", oauth_version="1.0"`,
67 },
68 {
69 // Test case and port insensitivity.
70 method: "GeT",
71 url: parseURL("https://apI.twItter.com:443/1/"),
72 form: url.Values{"page": {"10"}},
73 nonce: "8067e8abc6bdca2006818132445c8f4c",
74 timestamp: "1355795903",
75 clientCredentials: Credentials{"kMViZR2MHk2mM7hUNVw9A", "56Fgl58yOfqXOhHXX0ybvOmSnPQFvR2miYmm30A"},
76 credentials: Credentials{"10212-JJ3Zc1A49qSMgdcAO2GMOpW9l7A348ESmhjmOBOU", "yF75mvq4LZMHj9O0DXwoC3ZxUnN1ptvieThYuOAYM"},
77 base: `GET&https%3A%2F%2Fapi.twitter.com%2F1%2F&oauth_consumer_key%3DkMViZR2MHk2mM7hUNVw9A%26oauth_nonce%3D8067e8abc6bdca2006818132445c8f4c%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1355795903%26oauth_token%3D10212-JJ3Zc1A49qSMgdcAO2GMOpW9l7A348ESmhjmOBOU%26oauth_version%3D1.0%26page%3D10`,
78 header: `OAuth oauth_consumer_key="kMViZR2MHk2mM7hUNVw9A", oauth_nonce="8067e8abc6bdca2006818132445c8f4c", oauth_signature="o5cx1ggJrY9ognZuVVeUwglKV8U%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1355795903", oauth_token="10212-JJ3Zc1A49qSMgdcAO2GMOpW9l7A348ESmhjmOBOU", oauth_version="1.0"`,
79 },
80 {
81 // Example generated using the Netflix OAuth tool.
82 method: "GET",
83 url: parseURL("http://api-public.netflix.com/catalog/titles"),
84 form: url.Values{"term": {"Dark Knight"}, "count": {"2"}},
85 nonce: "1234",
86 timestamp: "1355850443",
87 clientCredentials: Credentials{"apiKey001", "sharedSecret002"},
88 credentials: Credentials{"accessToken003", "accessSecret004"},
89 base: `GET&http%3A%2F%2Fapi-public.netflix.com%2Fcatalog%2Ftitles&count%3D2%26oauth_consumer_key%3DapiKey001%26oauth_nonce%3D1234%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1355850443%26oauth_token%3DaccessToken003%26oauth_version%3D1.0%26term%3DDark%2520Knight`,
90 header: `OAuth oauth_consumer_key="apiKey001", oauth_nonce="1234", oauth_signature="0JAoaqt6oz6TJx8N%2B06XmhPjcOs%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1355850443", oauth_token="accessToken003", oauth_version="1.0"`,
91 },
92 {
93 // Special characters in form values.
94 method: "GET",
95 url: parseURL("http://PHOTOS.example.net:8001/Photos"),
96 form: url.Values{"photo size": {"300%"}, "title": {"Back of $100 Dollars Bill"}},
97 nonce: "kllo~9940~pd9333jh",
98 timestamp: "1191242096",
99 clientCredentials: Credentials{"dpf43f3++p+#2l4k3l03", "secret01"},
100 credentials: Credentials{"nnch734d(0)0sl2jdk", "secret02"},
101 base: "GET&http%3A%2F%2Fphotos.example.net%3A8001%2FPhotos&oauth_consumer_key%3Ddpf43f3%252B%252Bp%252B%25232l4k3l03%26oauth_nonce%3Dkllo~9940~pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d%25280%25290sl2jdk%26oauth_version%3D1.0%26photo%2520size%3D300%2525%26title%3DBack%2520of%2520%2524100%2520Dollars%2520Bill",
102 header: `OAuth oauth_consumer_key="dpf43f3%2B%2Bp%2B%232l4k3l03", oauth_nonce="kllo~9940~pd9333jh", oauth_signature="n1UAoQy2PoIYizZUiWvkdCxM3P0%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1191242096", oauth_token="nnch734d%280%290sl2jdk", oauth_version="1.0"`,
103 },
104 {
105 // Special characters in path, multiple values for same key in form.
106 method: "GET",
107 url: parseURL("http://EXAMPLE.COM:80/Space%20Craft"),
108 form: url.Values{"name": {"value", "value"}},
109 nonce: "Ix4U1Ei3RFL",
110 timestamp: "1327384901",
111 clientCredentials: Credentials{"abcd", "efgh"},
112 credentials: Credentials{"ijkl", "mnop"},
113 base: "GET&http%3A%2F%2Fexample.com%2FSpace%2520Craft&name%3Dvalue%26name%3Dvalue%26oauth_consumer_key%3Dabcd%26oauth_nonce%3DIx4U1Ei3RFL%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1327384901%26oauth_token%3Dijkl%26oauth_version%3D1.0",
114 header: `OAuth oauth_consumer_key="abcd", oauth_nonce="Ix4U1Ei3RFL", oauth_signature="TZZ5u7qQorLnmKs%2Biqunb8gqkh4%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1327384901", oauth_token="ijkl", oauth_version="1.0"`,
115 },
116 {
117 // Query string in URL.
118 method: "GET",
119 url: parseURL("http://EXAMPLE.COM:80/Space%20Craft?name=value"),
120 form: url.Values{"name": {"value"}},
121 nonce: "Ix4U1Ei3RFL",
122 timestamp: "1327384901",
123 clientCredentials: Credentials{"abcd", "efgh"},
124 credentials: Credentials{"ijkl", "mnop"},
125 base: "GET&http%3A%2F%2Fexample.com%2FSpace%2520Craft&name%3Dvalue%26name%3Dvalue%26oauth_consumer_key%3Dabcd%26oauth_nonce%3DIx4U1Ei3RFL%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1327384901%26oauth_token%3Dijkl%26oauth_version%3D1.0",
126 header: `OAuth oauth_consumer_key="abcd", oauth_nonce="Ix4U1Ei3RFL", oauth_signature="TZZ5u7qQorLnmKs%2Biqunb8gqkh4%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1327384901", oauth_token="ijkl", oauth_version="1.0"`,
127 },
128 {
129 // "/" in form value.
130 method: "POST",
131 url: parseURL("https://stream.twitter.com/1.1/statuses/filter.json"),
132 form: url.Values{"track": {"example.com/abcd"}},
133 nonce: "bf2cb6d611e59f99103238fc9a3bb8d8",
134 timestamp: "1362434376",
135 clientCredentials: Credentials{"consumer_key", "consumer_secret"},
136 credentials: Credentials{"token", "secret"},
137 base: "POST&https%3A%2F%2Fstream.twitter.com%2F1.1%2Fstatuses%2Ffilter.json&oauth_consumer_key%3Dconsumer_key%26oauth_nonce%3Dbf2cb6d611e59f99103238fc9a3bb8d8%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1362434376%26oauth_token%3Dtoken%26oauth_version%3D1.0%26track%3Dexample.com%252Fabcd",
138 header: `OAuth oauth_consumer_key="consumer_key", oauth_nonce="bf2cb6d611e59f99103238fc9a3bb8d8", oauth_signature="LcxylEOnNdgoKSJi7jX07mxcvfM%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1362434376", oauth_token="token", oauth_version="1.0"`,
139 },
140 {
141 // "/" in query string
142 method: "POST",
143 url: parseURL("https://stream.twitter.com/1.1/statuses/filter.json?track=example.com/query"),
144 form: url.Values{},
145 nonce: "884275759fbab914654b50ae643c563a",
146 timestamp: "1362435218",
147 clientCredentials: Credentials{"consumer_key", "consumer_secret"},
148 credentials: Credentials{"token", "secret"},
149 base: "POST&https%3A%2F%2Fstream.twitter.com%2F1.1%2Fstatuses%2Ffilter.json&oauth_consumer_key%3Dconsumer_key%26oauth_nonce%3D884275759fbab914654b50ae643c563a%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1362435218%26oauth_token%3Dtoken%26oauth_version%3D1.0%26track%3Dexample.com%252Fquery",
150 header: `OAuth oauth_consumer_key="consumer_key", oauth_nonce="884275759fbab914654b50ae643c563a", oauth_signature="OAldqvRrKDXRGZ9BqSi2CqeVH0g%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1362435218", oauth_token="token", oauth_version="1.0"`,
151 },
152 {
153 // QuickBooks query string
154 method: "GET",
155 url: parseURL("https://qb.sbfinance.intuit.com/v3/company/1273852765/query"),
156 form: url.Values{"query": {"select * from account"}},
157 nonce: "12345678",
158 timestamp: "1409876517",
159 clientCredentials: Credentials{"consumer_key", "consumer_secret"},
160 credentials: Credentials{"token", "secret"},
161 base: "GET&https%3A%2F%2Fqb.sbfinance.intuit.com%2Fv3%2Fcompany%2F1273852765%2Fquery&oauth_consumer_key%3Dconsumer_key%26oauth_nonce%3D12345678%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1409876517%26oauth_token%3Dtoken%26oauth_version%3D1.0%26query%3Dselect%2520%252A%2520from%2520account",
162 header: `OAuth oauth_consumer_key="consumer_key", oauth_nonce="12345678", oauth_signature="7crYee%2BJLvg7dksQiHbarUHN3rY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1409876517", oauth_token="token", oauth_version="1.0"`,
163 },
164 {
165 // Plain text signature method
166 signatureMethod: PLAINTEXT,
167 method: "GET",
168 url: parseURL("http://example.com/"),
169 clientCredentials: Credentials{"key", "secret"},
170 credentials: Credentials{"accesskey", "accesssecret"},
171 header: `OAuth oauth_consumer_key="key", oauth_signature="secret%26accesssecret", oauth_signature_method="PLAINTEXT", oauth_token="accesskey", oauth_version="1.0"`,
172 },
173 {
174 // RSA-SHA1 signature method
175 signatureMethod: RSASHA1,
176 method: "GET",
177 url: parseURL("http://term.ie/oauth/example/echo_api.php"),
178 form: url.Values{"method": {"foo%20bar"}, "bar": {"baz"}},
179 nonce: "a7da4d14579d61886be9d596d1a6a720",
180 timestamp: "1420240290",
181 clientCredentials: Credentials{Token: "key"},
182 credentials: Credentials{Token: "accesskey"},
183 base: `GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Fecho_api.php&bar%3Dbaz%26method%3Dfoo%252520bar%26oauth_consumer_key%3Dkey%26oauth_nonce%3Da7da4d14579d61886be9d596d1a6a720%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1420240290%26oauth_token%3Daccesskey%26oauth_version%3D1.0`,
184 header: `OAuth oauth_consumer_key="key", oauth_nonce="a7da4d14579d61886be9d596d1a6a720", oauth_signature="jPun728OkfFo7BjZiaQ5UBVChwk6tf0uKNFDmNKVb%2Bd6aWYEzsDVkqqjcgTrCRNabK8ubAnhyprafk0mk3zEJe%2BxGb9GKauqwUJ6ZZoGJNYYZg3BZUQvdxSKFs1M4MUMv3fxntmD%2BoyE8jPbrVM2zD1G1AAPm79sX%2B8XE25tBE8%3D", oauth_signature_method="RSA-SHA1", oauth_timestamp="1420240290", oauth_token="accesskey", oauth_version="1.0"`,
185 },
186 }
187
188 func TestBaseString(t *testing.T) {
189 for _, ot := range oauthTests {
190 if ot.signatureMethod == PLAINTEXT {
191 // PLAINTEXT signature does not use the base string.
192 continue
193 }
194 oauthParams := map[string]string{
195 "oauth_consumer_key": ot.clientCredentials.Token,
196 "oauth_nonce": ot.nonce,
197 "oauth_signature_method": ot.signatureMethod.String(),
198 "oauth_timestamp": ot.timestamp,
199 "oauth_token": ot.credentials.Token,
200 "oauth_version": "1.0",
201 }
202 var buf bytes.Buffer
203 writeBaseString(&buf, ot.method, ot.url, ot.form, oauthParams)
204 base := buf.String()
205 if base != ot.base {
206 t.Errorf("base string for %s %s\n = %q,\n want %q", ot.method, ot.url, base, ot.base)
207 }
208 }
209 }
210
211 var pemPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
212 MIICXAIBAAKBgQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3
213 gYytUvtC2JlYzypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp
214 /IpH7kH41EtbmUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQAB
215 AoGAWFlbZXlM2r5G6z48tE+RTKLvB1/btgAtq8vLw/5e3KnnbcDD6fZO07m4DRaP
216 jRryrJdsp8qazmUdcY0O1oK4FQfpprknDjP+R1XHhbhkQ4WEwjmxPstZMUZaDWF5
217 8d3otc23mCzwh3YcUWFu09KnMpzZsK59OfyjtkS44EDWpbECQQDXgN0ODboKsuEA
218 VAhAtPUqspU9ivRa6yLai9kCnPb9GcztrsJZQm4NHcKVbmD2F2L4pDRx4Pmglhfl
219 V7G/a6T7AkEA1kfU0+DkXc6I/jXHJ6pDLA5s7dBHzWgDsBzplSdkVQbKT3MbeYje
220 ByOxzXhulOWLBQW/vxmW4HwU95KTRlj06QJASPoBYY3yb0cN/J94P/lHgJMDCNky
221 UEuJ/PoYndLrrN/8zow8kh91xwlJ6HJ9cTiQMmTgwaOOxPuu0eI1df4M2wJBAJJS
222 WrKUT1z/O+zbLDOZwGTFNPzvzRgmft4z4A1J6OlmyZ+XKpvDKloVtcRpCJoEZPn5
223 AwaroquID4k/PfI7rIECQHeWa6+kPADv9IrK/92mujujS0MSEiynDw5NjTnHAH0v
224 8TrXzs+LCWDN/gbOCKPfnWRkgwgOeC8NN3h0zUIIUtA=
225 -----END RSA PRIVATE KEY-----
226 `
227
228 func TestAuthorizationHeader(t *testing.T) {
229 originalTestHook := testHook
230 defer func() {
231 testHook = originalTestHook
232 }()
233
234 block, _ := pem.Decode([]byte(pemPrivateKey))
235 privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
236 if err != nil {
237 t.Fatal(err)
238 }
239
240 for _, ot := range oauthTests {
241 testHook = func(p map[string]string) {
242 if _, ok := p["oauth_nonce"]; ok {
243 p["oauth_nonce"] = ot.nonce
244 }
245 if _, ok := p["oauth_timestamp"]; ok {
246 p["oauth_timestamp"] = ot.timestamp
247 }
248 }
249 c := Client{Credentials: ot.clientCredentials, SignatureMethod: ot.signatureMethod, PrivateKey: privateKey}
250 header, err := c.authorizationHeader(&request{credentials: &ot.credentials, method: ot.method, u: ot.url, form: ot.form})
251 if err != nil {
252 t.Errorf("authorizationHeader(&cred, %q, %q, %v) returned error %v", ot.method, ot.url.String(), ot.form, err)
253 continue
254 }
255 if header != ot.header {
256 t.Errorf("authorizationHeader(&cred, %q, %q, %v) =\n %s\nwant: %s", ot.method, ot.url.String(), ot.form, header, ot.header)
257 }
258 }
259 }
260
261 func TestNonce(t *testing.T) {
262 // This test is flaky, but failures should be very rare.
263 n := nonce()
264 if len(n) < 8 {
265 t.Fatalf("nonce is %s, exected something longer", n)
266 }
267 }
268
269 func TestRequestToken(t *testing.T) {
270 var method string
271 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
272 expectedMethod := method
273 if method == "" {
274 expectedMethod = http.MethodPost
275 }
276 if r.Method != expectedMethod {
277 t.Errorf("got method %s, want %s", r.Method, expectedMethod)
278 }
279 expectedContenType := ""
280 if r.Method != http.MethodGet {
281 expectedContenType = "application/x-www-form-urlencoded"
282 }
283 if contentType := r.Header.Get("Content-Type"); contentType != expectedContenType {
284 t.Errorf("got content type %q, want %q", contentType, expectedContenType)
285 }
286 if auth := r.Header.Get("Authorization"); !strings.Contains(auth, `oauth_verifier="verifier"`) {
287 t.Errorf("verifier missing from auth header %q", auth)
288 }
289 v := url.Values{}
290 v.Set("oauth_token", "token")
291 v.Set("oauth_token_secret", "secret")
292 io.WriteString(w, v.Encode())
293 }))
294 defer ts.Close()
295
296 for _, method = range []string{"", "GET", "POST"} {
297 c := Client{TokenRequestURI: ts.URL, TokenCredentailsMethod: method}
298 cred, _, err := c.RequestToken(http.DefaultClient, &Credentials{}, "verifier")
299 if err != nil {
300 t.Errorf("returned error %v", err)
301 }
302 if cred.Token != "token" {
303 t.Errorf("token for %s want %s", cred.Token, "token")
304 }
305 if cred.Secret != "secret" {
306 t.Errorf("secret for %s want %s", cred.Secret, "secret")
307 }
308 }
309 }
310
311 func TestRenewRequestCredentials(t *testing.T) {
312 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
313 a := r.Header.Get("Authorization")
314 if !strings.Contains(a, `oauth_token="token"`) {
315 t.Errorf("Authorization header %q should contains %q", a, `oauth_token="token"`)
316 }
317 if !strings.Contains(a, `oauth_session_handle="session-handle"`) {
318 t.Errorf("Authorization header %q should contains %q", a, `oauth_session_handle="session-handle"`)
319 }
320 v := url.Values{}
321 v.Set("oauth_token", "response-token")
322 v.Set("oauth_token_secret", "response-token-secret")
323 v.Set("oauth_session_handle", "response-session-handle")
324 io.WriteString(w, v.Encode())
325 }))
326 defer ts.Close()
327
328 c := Client{RenewCredentialRequestURI: ts.URL}
329 cred, rv, err := c.RenewRequestCredentials(http.DefaultClient, &Credentials{Token: "token"}, "session-handle")
330 if err != nil {
331 t.Errorf("returned error %v", err)
332 }
333 if cred.Token != "response-token" {
334 t.Errorf("token for %s want %s", cred.Token, "response-token")
335 }
336 if cred.Secret != "response-token-secret" {
337 t.Errorf("secret for %s want %s", cred.Secret, "response-token-secret")
338 }
339 if rv.Get("oauth_session_handle") != "response-session-handle" {
340 t.Errorf("session handle for %s want %s", rv.Get("oauth_session_handle"), "response-session-handle")
341 }
342 }
343
344 func TestGet(t *testing.T) {
345 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
346 if r.Method != http.MethodGet {
347 t.Errorf("got method %s, want %s", r.Method, http.MethodGet)
348 }
349 if err := r.ParseForm(); err != nil {
350 t.Errorf("returned error %v", err)
351 }
352 if form := r.Form.Get("form"); form != "foo" {
353 t.Errorf("form %s, want %s", form, "foo")
354 }
355 cookie, err := r.Cookie("client-cookie")
356 if err != nil {
357 t.Errorf("returned error %v", err)
358 }
359 if cookie.Value != "foobar" {
360 t.Errorf("client-cookie %s, want %s", cookie.Value, "foobar")
361 }
362 io.WriteString(w, "bar")
363 }))
364 defer ts.Close()
365
366 u, err := url.Parse(ts.URL)
367 if err != nil {
368 t.Errorf("returned error %v", err)
369 }
370 jar, err := cookiejar.New(nil)
371 if err != nil {
372 t.Errorf("returned error %v", err)
373 }
374 jar.SetCookies(u, []*http.Cookie{&http.Cookie{Name: "client-cookie", Value: "foobar"}})
375 v := url.Values{}
376 v.Set("form", "foo")
377 c := Client{}
378 resp, err := c.Get(&http.Client{Jar: jar}, &Credentials{}, u.String(), v)
379 if err != nil {
380 t.Errorf("returned error %v", err)
381 }
382 defer resp.Body.Close()
383 b, err := ioutil.ReadAll(resp.Body)
384 if err != nil {
385 t.Errorf("returned error %v", err)
386 }
387 if string(b) != "bar" {
388 t.Errorf("body %s, want %s", string(b), "bar")
389 }
390 }
391
392 func TestGet_ClientNil(t *testing.T) {
393 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
394 if r.Method != http.MethodGet {
395 t.Errorf("got method %s, want %s", r.Method, http.MethodGet)
396 }
397 io.WriteString(w, "bar")
398 }))
399 defer ts.Close()
400
401 c := Client{}
402 resp, err := c.Get(nil, &Credentials{}, ts.URL, nil)
403 if err != nil {
404 t.Errorf("returned error %v", err)
405 }
406 defer resp.Body.Close()
407 b, err := ioutil.ReadAll(resp.Body)
408 if err != nil {
409 t.Errorf("returned error %v", err)
410 }
411 if string(b) != "bar" {
412 t.Errorf("body %s, want %s", string(b), "bar")
413 }
414 }
415
416 func TestGetContext(t *testing.T) {
417 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
418 if r.Method != http.MethodGet {
419 t.Errorf("got method %s, want %s", r.Method, http.MethodGet)
420 }
421 cookie, err := r.Cookie("client-cookie")
422 if err != nil {
423 t.Errorf("returned error %v", err)
424 }
425 if cookie.Value != "foobar" {
426 t.Errorf("client-cookie %s, want %s", cookie.Value, "foobar")
427 }
428 io.WriteString(w, "bar")
429 }))
430 defer ts.Close()
431
432 u, err := url.Parse(ts.URL)
433 if err != nil {
434 t.Errorf("returned error %v", err)
435 }
436 jar, err := cookiejar.New(nil)
437 if err != nil {
438 t.Errorf("returned error %v", err)
439 }
440 jar.SetCookies(u, []*http.Cookie{&http.Cookie{Name: "client-cookie", Value: "foobar"}})
441 ctx := context.WithValue(context.Background(), HTTPClient, &http.Client{Jar: jar})
442 c := Client{}
443 resp, err := c.GetContext(ctx, &Credentials{}, u.String(), nil)
444 if err != nil {
445 t.Errorf("returned error %v", err)
446 }
447 defer resp.Body.Close()
448 b, err := ioutil.ReadAll(resp.Body)
449 if err != nil {
450 t.Errorf("returned error %v", err)
451 }
452 if string(b) != "bar" {
453 t.Errorf("body %s, want %s", string(b), "bar")
454 }
455 }
456
457 func TestRequestCredentialsError(t *testing.T) {
458 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
459 w.Header().Set("WWW-Authenticate", "oauth_problem=token_rejected")
460 w.WriteHeader(http.StatusUnauthorized)
461 io.WriteString(w, "oauth_problem=token_rejected")
462 }))
463 defer ts.Close()
464
465 c := Client{TokenRequestURI: ts.URL}
466 _, _, err := c.RequestToken(http.DefaultClient, &Credentials{}, "verifier")
467 if err == nil {
468 t.Error("error should not be nil")
469 }
470 if rce, ok := err.(RequestCredentialsError); ok {
471 if rce.StatusCode != http.StatusUnauthorized {
472 t.Errorf("status code %d, want %d", rce.StatusCode, http.StatusUnauthorized)
473 }
474 wa := rce.Header.Get("WWW-Authenticate")
475 if wa != "oauth_problem=token_rejected" {
476 t.Errorf("WWW-Authenticate header %s, want %s", wa, "oauth_problem=token_rejected")
477 }
478 if string(rce.Body) != "oauth_problem=token_rejected" {
479 t.Errorf("body %s,want %s", rce.Body, "oauth_problem=token_rejected")
480 }
481 } else {
482 t.Error("error should be assertable RequestCredentialsError")
483 }
484 }
485
486 func TestGetContext_Cancel(t *testing.T) {
487 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
488 }))
489 defer ts.Close()
490
491 ctx, cancel := context.WithCancel(context.Background())
492 cancel()
493 c := Client{}
494 _, err := c.GetContext(ctx, &Credentials{}, ts.URL, nil)
495 if err == nil {
496 t.Error("error should not be nil")
497 }
498 }