forked from cloudfoundry-attic/gunk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_server.go
104 lines (85 loc) · 2.14 KB
/
test_server.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package test_server
import (
"fmt"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega/format"
"io/ioutil"
"net/http"
"net/http/httptest"
"sync"
)
func new() *Server {
return &Server{
AllowUnhandledRequests: false,
UnhandledRequestStatusCode: http.StatusInternalServerError,
writeLock: &sync.Mutex{},
}
}
func New() *Server {
s := new()
s.HTTPTestServer = httptest.NewServer(s)
return s
}
func NewTLS() *Server {
s := new()
s.HTTPTestServer = httptest.NewTLSServer(s)
return s
}
type Server struct {
HTTPTestServer *httptest.Server
receivedRequests []*http.Request
requestHandlers []http.HandlerFunc
AllowUnhandledRequests bool
UnhandledRequestStatusCode int
writeLock *sync.Mutex
calls int
}
func (s *Server) URL() string {
return s.HTTPTestServer.URL
}
func (s *Server) Close() {
server := s.HTTPTestServer
s.HTTPTestServer = nil
server.Close()
}
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.writeLock.Lock()
defer s.writeLock.Unlock()
if s.calls < len(s.requestHandlers) {
s.requestHandlers[s.calls](w, req)
} else {
if s.AllowUnhandledRequests {
ioutil.ReadAll(req.Body)
req.Body.Close()
w.WriteHeader(s.UnhandledRequestStatusCode)
} else {
ginkgo.Fail(fmt.Sprintf("Received unhandled request:\n%s", format.Object(req, 1)))
}
}
s.receivedRequests = append(s.receivedRequests, req)
s.calls++
}
func (s *Server) ReceivedRequestsCount() int {
s.writeLock.Lock()
defer s.writeLock.Unlock()
return len(s.receivedRequests)
}
func (s *Server) Append(handlers ...http.HandlerFunc) {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.requestHandlers = append(s.requestHandlers, handlers...)
}
func (s *Server) Set(index int, handler http.HandlerFunc) {
s.writeLock.Lock()
defer s.writeLock.Unlock()
s.requestHandlers[index] = handler
}
func (s *Server) Get(index int) http.HandlerFunc {
s.writeLock.Lock()
defer s.writeLock.Unlock()
return s.requestHandlers[index]
}
func (s *Server) Wrap(index int, handler http.HandlerFunc) {
existingHandler := s.Get(index)
s.Set(index, CombineHandlers(existingHandler, handler))
}