-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimeout_test.go
81 lines (62 loc) · 1.91 KB
/
timeout_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
package gohm_test
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/karrick/gohm"
)
func TestBeforeTimeout(t *testing.T) {
response := "{pi:3.14159265}"
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/some/url", nil)
handler := gohm.New(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(response))
}), gohm.Config{Timeout: time.Second})
handler.ServeHTTP(recorder, request)
resp := recorder.Result()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
if got, want := string(body), response; got != want {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
}
func TestAfterTimeout(t *testing.T) {
response := "{pi:3.14159265}"
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/some/url", nil)
handler := gohm.New(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second)
w.Write([]byte(response))
}), gohm.Config{Timeout: 5 * time.Millisecond})
handler.ServeHTTP(recorder, request)
resp := recorder.Result()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if got, want := resp.StatusCode, http.StatusServiceUnavailable; got != want {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
if got, want := string(body), "503 Service Unavailable"; !strings.Contains(got, want) {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
}
func BenchmarkWithTimeout(b *testing.B) {
handler := gohm.New(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// don't bother exceeding timeout
}), gohm.Config{Timeout: time.Second})
b.ResetTimer()
for i := 0; i < b.N; i++ {
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/some/url", nil)
handler.ServeHTTP(recorder, request)
}
}