-
Notifications
You must be signed in to change notification settings - Fork 0
/
heartbeat_test.go
108 lines (88 loc) · 2.38 KB
/
heartbeat_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
103
104
105
106
107
108
package heartbeat_test
import (
"context"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"github.com/gorilla/mux"
heartbeat "github.com/rcrowe/opsgenie-heartbeat"
"github.com/sethgrid/pester"
)
func TestKeySet(t *testing.T) {
expected := "some random key"
hb := heartbeat.New(expected)
if hb.APIKey != expected {
t.Fail()
}
}
func TestKeyHeader(t *testing.T) {
expected := "5e0cf9c8-4665-4b7b-b829-6044b9323d98"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "GenieKey "+expected {
t.Fail()
}
}))
defer srv.Close()
hb := heartbeat.New(expected)
hb.Endpoint = srv.URL
hb.Ping(context.Background(), "foo")
}
func TestCorrectEndpoint(t *testing.T) {
expected := "the-heartbeat-name"
m := mux.NewRouter()
m.HandleFunc("/v2/heartbeats/{name}/ping", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if vars["name"] != expected {
t.Fail()
}
}).Methods("GET")
srv := httptest.NewServer(m)
defer srv.Close()
hb := heartbeat.New("")
hb.Endpoint = srv.URL
hb.Ping(context.Background(), expected)
}
func TestCombatsFlakyConnection(t *testing.T) {
var calls uint32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddUint32(&calls, 1)
if c := atomic.LoadUint32(&calls); c < 3 {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
}))
defer srv.Close()
hb := heartbeat.New("")
hb.Endpoint = srv.URL
if err := hb.Ping(context.Background(), "some-heartbeat"); err != nil {
t.Fail()
}
}
func TestUnauthorised(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()
hb := heartbeat.New("")
hb.Endpoint = srv.URL
if err := hb.Ping(context.Background(), "foo"); err != heartbeat.ErrUnauthorised {
t.Fail()
}
}
func TestBadResponse(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}))
defer srv.Close()
hb := heartbeat.New("")
hb.Endpoint = srv.URL
client := pester.New()
client.Concurrency = 1
client.MaxRetries = 1
hb.Client = client
if err := hb.Ping(context.Background(), "foo"); err != heartbeat.ErrNonOkStatusCode {
t.Fail()
}
}