forked from thoas/stats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats_test.go
102 lines (71 loc) · 1.67 KB
/
stats_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
package stats
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var testHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("bar"))
})
func TestSimple(t *testing.T) {
s := New()
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
s.Handler(testHandler).ServeHTTP(res, req)
assert.Equal(t, res.Code, 200)
assert.Equal(t, s.ResponseCounts, map[string]int{"200": 1})
}
func TestGetStats(t *testing.T) {
s := New()
var stats = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
stats := s.Data()
b, _ := json.Marshal(stats)
w.Write(b)
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
s.Handler(testHandler).ServeHTTP(res, req)
res = httptest.NewRecorder()
s.Handler(stats).ServeHTTP(res, req)
assert.Equal(t, res.Header().Get("Content-Type"), "application/json")
var data map[string]interface{}
err := json.Unmarshal(res.Body.Bytes(), &data)
assert.Nil(t, err)
assert.Equal(t, data["total_count"].(float64), float64(1))
}
func TestRace(t *testing.T) {
s := New()
ch1 := make(chan bool)
ch2 := make(chan bool)
go func() {
now := time.Now()
for true {
select {
case _ = <-ch1:
return
default:
s.EndWithStatus(now, 200)
}
}
}()
go func() {
dt := s.Data()
for true {
select {
case _ = <-ch2:
return
default:
_ = dt.TotalStatusCodeCount["200"]
}
}
}()
time.Sleep(time.Second)
ch1 <- true
ch2 <- true
}