Debian Codegraph @

testutil/http.go

raw symbols SCIP
1 package testutil
2
3 import (
4 "bytes"
5 "fmt"
6 "io/ioutil"
7 "net"
8 "net/http"
9 "net/url"
10 "os"
11 "time"
12 )
13
14 type HTTPServer struct {
15 URL string
16 Timeout time.Duration
17 started bool
18 request chan *http.Request
19 response chan ResponseFunc
20 }
21
22 type Response struct {
23 Status int
24 Headers map[string]string
25 Body string
26 }
27
28 var DefaultClient = &http.Client{
29 Transport: &http.Transport{
30 Proxy: http.ProxyFromEnvironment,
31 },
32 }
33
34 func NewHTTPServer() *HTTPServer {
35 return &HTTPServer{URL: "http://localhost:4444", Timeout: 5 * time.Second}
36 }
37
38 type ResponseFunc func(path string) Response
39
40 func (s *HTTPServer) Start() {
41 if s.started {
42 return
43 }
44 s.started = true
45 s.request = make(chan *http.Request, 1024)
46 s.response = make(chan ResponseFunc, 1024)
47 u, err := url.Parse(s.URL)
48 if err != nil {
49 panic(err)
50 }
51 l, err := net.Listen("tcp", u.Host)
52 if err != nil {
53 panic(err)
54 }
55 go http.Serve(l, s)
56
57 s.Response(203, nil, "")
58 for {
59 // Wait for it to be up.
60 resp, err := http.Get(s.URL)
61 if err == nil && resp.StatusCode == 203 {
62 break
63 }
64 time.Sleep(1e8)
65 }
66 s.WaitRequest() // Consume dummy request.
67 }
68
69 // Flush discards all pending requests and responses.
70 func (s *HTTPServer) Flush() {
71 for {
72 select {
73 case <-s.request:
74 case <-s.response:
75 default:
76 return
77 }
78 }
79 }
80
81 func body(req *http.Request) string {
82 data, err := ioutil.ReadAll(req.Body)
83 if err != nil {
84 panic(err)
85 }
86 return string(data)
87 }
88
89 func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
90 req.ParseMultipartForm(1e6)
91 data, err := ioutil.ReadAll(req.Body)
92 if err != nil {
93 panic(err)
94 }
95 req.Body = ioutil.NopCloser(bytes.NewBuffer(data))
96 s.request <- req
97 var resp Response
98 select {
99 case respFunc := <-s.response:
100 resp = respFunc(req.URL.Path)
101 case <-time.After(s.Timeout):
102 const msg = "ERROR: Timeout waiting for test to prepare a response\n"
103 fmt.Fprintf(os.Stderr, msg)
104 resp = Response{500, nil, msg}
105 }
106 if resp.Headers != nil {
107 h := w.Header()
108 for k, v := range resp.Headers {
109 h.Set(k, v)
110 }
111 }
112 if resp.Status != 0 {
113 w.WriteHeader(resp.Status)
114 }
115 w.Write([]byte(resp.Body))
116 }
117
118 // WaitRequests returns the next n requests made to the http server from
119 // the queue. If not enough requests were previously made, it waits until
120 // the timeout value for them to be made.
121 func (s *HTTPServer) WaitRequests(n int) []*http.Request {
122 reqs := make([]*http.Request, 0, n)
123 for i := 0; i < n; i++ {
124 select {
125 case req := <-s.request:
126 reqs = append(reqs, req)
127 case <-time.After(s.Timeout):
128 panic("Timeout waiting for request")
129 }
130 }
131 return reqs
132 }
133
134 // WaitRequest returns the next request made to the http server from
135 // the queue. If no requests were previously made, it waits until the
136 // timeout value for one to be made.
137 func (s *HTTPServer) WaitRequest() *http.Request {
138 return s.WaitRequests(1)[0]
139 }
140
141 // ResponseFunc prepares the test server to respond the following n
142 // requests using f to build each response.
143 func (s *HTTPServer) ResponseFunc(n int, f ResponseFunc) {
144 for i := 0; i < n; i++ {
145 s.response <- f
146 }
147 }
148
149 // ResponseMap maps request paths to responses.
150 type ResponseMap map[string]Response
151
152 // ResponseMap prepares the test server to respond the following n
153 // requests using the m to obtain the responses.
154 func (s *HTTPServer) ResponseMap(n int, m ResponseMap) {
155 f := func(path string) Response {
156 for rpath, resp := range m {
157 if rpath == path {
158 return resp
159 }
160 }
161 body := "Path not found in response map: " + path
162 return Response{Status: 500, Body: body}
163 }
164 s.ResponseFunc(n, f)
165 }
166
167 // Responses prepares the test server to respond the following n requests
168 // using the provided response parameters.
169 func (s *HTTPServer) Responses(n int, status int, headers map[string]string, body string) {
170 f := func(path string) Response {
171 return Response{status, headers, body}
172 }
173 s.ResponseFunc(n, f)
174 }
175
176 // Response prepares the test server to respond the following request
177 // using the provided response parameters.
178 func (s *HTTPServer) Response(status int, headers map[string]string, body string) {
179 s.Responses(1, status, headers, body)
180 }