-
Notifications
You must be signed in to change notification settings - Fork 10
/
http_test.go
87 lines (72 loc) · 2.32 KB
/
http_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package imgur
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/url"
"path"
)
func testHTTPClientJSON(json string) (*http.Client, *httptest.Server) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-RateLimit-UserLimit", "10")
w.Header().Set("X-RateLimit-UserRemaining", "2")
w.Header().Set("X-RateLimit-UserReset", "3")
w.Header().Set("X-RateLimit-ClientLimit", "40")
w.Header().Set("X-RateLimit-ClientRemaining", "5")
w.WriteHeader(200)
fmt.Fprintln(w, json)
}))
u, err := url.Parse(server.URL)
if err != nil {
log.Fatalln("failed to parse httptest.Server URL:", err)
}
http.DefaultClient.Transport = rewriteTransport{URL: u}
return http.DefaultClient, server
}
func testHTTPClient500() (*http.Client, *httptest.Server) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
u, err := url.Parse(server.URL)
if err != nil {
log.Fatalln("failed to parse httptest.Server URL:", err)
}
http.DefaultClient.Transport = rewriteTransport{URL: u}
return http.DefaultClient, server
}
func testHTTPClientInvalidJSON() (*http.Client, *httptest.Server) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// some broken headers
w.Header().Set("X-RateLimit-UserLimit", "asd123")
w.Header().Set("X-RateLimit-UserRemaining", "asd123")
w.Header().Set("X-RateLimit-UserReset", "asd123")
w.Header().Set("X-RateLimit-ClientLimit", "asd123")
w.Header().Set("X-RateLimit-ClientRemaining", "asd123")
w.WriteHeader(200)
// some invalid json
fmt.Fprintln(w, `[broken json.. :)]`)
}))
u, err := url.Parse(server.URL)
if err != nil {
log.Fatalln("failed to parse httptest.Server URL:", err)
}
http.DefaultClient.Transport = rewriteTransport{URL: u}
return http.DefaultClient, server
}
type rewriteTransport struct {
Transport http.RoundTripper
URL *url.URL
}
func (t rewriteTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.URL.Scheme = t.URL.Scheme
r.URL.Host = t.URL.Host
r.URL.Path = path.Join(t.URL.Path, r.URL.Path)
rt := t.Transport
if rt == nil {
rt = http.DefaultTransport
}
return rt.RoundTrip(r)
}