-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
47 lines (42 loc) · 972 Bytes
/
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
package main
import (
"context"
"fmt"
"io"
"net"
"net/http"
"testing"
"golang.org/x/sync/errgroup"
)
func TestServer_Run(t *testing.T) {
l, err := net.Listen("tcp", "localhost:0")
ctx, cancel := context.WithCancel(context.Background())
eg, ctx := errgroup.WithContext(ctx)
mux := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
})
eg.Go(func() error {
s := NewServer(l, mux)
return s.Run(ctx)
})
in := "message"
url := fmt.Sprintf("http://%s/%s", l.Addr().String(), in)
t.Logf("try request to %q", url)
rsp, err := http.Get(url)
if err != nil {
t.Errorf("failed to get: %+v", err)
}
defer rsp.Body.Close()
got, err := io.ReadAll(rsp.Body)
if err != nil {
t.Fatalf("failed to read body: %+v", err)
}
want := fmt.Sprintf("Hello, %s!", in)
if string(got) != want {
t.Errorf("want %q but %q", want, got)
}
cancel()
if err := eg.Wait(); err != nil {
t.Fatal(err)
}
}