-
Notifications
You must be signed in to change notification settings - Fork 0
/
do_test.go
66 lines (56 loc) · 1.29 KB
/
do_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
package listeners
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDoListenerOnFirstAcceptDo(t *testing.T) {
require := require.New(t)
assert := assert.New(t)
const (
once = "once"
regular = "regular"
)
address := ":0"
addr, err := net.ResolveTCPAddr("tcp", address)
require.NoError(err)
l, err := net.ListenTCP("tcp", addr)
require.NoError(err)
firstc := make(chan string, 1)
fadl := NewDoListener(l).OnFirstAcceptDo(func() {
firstc <- once
})
handler := func(w http.ResponseWriter, r *http.Request) {
select {
case first := <-firstc:
fmt.Fprintf(w, first)
default:
fmt.Fprint(w, regular)
}
}
ts := &httptest.Server{
Listener: fadl,
Config: &http.Server{Handler: http.HandlerFunc(handler)},
}
ts.Start()
tc := ts.Client()
resp, err := tc.Get(ts.URL)
require.NoError(err)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(err)
resp.Body.Close()
assert.Equal(http.StatusOK, resp.StatusCode)
assert.EqualValues(once, body)
resp, err = tc.Get(ts.URL)
require.NoError(err)
body, err = ioutil.ReadAll(resp.Body)
require.NoError(err)
resp.Body.Close()
assert.Equal(http.StatusOK, resp.StatusCode)
assert.EqualValues(regular, body)
}