-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathhttpserver_test.go
103 lines (83 loc) · 2.11 KB
/
httpserver_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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package httpserver
import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"testing"
"golang.org/x/sync/errgroup"
"gotest.tools/v3/assert"
"gotest.tools/v3/assert/cmp"
"github.com/circleci/ex/testing/testcontext"
)
func TestNew(t *testing.T) {
ctx, cancel := context.WithCancel(testcontext.Background())
defer cancel()
r := http.NewServeMux()
r.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "hello world!")
})
srv, err := New(ctx, Config{
Name: "test server",
Addr: "localhost:0",
Handler: r,
})
assert.Assert(t, err)
g, ctx := errgroup.WithContext(ctx)
t.Cleanup(func() {
assert.Check(t, g.Wait())
})
g.Go(func() error {
return srv.Serve(ctx)
})
body, status := get(t, http.DefaultClient, srv.Addr(), "test")
assert.Check(t, cmp.Equal(status, http.StatusOK))
assert.Check(t, cmp.Equal(body, "hello world!"))
}
func TestNew_unix(t *testing.T) {
ctx, cancel := context.WithCancel(testcontext.Background())
defer cancel()
r := http.NewServeMux()
r.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "hello world!")
})
socket := filepath.Join(os.TempDir(), "httpserver-test.sock")
srv, err := New(ctx, Config{
Name: "test server",
Addr: socket,
Handler: r,
Network: "unix",
})
assert.Assert(t, err)
g, ctx := errgroup.WithContext(ctx)
t.Cleanup(func() {
assert.Check(t, g.Wait())
})
g.Go(func() error {
return srv.Serve(ctx)
})
c := &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", socket)
},
},
}
body, status := get(t, c, "localhost", "test")
assert.Check(t, cmp.Equal(status, http.StatusOK))
assert.Check(t, cmp.Equal(body, "hello world!"))
}
func get(t *testing.T, c *http.Client, baseurl, path string) (string, int) {
t.Helper()
r, err := c.Get(fmt.Sprintf("http://%s/%s", baseurl, path))
assert.Assert(t, err)
defer func() {
assert.Assert(t, r.Body.Close())
}()
b, err := io.ReadAll(r.Body)
assert.Assert(t, err)
return string(b), r.StatusCode
}