Debian Codegraph @

testutil/http.go

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