-
Notifications
You must be signed in to change notification settings - Fork 18
/
stat_handler_test.go
75 lines (58 loc) · 1.42 KB
/
stat_handler_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
package stats
import (
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"github.com/lyft/gostats/mock"
)
func TestHttpHandler_ServeHTTP(t *testing.T) {
t.Parallel()
sink := mock.NewSink()
store := NewStore(sink, false)
h := NewStatHandler(
store,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if code, err := strconv.Atoi(r.Header.Get("code")); err == nil {
w.WriteHeader(code)
}
io.Copy(w, r.Body)
r.Body.Close()
})).(*httpHandler)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
r, _ := http.NewRequest(http.MethodGet, "/", strings.NewReader("foo"))
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
store.Flush()
if w.Body.String() != "foo" {
t.Errorf("wanted %q body, got %q", "foo", w.Body.String())
}
if w.Code != http.StatusOK {
t.Errorf("wanted 200, got %d", w.Code)
}
wg.Done()
}()
go func() {
r := httptest.NewRequest(http.MethodGet, "/", strings.NewReader("bar"))
r.Header.Set("code", strconv.Itoa(http.StatusNotFound))
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
store.Flush()
if w.Body.String() != "bar" {
t.Errorf("wanted %q body, got %q", "bar", w.Body.String())
}
if w.Code != http.StatusNotFound {
t.Errorf("wanted 404, got %d", w.Code)
}
wg.Done()
}()
wg.Wait()
sink.AssertTimerCallCount(t, requestTimer, 2)
sink.AssertCounterEquals(t, "200", 1)
sink.AssertCounterEquals(t, "404", 1)
}