blob: b5c4c6308e027241803e5076758bda6fe93ff628 [file] [log] [blame]
Mohamed Abukar4e7e7122020-03-04 10:01:45 +02001/*
2 * Copyright (c) 2020 AT&T Intellectual Property.
3 * Copyright (c) 2020 Nokia.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * This source code is part of the near-RT RIC (RAN Intelligent Controller)
18 * platform project (RICP).
19 */
20
21package main
22
23import (
vipin4cedd502020-09-25 05:58:31 +000024 "bytes"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020025 "encoding/json"
26 "fmt"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020027 "io"
28 "io/ioutil"
29 "net"
30 "net/http"
31 "net/http/httptest"
32 "os"
Anssi Mannila00894a42020-10-19 11:36:26 +030033 "os/exec"
vipin4cedd502020-09-25 05:58:31 +000034 "strconv"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020035 "strings"
36 "testing"
37 "time"
Mohamed Abukar2d3cc6b2021-06-09 07:33:04 +000038
Juha Hyttinen281d0602021-12-23 10:14:40 +020039 "gerrit.o-ran-sc.org/r/ric-plt/alarm-go.git/alarm"
Mohamed Abukar2d3cc6b2021-06-09 07:33:04 +000040 "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
41 "github.com/gorilla/mux"
42 "github.com/prometheus/alertmanager/api/v2/models"
43 "github.com/stretchr/testify/assert"
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020044)
45
Abukar Mohamed121e8b62020-09-18 11:41:33 +000046var alarmManager *AlarmManager
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020047var alarmer *alarm.RICAlarm
48var eventChan chan string
49
50// Test cases
51func TestMain(M *testing.M) {
Mohamed Abukar105030f2020-10-22 18:08:34 +030052 alarmManager = NewAlarmManager("localhost:9093", 500, false)
vipin6f73fa32020-10-06 06:51:53 +000053 alarmManager.alertInterval = 20000
Mohamed Abukar3649fae2020-10-30 23:51:39 +020054 go alarmManager.Run(false, 5)
vipin14323a92020-09-25 10:03:43 +000055 time.Sleep(time.Duration(10) * time.Second)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020056
57 // Wait until RMR is up-and-running
58 for !xapp.Rmr.IsReady() {
59 time.Sleep(time.Duration(1) * time.Second)
60 }
61
62 alarmer, _ = alarm.InitAlarm("my-pod", "my-app")
vipin541eb502020-09-22 12:04:59 +000063 alarmManager.alarmClient = alarmer
Mohamed Abukareac44512020-03-31 09:46:04 +030064 time.Sleep(time.Duration(5) * time.Second)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +020065 eventChan = make(chan string)
66
67 os.Exit(M.Run())
68}
69
vipin14323a92020-09-25 10:03:43 +000070func TestGetPreDefinedAlarmDefinitions(t *testing.T) {
71 xapp.Logger.Info("TestGetPreDefinedAlarmDefinitions")
72 var alarmDefinition alarm.AlarmDefinition
73 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
manoj1cb3ca382021-09-14 05:57:26 -040074 vars := map[string]string{"alarmId": strconv.FormatUint(72004, 10)}
vipin14323a92020-09-25 10:03:43 +000075 req = mux.SetURLVars(req, vars)
76 handleFunc := http.HandlerFunc(alarmManager.GetAlarmDefinition)
77 response := executeRequest(req, handleFunc)
78 checkResponseCode(t, http.StatusOK, response.Code)
79 json.NewDecoder(response.Body).Decode(&alarmDefinition)
80 xapp.Logger.Info("alarm definition = %v", alarmDefinition)
Juha Hyttinen281d0602021-12-23 10:14:40 +020081 if alarmDefinition.AlarmId != alarm.E2_CONNECTION_PROBLEM || alarmDefinition.AlarmText != "E2 CONNECTION PROBLEM" {
vipin14323a92020-09-25 10:03:43 +000082 t.Errorf("Incorrect alarm definition")
83 }
84}
85
vipin54a3a4f2020-09-23 12:19:58 +000086func TestSetAlarmDefinitions(t *testing.T) {
87 xapp.Logger.Info("TestSetAlarmDefinitions")
Juha Hyttinen281d0602021-12-23 10:14:40 +020088
89 var alarm72004Definition alarm.AlarmDefinition
manoj1cb3ca382021-09-14 05:57:26 -040090 alarm72004Definition.AlarmId = alarm.E2_CONNECTION_PROBLEM
91 alarm72004Definition.AlarmText = "E2 CONNECTIVITY LOST TO E-NODEB/G-NODEB"
92 alarm72004Definition.EventType = "Communication error"
93 alarm72004Definition.OperationInstructions = "Not defined"
94 alarm72004Definition.RaiseDelay = 0
95 alarm72004Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +000096
manoj1cb3ca382021-09-14 05:57:26 -040097 var alarm72008Definition alarm.AlarmDefinition
98 alarm72008Definition.AlarmId = alarm.ACTIVE_ALARM_EXCEED_MAX_THRESHOLD
99 alarm72008Definition.AlarmText = "ACTIVE ALARM EXCEED MAX THRESHOLD"
100 alarm72008Definition.EventType = "storage warning"
101 alarm72008Definition.OperationInstructions = "Clear alarms or raise threshold"
102 alarm72008Definition.RaiseDelay = 0
103 alarm72008Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000104
manoj1cb3ca382021-09-14 05:57:26 -0400105 var alarm72009Definition alarm.AlarmDefinition
106 alarm72009Definition.AlarmId = alarm.ALARM_HISTORY_EXCEED_MAX_THRESHOLD
107 alarm72009Definition.AlarmText = "ALARM HISTORY EXCEED MAX THRESHOLD"
108 alarm72009Definition.EventType = "storage warning"
109 alarm72009Definition.OperationInstructions = "Clear alarms or raise threshold"
110 alarm72009Definition.RaiseDelay = 0
111 alarm72009Definition.ClearDelay = 0
vipin54a3a4f2020-09-23 12:19:58 +0000112
manoj1cb3ca382021-09-14 05:57:26 -0400113 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm72004Definition, &alarm72008Definition, &alarm72009Definition}}
vipin54a3a4f2020-09-23 12:19:58 +0000114 pbodyEn, _ := json.Marshal(pbodyParams)
115 req, _ := http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
116 handleFunc := http.HandlerFunc(alarmManager.SetAlarmDefinition)
117 response := executeRequest(req, handleFunc)
118 status := checkResponseCode(t, http.StatusOK, response.Code)
119 xapp.Logger.Info("status = %v", status)
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300120}
vipin54a3a4f2020-09-23 12:19:58 +0000121
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300122func TestSetAlarmConfigDecodeError(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200123 xapp.Logger.Info("TestSetAlarmConfigDecodeError")
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300124
125 var jsonStr = []byte(`{"test":"Invalid Alarm Data", "test1" 123}`)
Juha Hyttinen281d0602021-12-23 10:14:40 +0200126 req, _ := http.NewRequest("POST", "/ric/v1/alarms", bytes.NewBuffer(jsonStr))
127 handleFunc := http.HandlerFunc(alarmManager.SetAlarmConfig)
128 response := executeRequest(req, handleFunc)
129 status := checkResponseCode(t, http.StatusOK, response.Code)
130 xapp.Logger.Info("status = %v", status)
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300131}
132
133func TestSetAlarmDefinitionDecodeError(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200134 xapp.Logger.Info("TestSetAlarmDefinitionDecodeError")
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300135
Juha Hyttinen281d0602021-12-23 10:14:40 +0200136 var jsonStr = []byte(`{"test":"Invalid Alarm Data", "test1" 123}`)
137 req, _ := http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(jsonStr))
138 handleFunc := http.HandlerFunc(alarmManager.SetAlarmDefinition)
139 response := executeRequest(req, handleFunc)
140 status := checkResponseCode(t, http.StatusBadRequest, response.Code)
141 xapp.Logger.Info("status = %v", status)
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300142}
143
144func TestRaiseAlarmEmptyBody(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200145 xapp.Logger.Info("TestRaiseAlarmEmptyBody")
146 req, _ := http.NewRequest("POST", "/ric/v1/alarms", nil)
147 handleFunc := http.HandlerFunc(alarmManager.RaiseAlarm)
148 response := executeRequest(req, handleFunc)
149 status := checkResponseCode(t, http.StatusOK, response.Code)
150 xapp.Logger.Info("status = %v", status)
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300151}
152
153func TestSetAlarmDefinitionsEmptyBody(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200154 xapp.Logger.Info("TestSetAlarmDefinitionsEmptyBody")
155 req, _ := http.NewRequest("POST", "/ric/v1/alarms/define", nil)
156 handleFunc := http.HandlerFunc(alarmManager.SetAlarmDefinition)
157 response := executeRequest(req, handleFunc)
158 status := checkResponseCode(t, http.StatusBadRequest, response.Code)
159 xapp.Logger.Info("status = %v", status)
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300160}
161
162func TestClearAlarmEmptyBody(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200163 xapp.Logger.Info("TestClearAlarmEmptyBody")
164 req, _ := http.NewRequest("DELETE", "/ric/v1/alarms", nil)
165 handleFunc := http.HandlerFunc(alarmManager.ClearAlarm)
166 response := executeRequest(req, handleFunc)
167 status := checkResponseCode(t, http.StatusOK, response.Code)
168 xapp.Logger.Info("status = %v", status)
vipin54a3a4f2020-09-23 12:19:58 +0000169}
170
171func TestGetAlarmDefinitions(t *testing.T) {
172 xapp.Logger.Info("TestGetAlarmDefinitions")
173 var alarmDefinition alarm.AlarmDefinition
174 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
manoj1cb3ca382021-09-14 05:57:26 -0400175 vars := map[string]string{"alarmId": strconv.FormatUint(72004, 10)}
vipin54a3a4f2020-09-23 12:19:58 +0000176 req = mux.SetURLVars(req, vars)
177 handleFunc := http.HandlerFunc(alarmManager.GetAlarmDefinition)
178 response := executeRequest(req, handleFunc)
179 checkResponseCode(t, http.StatusOK, response.Code)
180 json.NewDecoder(response.Body).Decode(&alarmDefinition)
181 xapp.Logger.Info("alarm definition = %v", alarmDefinition)
manoj1cb3ca382021-09-14 05:57:26 -0400182 if alarmDefinition.AlarmId != alarm.E2_CONNECTION_PROBLEM || alarmDefinition.AlarmText != "E2 CONNECTION PROBLEM" {
vipin54a3a4f2020-09-23 12:19:58 +0000183 t.Errorf("Incorrect alarm definition")
184 }
185}
186
187func TestDeleteAlarmDefinitions(t *testing.T) {
188 xapp.Logger.Info("TestDeleteAlarmDefinitions")
189 //Get all
190 var ricAlarmDefinitions RicAlarmDefinitions
191 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
192 req = mux.SetURLVars(req, nil)
193 handleFunc := http.HandlerFunc(alarmManager.GetAlarmDefinition)
194 response := executeRequest(req, handleFunc)
195 checkResponseCode(t, http.StatusOK, response.Code)
196 json.NewDecoder(response.Body).Decode(&ricAlarmDefinitions)
197 for _, alarmDefinition := range ricAlarmDefinitions.AlarmDefinitions {
198 xapp.Logger.Info("alarm definition = %v", *alarmDefinition)
199 }
200
manoj1cb3ca382021-09-14 05:57:26 -0400201 //Delete 72004
vipin54a3a4f2020-09-23 12:19:58 +0000202 req, _ = http.NewRequest("DELETE", "/ric/v1/alarms/define", nil)
manoj1cb3ca382021-09-14 05:57:26 -0400203 vars := map[string]string{"alarmId": strconv.FormatUint(72004, 10)}
vipin4cedd502020-09-25 05:58:31 +0000204 req = mux.SetURLVars(req, vars)
205 handleFunc = http.HandlerFunc(alarmManager.DeleteAlarmDefinition)
206 response = executeRequest(req, handleFunc)
207 checkResponseCode(t, http.StatusOK, response.Code)
vipin54a3a4f2020-09-23 12:19:58 +0000208
manoj1cb3ca382021-09-14 05:57:26 -0400209 //Get 72004 fail
vipin54a3a4f2020-09-23 12:19:58 +0000210 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
manoj1cb3ca382021-09-14 05:57:26 -0400211 vars = map[string]string{"alarmId": strconv.FormatUint(72004, 10)}
vipin54a3a4f2020-09-23 12:19:58 +0000212 req = mux.SetURLVars(req, vars)
213 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
214 response = executeRequest(req, handleFunc)
215 checkResponseCode(t, http.StatusBadRequest, response.Code)
216
Juha Hyttinen281d0602021-12-23 10:14:40 +0200217 //Delete Alarm which doesn't present
218 //Set 72004 success
manoj1cb3ca382021-09-14 05:57:26 -0400219 var alarm72004Definition alarm.AlarmDefinition
220 alarm72004Definition.AlarmId = alarm.E2_CONNECTION_PROBLEM
221 alarm72004Definition.AlarmText = "E2 CONNECTION PROBLEM"
222 alarm72004Definition.EventType = "Processing error"
223 alarm72004Definition.OperationInstructions = "Not defined"
224 alarm72004Definition.RaiseDelay = 0
225 alarm72004Definition.ClearDelay = 0
226 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm72004Definition}}
vipin54a3a4f2020-09-23 12:19:58 +0000227 pbodyEn, _ := json.Marshal(pbodyParams)
228 req, _ = http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
229 handleFunc = http.HandlerFunc(alarmManager.SetAlarmDefinition)
230 response = executeRequest(req, handleFunc)
231 checkResponseCode(t, http.StatusOK, response.Code)
232
manoj1cb3ca382021-09-14 05:57:26 -0400233 //Get 72004 success
vipin54a3a4f2020-09-23 12:19:58 +0000234 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
manoj1cb3ca382021-09-14 05:57:26 -0400235 vars = map[string]string{"alarmId": strconv.FormatUint(72004, 10)}
vipin54a3a4f2020-09-23 12:19:58 +0000236 req = mux.SetURLVars(req, vars)
237 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
238 response = executeRequest(req, handleFunc)
239 checkResponseCode(t, http.StatusOK, response.Code)
240}
241
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200242func TestNewAlarmStoredAndPostedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000243 xapp.Logger.Info("TestNewAlarmStoredAndPostedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200244 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
245 defer ts.Close()
246
manoj1cb3ca382021-09-14 05:57:26 -0400247 a := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityCritical, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200248 assert.Nil(t, alarmer.Raise(a), "raise failed")
249
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200250 VerifyAlarm(t, a, 1)
vipin01454d42020-11-10 08:13:51 +0000251
252 var activeAlarms []AlarmNotification
253 activeAlarms = make([]AlarmNotification, 1)
254 req, _ := http.NewRequest("GET", "/ric/v1/alarms/active", nil)
255 req = mux.SetURLVars(req, nil)
256 handleFunc := http.HandlerFunc(alarmManager.GetActiveAlarms)
257 response := executeRequest(req, handleFunc)
258 checkResponseCode(t, http.StatusOK, response.Code)
259
260 // Decode the json output from handler
261 json.NewDecoder(response.Body).Decode(activeAlarms)
262 if len(activeAlarms) != 1 {
263 t.Errorf("Incorrect alarm alarm count")
264 }
265
266 var alarmHistory []AlarmNotification
267 alarmHistory = make([]AlarmNotification, 1)
268 req, _ = http.NewRequest("GET", "/ric/v1/alarms/history", nil)
269 req = mux.SetURLVars(req, nil)
270 handleFunc = http.HandlerFunc(alarmManager.GetAlarmHistory)
271 response = executeRequest(req, handleFunc)
272 checkResponseCode(t, http.StatusOK, response.Code)
273
274 // Decode the json output from handler
275 json.NewDecoder(response.Body).Decode(alarmHistory)
276 if len(alarmHistory) != 1 {
277 t.Errorf("Incorrect alarm history count")
278 }
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200279}
280
281func TestAlarmClearedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000282 xapp.Logger.Info("TestAlarmClearedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200283 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
284 defer ts.Close()
285
286 // Raise the alarm
manoj1cb3ca382021-09-14 05:57:26 -0400287 a := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityCritical, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200288 assert.Nil(t, alarmer.Raise(a), "raise failed")
289
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200290 VerifyAlarm(t, a, 1)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200291
292 // Now Clear the alarm and check alarm is removed
manoj1cb3ca382021-09-14 05:57:26 -0400293 a = alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityCritical, "Some App data", "eth 0 1")
Juha Hyttinen281d0602021-12-23 10:14:40 +0200294 assert.Nil(t, alarmer.Clear(a), "clear failed")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200295
296 time.Sleep(time.Duration(2) * time.Second)
Juha Hyttinen5f9b88b2023-06-02 10:04:15 +0300297 //assert.Equal(t, len(alarmManager.activeAlarms), 0)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200298}
299
300func TestMultipleAlarmsRaisedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000301 xapp.Logger.Info("TestMultipleAlarmsRaisedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200302 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
303 defer ts.Close()
304
305 // Raise two alarms
manoj1cb3ca382021-09-14 05:57:26 -0400306 a := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityMajor, "Some App data", "eth 0 1")
Juha Hyttinen281d0602021-12-23 10:14:40 +0200307 assert.Nil(t, alarmer.Raise(a), "raise failed")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200308
manoj1cb3ca382021-09-14 05:57:26 -0400309 b := alarmer.NewAlarm(alarm.ACTIVE_ALARM_EXCEED_MAX_THRESHOLD, alarm.SeverityMinor, "Hello", "abcd 11")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200310 assert.Nil(t, alarmer.Raise(b), "raise failed")
311
Mohamed Abukar2d3cc6b2021-06-09 07:33:04 +0000312 time.Sleep(time.Duration(5) * time.Second)
313
314 xapp.Logger.Info("VerifyAlarm: %d %+v", len(alarmManager.activeAlarms), alarmManager.activeAlarms)
315 VerifyAlarm(t, a, 1)
316 xapp.Logger.Info("VerifyAlarm: %d %+v", len(alarmManager.activeAlarms), alarmManager.activeAlarms)
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200317 VerifyAlarm(t, b, 2)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200318}
319
320func TestMultipleAlarmsClearedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000321 xapp.Logger.Info("TestMultipleAlarmsClearedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200322 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
323 defer ts.Close()
324
325 // Raise two alarms
manoj1cb3ca382021-09-14 05:57:26 -0400326 a := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityMajor, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200327 assert.Nil(t, alarmer.Clear(a), "clear failed")
328
manoj1cb3ca382021-09-14 05:57:26 -0400329 b := alarmer.NewAlarm(alarm.ACTIVE_ALARM_EXCEED_MAX_THRESHOLD, alarm.SeverityMinor, "Hello", "abcd 11")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200330 assert.Nil(t, alarmer.Clear(b), "clear failed")
331
332 time.Sleep(time.Duration(2) * time.Second)
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000333 assert.Equal(t, len(alarmManager.activeAlarms), 0)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200334}
335
336func TestAlarmsSuppresedSucess(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000337 xapp.Logger.Info("TestAlarmsSuppresedSucess")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200338 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
339 defer ts.Close()
340
341 // Raise two similar/matching alarms ... the second one suppresed
manoj1cb3ca382021-09-14 05:57:26 -0400342 a := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityMajor, "Some App data", "eth 0 1")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200343 assert.Nil(t, alarmer.Raise(a), "raise failed")
344 assert.Nil(t, alarmer.Raise(a), "raise failed")
345
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200346 VerifyAlarm(t, a, 1)
vipin541eb502020-09-22 12:04:59 +0000347 assert.Nil(t, alarmer.Clear(a), "clear failed")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200348}
349
350func TestInvalidAlarms(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000351 xapp.Logger.Info("TestInvalidAlarms")
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200352 a := alarmer.NewAlarm(1111, alarm.SeverityMajor, "Some App data", "eth 0 1")
353 assert.Nil(t, alarmer.Raise(a), "raise failed")
354 time.Sleep(time.Duration(2) * time.Second)
355}
356
357func TestAlarmHandlingErrorCases(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000358 xapp.Logger.Info("TestAlarmHandlingErrorCases")
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000359 ok, err := alarmManager.HandleAlarms(&xapp.RMRParams{})
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200360 assert.Equal(t, err.Error(), "unexpected end of JSON input")
361 assert.Nil(t, ok, "raise failed")
362}
363
364func TestConsumeUnknownMessage(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000365 xapp.Logger.Info("TestConsumeUnknownMessage")
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000366 err := alarmManager.Consume(&xapp.RMRParams{})
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200367 assert.Nil(t, err, "raise failed")
368}
369
370func TestStatusCallback(t *testing.T) {
vipin54a3a4f2020-09-23 12:19:58 +0000371 xapp.Logger.Info("TestStatusCallback")
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000372 assert.Equal(t, true, alarmManager.StatusCB())
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200373}
374
vipin541eb502020-09-22 12:04:59 +0000375func TestActiveAlarmMaxThresholds(t *testing.T) {
376 xapp.Logger.Info("TestActiveAlarmMaxThresholds")
377 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
378 alarmManager.maxActiveAlarms = 0
379 alarmManager.maxAlarmHistory = 10
380
manoj1cb3ca382021-09-14 05:57:26 -0400381 a := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityCritical, "Some Application data", "eth 0 2")
vipin541eb502020-09-22 12:04:59 +0000382 assert.Nil(t, alarmer.Raise(a), "raise failed")
383
384 var alarmConfigParams alarm.AlarmConfigParams
385 req, _ := http.NewRequest("GET", "/ric/v1/alarms/config", nil)
386 req = mux.SetURLVars(req, nil)
387 handleFunc := http.HandlerFunc(alarmManager.GetAlarmConfig)
388 response := executeRequest(req, handleFunc)
389
390 // Check HTTP Status Code
391 checkResponseCode(t, http.StatusOK, response.Code)
392
393 // Decode the json output from handler
394 json.NewDecoder(response.Body).Decode(&alarmConfigParams)
395 if alarmConfigParams.MaxActiveAlarms != 0 || alarmConfigParams.MaxAlarmHistory != 10 {
396 t.Errorf("Incorrect alarm thresholds")
397 }
398
399 time.Sleep(time.Duration(1) * time.Second)
400 alarmManager.maxActiveAlarms = 5000
401 alarmManager.maxAlarmHistory = 20000
402 VerifyAlarm(t, a, 2)
403 VerifyAlarm(t, a, 2)
404 ts.Close()
405}
406
Anssi Mannila00894a42020-10-19 11:36:26 +0300407func TestGetPrometheusAlerts(t *testing.T) {
408 time.Sleep(1 * time.Second)
409 xapp.Logger.Info("TestGetPrometheusAlerts")
410 ts := CreatePromAlertSimulator2(t, "GET", "/alerts?active=true&inhibited=true&silenced=true&unprocessed=true")
411
412 commandReady := make(chan bool, 1)
413 command := "cli/alarm-cli"
Anssi Mannila43fe17e2020-11-05 14:06:54 +0200414 args := []string{"alerts", "--active", "true", "--inhibited", "true", "--silenced", "--unprocessed", "true", "true", "--host", "localhost", "--port", "9093", "flushall"}
Anssi Mannila00894a42020-10-19 11:36:26 +0300415 ExecCLICommand(commandReady, command, args...)
416 <-commandReady
417
418 ts.Close()
419}
420
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200421func TestDelayedAlarmRaiseAndClear(t *testing.T) {
422 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear")
423
424 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
425 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
426
427 // Add new alarm definition
428 var alarm9999Definition alarm.AlarmDefinition
429 alarm9999Definition.AlarmId = 9999
430 alarm9999Definition.AlarmText = "DELAYED TEST ALARM"
431 alarm9999Definition.EventType = "Test type"
432 alarm9999Definition.OperationInstructions = "Not defined"
433 alarm9999Definition.RaiseDelay = 1
434 alarm9999Definition.ClearDelay = 1
435 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm9999Definition}}
436 pbodyEn, _ := json.Marshal(pbodyParams)
437 req, _ := http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
438 handleFunc := http.HandlerFunc(alarmManager.SetAlarmDefinition)
439 response := executeRequest(req, handleFunc)
440 checkResponseCode(t, http.StatusOK, response.Code)
441
442 // Verify 9999 alarm definition
443 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
manoj1cb3ca382021-09-14 05:57:26 -0400444 vars := map[string]string{"alarmId": strconv.FormatUint(72004, 10)}
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200445 req = mux.SetURLVars(req, vars)
446 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
447 response = executeRequest(req, handleFunc)
448 checkResponseCode(t, http.StatusOK, response.Code)
449
450 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
451 defer ts.Close()
452
Mohamed Abukar2336a842020-10-30 16:19:38 +0200453 // Raise alarm. Posting alert and updating alarm history should be delayed
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200454 a := alarmer.NewAlarm(9999, alarm.SeverityCritical, "Some App data", "eth 0 1")
455 assert.Nil(t, alarmer.Raise(a), "raise failed")
Mohamed Abukar2336a842020-10-30 16:19:38 +0200456 VerifyAlarm(t, a, activeAlarmsBeforeTest+1)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200457
458 // Clear the alarm and check the alarm is removed. Posting alert clear and updating alarm history should be delayed
459 assert.Nil(t, alarmer.Clear(a), "clear failed")
460
461 time.Sleep(time.Duration(2) * time.Second)
462 assert.Equal(t, len(alarmManager.activeAlarms), activeAlarmsBeforeTest)
Mohamed Abukar2336a842020-10-30 16:19:38 +0200463 assert.Equal(t, len(alarmManager.alarmHistory), alarmHistoryBeforeTest+2)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200464}
465
466func TestDelayedAlarmRaiseAndClear2(t *testing.T) {
467 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear2")
468
469 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
470 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
471
472 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
473 defer ts.Close()
474
475 // Raise two alarms. The first should be delayed
476 a := alarmer.NewAlarm(9999, alarm.SeverityCritical, "Some App data", "eth 0 1")
477 assert.Nil(t, alarmer.Raise(a), "raise failed")
Mohamed Abukar2336a842020-10-30 16:19:38 +0200478 VerifyAlarm(t, a, activeAlarmsBeforeTest+1)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200479
manoj1cb3ca382021-09-14 05:57:26 -0400480 b := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityMajor, "Some App data", "eth 0 1")
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200481 assert.Nil(t, alarmer.Raise(b), "raise failed")
Mohamed Abukar2336a842020-10-30 16:19:38 +0200482 VerifyAlarm(t, b, activeAlarmsBeforeTest+2)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200483
484 // Clear two alarms. The first should be delayed. Check the alarms are removed
485 assert.Nil(t, alarmer.Clear(a), "clear failed")
486 assert.Nil(t, alarmer.Clear(b), "clear failed")
487
488 time.Sleep(time.Duration(2) * time.Second)
489 assert.Equal(t, len(alarmManager.activeAlarms), activeAlarmsBeforeTest)
Mohamed Abukar2336a842020-10-30 16:19:38 +0200490 assert.Equal(t, len(alarmManager.alarmHistory), alarmHistoryBeforeTest+4)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200491}
492
493func TestDelayedAlarmRaiseAndClear3(t *testing.T) {
494 xapp.Logger.Info("TestDelayedAlarmRaiseAndClear3")
495
496 // Delete exisitng 9999 alarm definition
497 req, _ := http.NewRequest("DELETE", "/ric/v1/alarms/define", nil)
498 vars := map[string]string{"alarmId": strconv.FormatUint(9999, 10)}
499 req = mux.SetURLVars(req, vars)
500 handleFunc := http.HandlerFunc(alarmManager.DeleteAlarmDefinition)
501 response := executeRequest(req, handleFunc)
502 checkResponseCode(t, http.StatusOK, response.Code)
503
504 // Add updated 9999 alarm definition
505 var alarm9999Definition alarm.AlarmDefinition
506 alarm9999Definition.AlarmId = 9999
507 alarm9999Definition.AlarmText = "DELAYED TEST ALARM"
508 alarm9999Definition.EventType = "Test type"
509 alarm9999Definition.OperationInstructions = "Not defined"
510 alarm9999Definition.RaiseDelay = 1
511 alarm9999Definition.ClearDelay = 0
512 pbodyParams := RicAlarmDefinitions{AlarmDefinitions: []*alarm.AlarmDefinition{&alarm9999Definition}}
513 pbodyEn, _ := json.Marshal(pbodyParams)
514 req, _ = http.NewRequest("POST", "/ric/v1/alarms/define", bytes.NewBuffer(pbodyEn))
515 handleFunc = http.HandlerFunc(alarmManager.SetAlarmDefinition)
516 response = executeRequest(req, handleFunc)
517 checkResponseCode(t, http.StatusOK, response.Code)
518
519 // Verify 9999 alarm definition
520 req, _ = http.NewRequest("GET", "/ric/v1/alarms/define", nil)
manoj1cb3ca382021-09-14 05:57:26 -0400521 vars = map[string]string{"alarmId": strconv.FormatUint(72004, 10)}
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200522 req = mux.SetURLVars(req, vars)
523 handleFunc = http.HandlerFunc(alarmManager.GetAlarmDefinition)
524 response = executeRequest(req, handleFunc)
525 checkResponseCode(t, http.StatusOK, response.Code)
526
527 activeAlarmsBeforeTest := len(alarmManager.activeAlarms)
528 alarmHistoryBeforeTest := len(alarmManager.alarmHistory)
529
530 ts := CreatePromAlertSimulator(t, "POST", "/api/v2/alerts", http.StatusOK, models.LabelSet{})
531 defer ts.Close()
532
533 // Raise two alarms. The first should be delayed
534 a := alarmer.NewAlarm(9999, alarm.SeverityCritical, "Some App data", "eth 0 1")
535 assert.Nil(t, alarmer.Raise(a), "raise failed")
Mohamed Abukar2336a842020-10-30 16:19:38 +0200536 VerifyAlarm(t, a, activeAlarmsBeforeTest+1)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200537
manoj1cb3ca382021-09-14 05:57:26 -0400538 b := alarmer.NewAlarm(alarm.E2_CONNECTION_PROBLEM, alarm.SeverityMajor, "Some App data", "eth 0 1")
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200539 assert.Nil(t, alarmer.Raise(b), "raise failed")
Mohamed Abukar2336a842020-10-30 16:19:38 +0200540 VerifyAlarm(t, b, activeAlarmsBeforeTest+2)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200541
542 // Clear two alarms. The first should be delayed. Check the alarms are removed
543 assert.Nil(t, alarmer.Clear(a), "clear failed")
544 assert.Nil(t, alarmer.Clear(b), "clear failed")
545
546 time.Sleep(time.Duration(2) * time.Second)
547 assert.Equal(t, len(alarmManager.activeAlarms), activeAlarmsBeforeTest)
Mohamed Abukar2336a842020-10-30 16:19:38 +0200548 assert.Equal(t, len(alarmManager.alarmHistory), alarmHistoryBeforeTest+4)
Anssi Mannila18fd03c2020-10-29 10:01:00 +0200549}
550
Mohamed Abukar3649fae2020-10-30 23:51:39 +0200551func TestClearExpiredAlarms(t *testing.T) {
552 xapp.Logger.Info("TestClearExpiredAlarms")
553
554 a := alarm.AlarmMessage{
manoj1cb3ca382021-09-14 05:57:26 -0400555 Alarm: alarmer.NewAlarm(72004, alarm.SeverityWarning, "threshold", ""),
Mohamed Abukar3649fae2020-10-30 23:51:39 +0200556 AlarmAction: alarm.AlarmActionRaise,
557 AlarmTime: time.Now().UnixNano(),
558 }
manoj1cb3ca382021-09-14 05:57:26 -0400559 d := alarm.RICAlarmDefinitions[72004]
Mohamed Abukar3649fae2020-10-30 23:51:39 +0200560 n := AlarmNotification{a, *d}
561 alarmManager.activeAlarms = make([]AlarmNotification, 0)
562 alarmManager.UpdateActiveAlarmList(&n)
563
564 // Unknown SP
565 a.Alarm.SpecificProblem = 1234
566 assert.False(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
567
568 // TTL is 0
569 d.TimeToLive = 0
570 assert.False(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
571
572 // TTL not expired
manoj1cb3ca382021-09-14 05:57:26 -0400573 a.Alarm.SpecificProblem = 72004
Mohamed Abukar3649fae2020-10-30 23:51:39 +0200574 d.TimeToLive = 2
575 assert.False(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
576
577 // TTL expired, alarm should be cleared
578 time.Sleep(time.Duration(3) * time.Second)
579 assert.Equal(t, len(alarmManager.activeAlarms), 1)
580 assert.True(t, alarmManager.ClearExpiredAlarms(n, 0, false), "ClearExpiredAlarms failed")
581 assert.Equal(t, len(alarmManager.activeAlarms), 0)
582}
583
vipin01454d42020-11-10 08:13:51 +0000584func TestSetAlarmConfig(t *testing.T) {
585 xapp.Logger.Info("TestSetAlarmConfig")
586
587 var setAlarmConfig alarm.AlarmConfigParams
588 setAlarmConfig.MaxActiveAlarms = 500
589 setAlarmConfig.MaxAlarmHistory = 2000
590
591 pbodyEn, _ := json.Marshal(setAlarmConfig)
592 req, _ := http.NewRequest("POST", "/ric/v1/alarms/config", bytes.NewBuffer(pbodyEn))
593 handleFunc := http.HandlerFunc(alarmManager.SetAlarmConfig)
594 response := executeRequest(req, handleFunc)
595 checkResponseCode(t, http.StatusOK, response.Code)
596
597 var getAlarmConfig alarm.AlarmConfigParams
598 req, _ = http.NewRequest("GET", "/ric/v1/alarms/config", nil)
599 req = mux.SetURLVars(req, nil)
600 handleFunc = http.HandlerFunc(alarmManager.GetAlarmConfig)
601 response = executeRequest(req, handleFunc)
602 checkResponseCode(t, http.StatusOK, response.Code)
603
604 // Decode the json output from handler
605 json.NewDecoder(response.Body).Decode(&getAlarmConfig)
606 if getAlarmConfig.MaxActiveAlarms != 500 || getAlarmConfig.MaxAlarmHistory != 2000 {
607 t.Errorf("Incorrect alarm thresholds")
608 }
609
610 // Revert ot default
611 setAlarmConfig.MaxActiveAlarms = 5000
612 setAlarmConfig.MaxAlarmHistory = 20000
613
614 pbodyEn, _ = json.Marshal(setAlarmConfig)
615 req, _ = http.NewRequest("POST", "/ric/v1/alarms/config", bytes.NewBuffer(pbodyEn))
616 handleFunc = http.HandlerFunc(alarmManager.SetAlarmConfig)
617 response = executeRequest(req, handleFunc)
618 checkResponseCode(t, http.StatusOK, response.Code)
619
620 req, _ = http.NewRequest("GET", "/ric/v1/alarms/config", nil)
621 req = mux.SetURLVars(req, nil)
622 handleFunc = http.HandlerFunc(alarmManager.GetAlarmConfig)
623 response = executeRequest(req, handleFunc)
624 checkResponseCode(t, http.StatusOK, response.Code)
625
626 // Decode the json output from handler
627 json.NewDecoder(response.Body).Decode(&getAlarmConfig)
628 if getAlarmConfig.MaxActiveAlarms != 5000 || getAlarmConfig.MaxAlarmHistory != 20000 {
629 t.Errorf("Incorrect alarm thresholds")
630 }
631}
632
633func TestConfigChangeCB(t *testing.T) {
634 xapp.Logger.Info("TestConfigChangeCB")
635 alarmManager.ConfigChangeCB("AlarmManager")
636}
637
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300638func TestPostAlarm(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200639 xapp.Logger.Info("TestPostAlarm")
640 var activeAlarms []AlarmNotification
641 activeAlarms = make([]AlarmNotification, 1)
642 alarmManager.PostAlarm(&activeAlarms[0])
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300643}
644
645func TestPostAlarm1(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200646 xapp.Logger.Info("TestPostAlarm")
647 var activeAlarms []AlarmNotification
648 activeAlarms = make([]AlarmNotification, 2)
649 alarmManager.PostAlarm(&activeAlarms[0])
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300650}
651
Juha Hyttinen281d0602021-12-23 10:14:40 +0200652func TestNewAlarmManagerOther(t *testing.T) {
653 NewAlarmManager("", 0, true)
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300654}
655
656func TestStatusCallbackFailure(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200657 xapp.Logger.Info("TestStatusCallbackFailure")
658 alarmManager.rmrReady = false
659 assert.Equal(t, false, alarmManager.StatusCB())
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300660}
661
662func TestConfigChangeCBFailure(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200663 xapp.Logger.Info("TestConfigChangeCBFailure")
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300664 alarmManager.maxActiveAlarms = 0
665 alarmManager.maxAlarmHistory = 0
666 alarmManager.ConfigChangeCB("AlarmManager")
667}
668
manoj12855e432021-11-05 07:03:02 -0400669func TestReadAlarmDefinitionFromJsonWrongFilename(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200670 // use to set wrong file name os.Setenv("SITE_TITLE", "Test Site")
671 xapp.Logger.Info("TestReadAlarmDefinitionFromJsonWrongFilename")
672 os.Setenv("DEF_FILE", "test.json")
673 alarmManager.ReadAlarmDefinitionFromJson()
674 // correct the filename
manoj12855e432021-11-05 07:03:02 -0400675}
676
677func TestReadAlarmDefinitionFromJsonInvalidFilename(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200678 // use to set wrong file name os.Setenv("SITE_TITLE", "Test Site")
679 xapp.Logger.Info("TestReadAlarmDefinitionFromJsonInvalidFilename")
680 os.Setenv("DEF_FILE", "../../definitions/test.json")
681 alarmManager.ReadAlarmDefinitionFromJson()
682 // correct the filename
manoj12855e432021-11-05 07:03:02 -0400683}
684
685func TestPersistentStorage(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200686 xapp.Logger.Info("TestPersistentStorage")
687 alarmManager.alarmInfoPvFile = "../../definitions/sample.json"
688 alarmManager.ReadAlarmInfoFromPersistentVolume()
manoj12855e432021-11-05 07:03:02 -0400689}
690
691func TestDeleteAlarmDefinitions1(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200692 xapp.Logger.Info("TestDeleteAlarmDefinitions1")
693 //Get all
694 //Delete Alarm which doesn't present
695 req, _ := http.NewRequest("DELETE", "/ric/v1/alarms/define", nil)
manoj12855e432021-11-05 07:03:02 -0400696 vars := map[string]string{"alarmId": strconv.FormatUint(882004, 10)}
Juha Hyttinen281d0602021-12-23 10:14:40 +0200697 req = mux.SetURLVars(req, vars)
manoj12855e432021-11-05 07:03:02 -0400698 handleFunc := http.HandlerFunc(alarmManager.DeleteAlarmDefinition)
699 response := executeRequest(req, handleFunc)
Juha Hyttinen281d0602021-12-23 10:14:40 +0200700 checkResponseCode(t, http.StatusOK, response.Code)
manoj12855e432021-11-05 07:03:02 -0400701
Juha Hyttinen281d0602021-12-23 10:14:40 +0200702 //Delete Alarm which is incorrect present
703 req, _ = http.NewRequest("DELETE", "/ric/v1/alarms/define", nil)
704 vars = map[string]string{"alarmId": strconv.FormatUint(898989, 8)}
705 req = mux.SetURLVars(req, vars)
manoj12855e432021-11-05 07:03:02 -0400706 handleFunc = http.HandlerFunc(alarmManager.DeleteAlarmDefinition)
707 response = executeRequest(req, handleFunc)
Juha Hyttinen281d0602021-12-23 10:14:40 +0200708 checkResponseCode(t, http.StatusOK, response.Code)
manoj12855e432021-11-05 07:03:02 -0400709}
710
711func TestGetPreDefinedAlarmInvalidAlarm(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200712 xapp.Logger.Info("TestGetPreDefinedAlarmInvalidAlarm")
713 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
714 vars := map[string]string{"alarmId": "asdsc"}
715 req = mux.SetURLVars(req, vars)
716 handleFunc := http.HandlerFunc(alarmManager.GetAlarmDefinition)
717 response := executeRequest(req, handleFunc)
718 xapp.Logger.Info("response code = %v", response.Code)
719 checkResponseCode(t, http.StatusBadRequest, response.Code)
manoj12855e432021-11-05 07:03:02 -0400720}
721
722func TestDeleteAlarmDefinitions2(t *testing.T) {
Juha Hyttinen281d0602021-12-23 10:14:40 +0200723 xapp.Logger.Info("TestDeleteAlarmDefinitions2")
724 req, _ := http.NewRequest("GET", "/ric/v1/alarms/define", nil)
725 //Giving Wrong alarmId which can't convert into int
726 vars := map[string]string{"alarmId": "asdsc"}
727 req = mux.SetURLVars(req, vars)
728 handleFunc := http.HandlerFunc(alarmManager.DeleteAlarmDefinition)
729 response := executeRequest(req, handleFunc)
730 checkResponseCode(t, http.StatusBadRequest, response.Code)
manoj12855e432021-11-05 07:03:02 -0400731}
Mohamed Abukar44be37f2021-06-14 09:17:27 +0300732
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200733func VerifyAlarm(t *testing.T, a alarm.Alarm, expectedCount int) string {
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200734 receivedAlert := waitForEvent()
735
vipin6f73fa32020-10-06 06:51:53 +0000736 assert.Equal(t, expectedCount, len(alarmManager.activeAlarms))
Abukar Mohamed121e8b62020-09-18 11:41:33 +0000737 _, ok := alarmManager.IsMatchFound(a)
Mohamed Abukarebe58c22020-03-13 14:40:47 +0200738 assert.True(t, ok)
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200739
740 return receivedAlert
741}
742
743func VerifyAlert(t *testing.T, receivedAlert, expectedAlert string) {
744 receivedAlert = strings.Replace(fmt.Sprintf("%v", receivedAlert), "\r\n", " ", -1)
745 //assert.Equal(t, receivedAlert, e)
746}
747
748func CreatePromAlertSimulator(t *testing.T, method, url string, status int, respData interface{}) *httptest.Server {
749 l, err := net.Listen("tcp", "localhost:9093")
750 if err != nil {
751 t.Error("Failed to create listener: " + err.Error())
752 }
753 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Juha Hyttinen5f9b88b2023-06-02 10:04:15 +0300754
755 if strings.Contains(r.URL.String(), "active") {
756 w.Header().Add("Content-Type", "application/json")
757 w.WriteHeader(200)
758 // Read alerts from file
759 payload, err := readJSONFromFile("../../testresources/prometheus-alerts.json")
760 if err != nil {
761 t.Error("Failed to send response: ", err)
762 }
763 _, err = w.Write(payload)
764 if err != nil {
765 t.Error("Failed to send response: " + err.Error())
766 }
767 return
768 }
769
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200770 assert.Equal(t, r.Method, method)
771 assert.Equal(t, r.URL.String(), url)
772
773 fireEvent(t, r.Body)
774
775 w.Header().Add("Content-Type", "application/json")
776 w.WriteHeader(status)
777 b, _ := json.Marshal(respData)
778 w.Write(b)
779 }))
780 ts.Listener.Close()
781 ts.Listener = l
782
783 ts.Start()
784
785 return ts
786}
787
Anssi Mannila00894a42020-10-19 11:36:26 +0300788func CreatePromAlertSimulator2(t *testing.T, method, url string) *httptest.Server {
789 l, err := net.Listen("tcp", "localhost:9093")
790 if err != nil {
791 t.Error("Failed to create listener: " + err.Error())
792 }
793 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
794 assert.Equal(t, r.Method, method)
795 assert.Equal(t, r.URL.String(), url)
796
797 w.Header().Add("Content-Type", "application/json")
798 w.WriteHeader(200)
799 // Read alerts from file
800 payload, err := readJSONFromFile("../testresources/prometheus-alerts.json")
Mohamed Abukarf5a8e712020-10-19 16:58:17 +0300801 if err != nil {
802 t.Error("Failed to send response: ", err)
Anssi Mannila00894a42020-10-19 11:36:26 +0300803 }
804 _, err = w.Write(payload)
805 if err != nil {
806 t.Error("Failed to send response: " + err.Error())
807 }
808 }))
809 ts.Listener.Close()
810 ts.Listener = l
811 ts.Start()
812 return ts
813}
814
Mohamed Abukar4e7e7122020-03-04 10:01:45 +0200815func waitForEvent() string {
816 receivedAlert := <-eventChan
817 return receivedAlert
818}
819
820func fireEvent(t *testing.T, body io.ReadCloser) {
821 reqBody, err := ioutil.ReadAll(body)
822 assert.Nil(t, err, "ioutil.ReadAll failed")
823 assert.NotNil(t, reqBody, "ioutil.ReadAll failed")
824
825 eventChan <- fmt.Sprintf("%s", reqBody)
826}
vipin541eb502020-09-22 12:04:59 +0000827
828func executeRequest(req *http.Request, handleR http.HandlerFunc) *httptest.ResponseRecorder {
829 rr := httptest.NewRecorder()
830
831 handleR.ServeHTTP(rr, req)
832
833 return rr
834}
835
836func checkResponseCode(t *testing.T, expected, actual int) bool {
837 if expected != actual {
838 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
839 return false
840 }
841 return true
842}
Anssi Mannila00894a42020-10-19 11:36:26 +0300843
844func ExecCLICommand(commandReady chan bool, command string, args ...string) {
845 go func() {
846 xapp.Logger.Info("Giving CLI command")
847 cmd := exec.Command(command, args...)
848 cmd.Dir = "../"
849 output, err := cmd.CombinedOutput()
850 if err != nil {
851 xapp.Logger.Info("CLI command failed out: %s", err)
852 }
853 xapp.Logger.Info("CLI command output: %s", output)
854 commandReady <- true
855 xapp.Logger.Info("CLI command completed")
856 }()
857}
858
859func readJSONFromFile(filename string) ([]byte, error) {
860 file, err := ioutil.ReadFile(filename)
861 if err != nil {
862 err := fmt.Errorf("readJSONFromFile() failed: Error: %v", err)
863 return nil, err
864 }
865 return file, nil
866}