abf9345e6d04895c86185aa68e0426cfabb51de7
[ric-plt/xapp-frame.git] / pkg / xapp / xapp_test.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package xapp
21
22 import (
23         "github.com/gorilla/mux"
24         "github.com/spf13/viper"
25         "net/http"
26         "net/http/httptest"
27         "os"
28         "strings"
29         "testing"
30         "time"
31 )
32
33 //var _ = func() bool {
34 //      testing.Init()
35 //      return true
36 //}()
37
38 type Consumer struct{}
39
40 func (m Consumer) Consume(params *RMRParams) (err error) {
41         Sdl.Store("myKey", params.Payload)
42         return nil
43 }
44
45 // Test cases
46 func TestMain(m *testing.M) {
47         go RunWithParams(Consumer{}, viper.GetBool("db.waitForSdl"))
48         time.Sleep(time.Duration(5) * time.Second)
49         code := m.Run()
50         os.Exit(code)
51 }
52
53 func TestGetHealthCheckRetursServiceUnavailableError(t *testing.T) {
54         Logger.Info("CASE: TestGetHealthCheckRetursServiceUnavailableError")
55         req, _ := http.NewRequest("GET", "/ric/v1/health/ready", nil)
56         /*response :=*/ executeRequest(req)
57
58         //checkResponseCode(t, http.StatusServiceUnavailable, response.Code)
59 }
60
61 func TestGetHealthCheckReturnsSuccess(t *testing.T) {
62         Logger.Info("CASE: TestGetHealthCheckReturnsSuccess")
63         for Rmr.IsReady() == false {
64                 time.Sleep(time.Duration(2) * time.Second)
65         }
66
67         req, _ := http.NewRequest("GET", "/ric/v1/health/ready", nil)
68         response := executeRequest(req)
69
70         checkResponseCode(t, http.StatusOK, response.Code)
71 }
72
73 func TestInjectQuerySinglePath(t *testing.T) {
74         Logger.Info("CASE: TestInjectQuerySinglePath")
75         var handler = func(w http.ResponseWriter, r *http.Request) {
76         }
77
78         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar")
79
80         req, _ := http.NewRequest("GET", "/ric/v1/user?foo=bar", nil)
81         response := executeRequest(req)
82         checkResponseCode(t, http.StatusOK, response.Code)
83 }
84
85 func TestInjectQueryMultiplePaths(t *testing.T) {
86         Logger.Info("CASE: TestInjectQueryMultiplePaths")
87         var handler = func(w http.ResponseWriter, r *http.Request) {
88         }
89
90         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar", "id", "mykey")
91
92         req, _ := http.NewRequest("GET", "/ric/v1/user?foo=bar&id=mykey", nil)
93         response := executeRequest(req)
94         checkResponseCode(t, http.StatusOK, response.Code)
95 }
96
97 func TestInjectQueryFailures(t *testing.T) {
98         Logger.Info("CASE: TestInjectQueryFailures")
99         var handler = func(w http.ResponseWriter, r *http.Request) {
100         }
101
102         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar", "id", "mykey")
103
104         req, _ := http.NewRequest("GET", "/ric/v1/user?invalid=bar&no=mykey", nil)
105         response := executeRequest(req)
106         checkResponseCode(t, http.StatusNotFound, response.Code)
107 }
108
109 func TestMessagesReceivedSuccessfully(t *testing.T) {
110         Logger.Info("CASE: TestMessagesReceivedSuccessfully")
111         time.Sleep(time.Duration(5) * time.Second)
112         for i := 0; i < 100; i++ {
113                 params := &RMRParams{}
114                 params.Mtype = 10004
115                 params.SubId = -1
116                 params.Payload = []byte{1, 2, 3, 4, 5, 6}
117                 params.Meid = &RMRMeid{PlmnID: "1234", EnbID: "7788", RanName: "RanName-1234"}
118                 params.Xid = "TestXID"
119                 Rmr.SendMsg(params)
120         }
121
122         // Allow time to process the messages
123         time.Sleep(time.Duration(5) * time.Second)
124
125         waitForSdl := viper.GetBool("db.waitForSdl")
126         stats := getMetrics(t)
127         if !strings.Contains(stats, "ricxapp_RMR_Transmitted 100") {
128                 t.Errorf("Error: ricxapp_RMR_Transmitted value incorrect: %v", stats)
129         }
130
131         if !strings.Contains(stats, "ricxapp_RMR_Received 100") {
132                 t.Errorf("Error: ricxapp_RMR_Received value incorrect: %v", stats)
133         }
134
135         if !strings.Contains(stats, "ricxapp_RMR_TransmitError 0") {
136                 t.Errorf("Error: ricxapp_RMR_TransmitError value incorrect")
137         }
138
139         if !strings.Contains(stats, "ricxapp_RMR_ReceiveError 0") {
140                 t.Errorf("Error: ricxapp_RMR_ReceiveError value incorrect")
141         }
142
143         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_Stored 100") {
144                 t.Errorf("Error: ricxapp_SDL_Stored value incorrect")
145         }
146
147         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_StoreError 0") {
148                 t.Errorf("Error: ricxapp_SDL_StoreError value incorrect")
149         }
150 }
151
152 func TestMessagesReceivedSuccessfullyUsingWh(t *testing.T) {
153         Logger.Info("CASE: TestMessagesReceivedSuccessfullyUsingWh")
154         time.Sleep(time.Duration(5) * time.Second)
155         whid := Rmr.Openwh("localhost:4560")
156         time.Sleep(time.Duration(1) * time.Second)
157         for i := 0; i < 100; i++ {
158                 params := &RMRParams{}
159                 params.Mtype = 10004
160                 params.SubId = -1
161                 params.Payload = []byte{1, 2, 3, 4, 5, 6}
162                 params.Meid = &RMRMeid{PlmnID: "1234", EnbID: "7788", RanName: "RanName-1234"}
163                 params.Xid = "TestXID"
164                 params.Whid = int(whid)
165                 Rmr.SendMsg(params)
166         }
167
168         // Allow time to process the messages
169         time.Sleep(time.Duration(5) * time.Second)
170
171         waitForSdl := viper.GetBool("db.waitForSdl")
172         stats := getMetrics(t)
173         if !strings.Contains(stats, "ricxapp_RMR_Transmitted 200") {
174                 t.Errorf("Error: ricxapp_RMR_Transmitted value incorrect: %v", stats)
175         }
176
177         if !strings.Contains(stats, "ricxapp_RMR_Received 200") {
178                 t.Errorf("Error: ricxapp_RMR_Received value incorrect: %v", stats)
179         }
180
181         if !strings.Contains(stats, "ricxapp_RMR_TransmitError 0") {
182                 t.Errorf("Error: ricxapp_RMR_TransmitError value incorrect")
183         }
184
185         if !strings.Contains(stats, "ricxapp_RMR_ReceiveError 0") {
186                 t.Errorf("Error: ricxapp_RMR_ReceiveError value incorrect")
187         }
188
189         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_Stored 200") {
190                 t.Errorf("Error: ricxapp_SDL_Stored value incorrect")
191         }
192
193         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_StoreError 0") {
194                 t.Errorf("Error: ricxapp_SDL_StoreError value incorrect")
195         }
196         Rmr.Closewh(int(whid))
197 }
198
199 func TestMessagesReceivedSuccessfullyUsingWhCall(t *testing.T) {
200         Logger.Info("CASE: TestMessagesReceivedSuccessfullyUsingWhCall")
201         time.Sleep(time.Duration(5) * time.Second)
202         whid := Rmr.Openwh("localhost:4560")
203         params := &RMRParams{}
204         params.Payload = []byte("newrt|start\nnewrt|end\n")
205         params.Whid = int(whid)
206         params.Callid = 4
207         params.Timeout = 1000
208         Rmr.SendCallMsg(params)
209
210         // Allow time to process the messages
211         time.Sleep(time.Duration(2) * time.Second)
212
213         waitForSdl := viper.GetBool("db.waitForSdl")
214         stats := getMetrics(t)
215         if !strings.Contains(stats, "ricxapp_RMR_Transmitted 200") {
216                 t.Errorf("Error: ricxapp_RMR_Transmitted value incorrect: %v", stats)
217         }
218
219         if !strings.Contains(stats, "ricxapp_RMR_Received 201") {
220                 t.Errorf("Error: ricxapp_RMR_Received value incorrect: %v", stats)
221         }
222
223         if !strings.Contains(stats, "ricxapp_RMR_TransmitError 1") {
224                 t.Errorf("Error: ricxapp_RMR_TransmitError value incorrect")
225         }
226
227         if !strings.Contains(stats, "ricxapp_RMR_ReceiveError 0") {
228                 t.Errorf("Error: ricxapp_RMR_ReceiveError value incorrect")
229         }
230
231         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_Stored 201") {
232                 t.Errorf("Error: ricxapp_SDL_Stored value incorrect")
233         }
234
235         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_StoreError 0") {
236                 t.Errorf("Error: ricxapp_SDL_StoreError value incorrect")
237         }
238         Rmr.Closewh(int(whid))
239 }
240
241 func TestSubscribeChannels(t *testing.T) {
242         Logger.Info("CASE: TestSubscribeChannels")
243         if !viper.GetBool("db.waitForSdl") {
244                 return
245         }
246
247         var NotificationCb = func(ch string, events ...string) {
248                 if ch != "channel1" {
249                         t.Errorf("Error: Callback function called with incorrect params")
250                 }
251         }
252
253         if err := Sdl.Subscribe(NotificationCb, "channel1"); err != nil {
254                 t.Errorf("Error: Subscribe failed: %v", err)
255         }
256         time.Sleep(time.Duration(2) * time.Second)
257
258         if err := Sdl.StoreAndPublish("channel1", "event", "key1", "data1"); err != nil {
259                 t.Errorf("Error: Publish failed: %v", err)
260         }
261 }
262
263 func TestGetRicMessageSuccess(t *testing.T) {
264         Logger.Info("CASE: TestGetRicMessageSuccess")
265         id, ok := Rmr.GetRicMessageId("RIC_SUB_REQ")
266         if !ok || id != 12010 {
267                 t.Errorf("Error: GetRicMessageId failed: id=%d", id)
268         }
269
270         name := Rmr.GetRicMessageName(12010)
271         if name != "RIC_SUB_REQ" {
272                 t.Errorf("Error: GetRicMessageName failed: name=%s", name)
273         }
274 }
275
276 func TestGetRicMessageFails(t *testing.T) {
277         Logger.Info("CASE: TestGetRicMessageFails")
278         ok := Rmr.IsRetryError(&RMRParams{status: 0})
279         if ok {
280                 t.Errorf("Error: IsRetryError returned wrong value")
281         }
282
283         ok = Rmr.IsRetryError(&RMRParams{status: 10})
284         if !ok {
285                 t.Errorf("Error: IsRetryError returned wrong value")
286         }
287
288         ok = Rmr.IsNoEndPointError(&RMRParams{status: 5})
289         if ok {
290                 t.Errorf("Error: IsNoEndPointError returned wrong value")
291         }
292
293         ok = Rmr.IsNoEndPointError(&RMRParams{status: 2})
294         if !ok {
295                 t.Errorf("Error: IsNoEndPointError returned wrong value")
296         }
297 }
298
299 func TestIsErrorFunctions(t *testing.T) {
300         Logger.Info("CASE: TestIsErrorFunctions")
301         id, ok := Rmr.GetRicMessageId("RIC_SUB_REQ")
302         if !ok || id != 12010 {
303                 t.Errorf("Error: GetRicMessageId failed: id=%d", id)
304         }
305
306         name := Rmr.GetRicMessageName(12010)
307         if name != "RIC_SUB_REQ" {
308                 t.Errorf("Error: GetRicMessageName failed: name=%s", name)
309         }
310 }
311
312 func TestTeardown(t *testing.T) {
313         Logger.Info("CASE: TestTeardown")
314         Sdl.Clear()
315 }
316
317 // Helper functions
318 func executeRequest(req *http.Request) *httptest.ResponseRecorder {
319         rr := httptest.NewRecorder()
320         vars := map[string]string{"id": "1"}
321         req = mux.SetURLVars(req, vars)
322         Resource.router.ServeHTTP(rr, req)
323
324         return rr
325 }
326
327 func checkResponseCode(t *testing.T, expected, actual int) {
328         if expected != actual {
329                 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
330         }
331 }
332
333 func getMetrics(t *testing.T) string {
334         req, _ := http.NewRequest("GET", "/ric/v1/metrics", nil)
335         response := executeRequest(req)
336
337         return response.Body.String()
338 }