diff options
Diffstat (limited to 'http/http_test.go')
-rw-r--r-- | http/http_test.go | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/http/http_test.go b/http/http_test.go new file mode 100644 index 0000000..603dce3 --- /dev/null +++ b/http/http_test.go @@ -0,0 +1,54 @@ +package http_test + +import ( + "context" + httpServer "go.sudomsg.com/kit/http" + "io" + "net/http" + "strings" + "testing" + "time" +) + +func TestRunHTTPServers(t *testing.T) { + t.Parallel() + t.Run("basic serve and shutdown", func(t *testing.T) { + t.Parallel() + ctx := t.Context() + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "hello") + }) + + ln := newListener(t) + addr := ln.Addr().String() + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + go func() { + // Wait for server to be ready + time.Sleep(200 * time.Millisecond) + + r, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+addr, nil) + resp, err := http.DefaultClient.Do(r) + if err != nil { + t.Errorf("http.Do error: %v", err) + return + } + defer resp.Body.Close() + + body, _ := io.ReadAll(resp.Body) + if got := strings.TrimSpace(string(body)); got != "hello" { + t.Errorf("unexpected response body: %q", got) + } + + cancel() // shutdown the server + }() + + err := httpServer.RunHTTPServers(ctx, httpServer.Listeners{ln}, handler) + if err != nil { + t.Fatalf("RunHTTPServers failed: %v", err) + } + }) +} + |