-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathserver.go
60 lines (44 loc) · 1.24 KB
/
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
package httpclienttest
import (
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
type TestHTTPRequestFunc func(tb testing.TB, req *http.Request) error
type TestHTTPResponseFunc func(tb testing.TB, w http.ResponseWriter) error
type TestHTTPRoundTrip struct {
RequestFunc TestHTTPRequestFunc
ResponseFunc TestHTTPResponseFunc
}
func NewTestHTTPServer(tb testing.TB, options ...TestHTTPServerOptionFunc) *httptest.Server {
tb.Helper()
var mu sync.Mutex
serverOptions := DefaultTestHTTPServerOptions()
for _, opt := range options {
opt(&serverOptions)
}
if len(serverOptions.RoundtripsStack) == 0 {
tb.Error("test HTTP server: empty roundtrips stack")
return nil
}
stackPosition := 0
return httptest.NewServer(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
if stackPosition >= len(serverOptions.RoundtripsStack) {
tb.Error("test HTTP server: roundtrips stack exhausted")
return
}
err := serverOptions.RoundtripsStack[stackPosition].RequestFunc(tb, r)
assert.NoError(tb, err)
err = serverOptions.RoundtripsStack[stackPosition].ResponseFunc(tb, w)
assert.NoError(tb, err)
stackPosition++
},
),
)
}