-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
102 lines (88 loc) · 2.42 KB
/
main_test.go
File metadata and controls
102 lines (88 loc) · 2.42 KB
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
package main
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog"
)
func TestHelloHandler(t *testing.T) {
tests := []struct {
name string
method string
headers map[string]string
wantStatus int
wantBody string
wantContains string
}{
{
name: "successful GET request",
method: http.MethodGet,
wantStatus: http.StatusOK,
wantBody: "Hello, World!\n",
},
{
name: "method not allowed",
method: http.MethodPost,
wantStatus: http.StatusMethodNotAllowed,
wantContains: "Method not allowed",
},
{
name: "forced failure",
method: http.MethodGet,
headers: map[string]string{"Fail": "true"},
wantStatus: http.StatusInternalServerError,
wantContains: "Internal server error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := prometheus.NewRegistry()
metrics := newMetrics(reg)
logger := zerolog.New(io.Discard)
srv := newServer(":8080", metrics, logger)
req := httptest.NewRequest(tt.method, "/hello", nil)
for k, v := range tt.headers {
req.Header.Set(k, v)
}
w := httptest.NewRecorder()
srv.helloHandler(w, req)
if w.Code != tt.wantStatus {
t.Errorf("handler returned wrong status code: got %v want %v", w.Code, tt.wantStatus)
}
if tt.wantBody != "" && w.Body.String() != tt.wantBody {
t.Errorf("handler returned wrong body: got %v want %v", w.Body.String(), tt.wantBody)
}
if tt.wantContains != "" && !strings.Contains(w.Body.String(), tt.wantContains) {
t.Errorf("handler body doesn't contain expected string: got %v want to contain %v", w.Body.String(), tt.wantContains)
}
})
}
}
func TestServerGracefulShutdown(t *testing.T) {
reg := prometheus.NewRegistry()
metrics := newMetrics(reg)
logger := zerolog.New(io.Discard)
srv := newServer(":0", metrics, logger)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
errCh := make(chan error)
go func() {
errCh <- srv.run(ctx)
}()
// Wait a bit for server to start
time.Sleep(100 * time.Millisecond)
cancel()
select {
case err := <-errCh:
if err != nil {
t.Errorf("server.run() returned unexpected error: %v", err)
}
case <-time.After(6 * time.Second):
t.Error("server didn't shut down within expected timeframe")
}
}