forked from synapsecns/sanguine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
80 lines (67 loc) · 1.85 KB
/
server_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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package server_test
import (
"context"
"errors"
"fmt"
"github.com/phayes/freeport"
"github.com/synapsecns/sanguine/core/retry"
"github.com/synapsecns/sanguine/core/server"
"io"
"net/http"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestListenAndServe(t *testing.T) {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong")
})
s := &server.Server{}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
port, err := freeport.GetFreePort()
assert.NoError(t, err)
go func() {
err := s.ListenAndServe(ctx, fmt.Sprintf(":%d", port), r)
assert.NoError(t, err)
}()
url := fmt.Sprintf("http://localhost:%d/ping", port)
// Give some time for server to start
err = retry.WithBackoff(ctx, func(ctx context.Context) error {
// Make a request to test if server is running
// nolint: gosec, noctx
resp, err := http.Get(url)
if err != nil {
return errors.New("server has not yet started")
}
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
// Wait for the context to cancel
<-ctx.Done()
return nil
})
assert.NoError(t, err)
// Make a request to test if server is running
// nolint: gosec, noctx
resp, err := http.Get(url)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
assert.NoError(t, err)
assert.Equal(t, "pong", string(body))
// Wait for the context to cancel
<-ctx.Done()
// make sure cancellation triggers were processed and server is closed
//nolint: gosec, noctx
resp, err = http.Get("http://localhost:9090/ping")
assert.NotNil(t, err)
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
}