-
Notifications
You must be signed in to change notification settings - Fork 10
/
main_test.go
67 lines (56 loc) · 1.79 KB
/
main_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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/sensu/sensu-go/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSendAlert(t *testing.T) {
assert := assert.New(t)
event := types.FixtureEvent("entity1", "check1")
var apiStub = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
expectedBody := `{"resource":"entity1","event":"check1","environment":"Production","severity":"normal","status":"","service":["Sensu"],"group":"default","value":"","text":"","origin":"sensu-go/`
assert.Contains(string(body), expectedBody)
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(`{"status": "ok"}`))
require.NoError(t, err)
}))
config.AlertaEndpoint = apiStub.URL
config.AlertaAPIKey = "demo-key"
config.Environment = "Production"
err := sendAlert(event)
assert.NoError(err)
}
func TestMain(t *testing.T) {
assert := assert.New(t)
file, _ := ioutil.TempFile(os.TempDir(), "sensu-handler-alerta-")
defer func() {
_ = os.Remove(file.Name())
}()
event := types.FixtureEvent("entity1", "check1")
eventJSON, _ := json.Marshal(event)
_, err := file.WriteString(string(eventJSON))
require.NoError(t, err)
require.NoError(t, file.Sync())
_, err = file.Seek(0, 0)
require.NoError(t, err)
os.Stdin = file
requestReceived := false
var apiStub = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestReceived = true
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(`{"status": "ok"}`))
require.NoError(t, err)
}))
oldArgs := os.Args
os.Args = []string{"alerta", "--endpoint-url", apiStub.URL}
defer func() { os.Args = oldArgs }()
main()
assert.True(requestReceived)
}