-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.go
206 lines (172 loc) · 6.42 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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"testing"
"time"
splunk "github.com/AmadeusITGroup/keptn-splunk-sli-provider/pkg/splunksdk/client"
"github.com/AmadeusITGroup/keptn-splunk-sli-provider/pkg/utils"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/cloudevents/sdk-go/v2/event"
"github.com/kelseyhightower/envconfig"
keptnv1 "github.com/keptn/go-utils/pkg/lib"
keptnv2 "github.com/keptn/go-utils/pkg/lib/v0_2_0"
logger "github.com/sirupsen/logrus"
)
var testPortforMain = 38888
// Tests the parseKeptnCloudEventPayload function
func TestParseKeptnCloudEventPayload(t *testing.T) {
incomingEvent, err := extractEvent("test/events/get-sli.triggered.json")
if err != nil {
t.Fatalf("Error getting keptn event : %v", err)
}
eventData := &keptnv2.GetSLITriggeredEventData{}
err = parseKeptnCloudEventPayload(*incomingEvent, eventData)
//fails if eventData has not been modified
if err != nil || eventData.Project == "" {
t.Fatalf("Failed to parse keptn cloud event payload")
}
t.Logf("%v", eventData)
}
// Tests the processKeptnCloudEvent function by checking if it processes get-sli.triggered and configure monitoring events
func TestProcessKeptnCloudEvent(t *testing.T) {
t.Log("Initializing get sli triggered event")
var calledSLI *bool = new(bool)
var calledConfig *bool = new(bool)
*calledSLI = false
*calledConfig = false
handleConfigureMonitoringTriggeredEvent = func(ddKeptn *keptnv2.Keptn, incomingEvent event.Event, data *keptnv2.ConfigureMonitoringTriggeredEventData, env utils.EnvConfig, client *splunk.SplunkClient, pollingSystemHasBeenStarted bool) error {
*calledConfig = true
return nil
}
handleGetSliTriggeredEvent = func(ddKeptn *keptnv2.Keptn, incomingEvent event.Event, data *keptnv2.GetSLITriggeredEventData, client *splunk.SplunkClient) error {
*calledSLI = true
return nil
}
//Test for a get-sli.triggered event
checkProcessKeptnCloudEvent(t, "test/events/get-sli.triggered.json", calledSLI, calledConfig)
//Test for a monitoring.configure event
checkProcessKeptnCloudEvent(t, "test/events/monitoring.configure.json", calledSLI, calledConfig)
//Test for a random event
checkProcessKeptnCloudEvent(t, "test/events/release.triggered.json", calledSLI, calledConfig)
}
// Tests the _main function by ensuring that it listens to cloudevents and trigger the procKeptnCE function
func TestCloudEventListener(t *testing.T) {
if err := envconfig.Process("", &env); err != nil {
logger.Fatalf("Failed to process env var: %s", err)
}
env.Port = testPortforMain
env.Env = "test"
var handled bool
processKeptnCloudEvent = func(ctx context.Context, event cloudevents.Event) error {
handled = true
return nil
}
args := []string{}
go CloudEventListener(args)
//sleep for 2 seconds to let the previous go routine the time to start listening for events
time.Sleep(time.Duration(2) * time.Second)
err := sendTestCloudEvent("test/events/get-sli.triggered.json")
if err != nil {
logger.Fatalf("Couldn't send cloud event : %v", err)
}
if handled == false {
t.Fatal("The function didn't handle the event.")
}
}
// Tests the main function by verifying if the exit code corresponds to the one returned by cloudEventListener function
// func TestMain(t *testing.T) {
// const expectedReturn = 15
// cloudEventListener = func(args []string) int {
// return expectedReturn
// }
// if os.Getenv("BE_MAIN") == "1" {
// main()
// return
// }
// cmd := exec.Command(os.Args[0], "-test.run=TestMain")
// cmd.Env = append(os.Environ(), "BE_MAIN=1")
// err := cmd.Run()
// if e, ok := err.(*exec.ExitError); ok && e.ExitCode() == expectedReturn {
// return
// }
// t.Fatalf("process ran with err %v, want exit status %v", expectedReturn, err)
// }
// reads the json event file and convert its content into an event
func extractEvent(eventFileName string) (*event.Event, error) {
eventFile, err := os.ReadFile(eventFileName)
if err != nil {
return nil, err
}
incomingEvent := &cloudevents.Event{}
err = json.Unmarshal(eventFile, incomingEvent)
if err != nil {
return nil, err
}
return incomingEvent, err
}
// Check if events are handled (not handled) when they should be (shouldn't be)
func checkProcessKeptnCloudEvent(t *testing.T, fileName string, calledSLI *bool, calledConfig *bool) {
configureMonitoringTriggeredEventv1 := "sh.keptn.event.monitoring.configure.triggered"
configureMonitoringTriggeredEvent := "sh.keptn.event.configure-monitoring.triggered"
incomingEvent, err := extractEvent(fileName)
if err != nil {
t.Fatalf("Error getting keptn event : %v", err)
}
err = processKeptnCloudEvent(context.Background(), *incomingEvent)
if err != nil {
//verify if events that should be handled are not skipped
if strings.HasPrefix(err.Error(), UnhandleKeptnCloudEvent) &&
(incomingEvent.Type() == "sh.keptn.event.configure-monitoring" ||
incomingEvent.Type() == keptnv2.GetTriggeredEventType(keptnv2.GetSLITaskName) ||
incomingEvent.Type() == configureMonitoringTriggeredEventv1 ||
incomingEvent.Type() == keptnv1.ConfigureMonitoringEventType) {
t.Fatal("The function didn't handle an event that should have been handled.")
}
return
}
//verify if events that should be handled are handled correctly
switch incomingEvent.Type() {
case configureMonitoringTriggeredEvent, keptnv2.ConfigureMonitoringTaskName:
if *calledConfig == false {
t.Fatal("The configure monitoring event has not been handled.")
}
case keptnv2.GetTriggeredEventType(keptnv2.GetSLITaskName):
if *calledSLI == false {
t.Fatal("The get-sli triggered event has not been handled.")
}
case keptnv1.ConfigureMonitoringEventType:
t.Fatal("keptnv1 configure monitoring event must be converted into keptnv2 configure monitoring event.")
}
}
// Sends a cloud event
func sendTestCloudEvent(eventFileName string) error {
body, err := os.ReadFile(eventFileName)
if err != nil {
return fmt.Errorf("Can't load %s: %w", eventFileName, err)
}
client := &http.Client{}
req, err := http.NewRequest(http.MethodPost, "http://localhost:"+fmt.Sprint(testPortforMain), bytes.NewBuffer(body))
if err != nil {
return fmt.Errorf("Error : %w\n", err)
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Cache-Control", "no-cache")
req.Header.Add("Content-Type", "application/cloudevents+json")
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
_, err = io.ReadAll(res.Body)
if err != nil {
return err
}
return nil
}