27fb44514c67ead3340685f9df5445e1d9af8339
[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         req, _ := http.NewRequest("GET", "/ric/v1/health/ready", nil)
55         /*response :=*/ executeRequest(req)
56
57         //checkResponseCode(t, http.StatusServiceUnavailable, response.Code)
58 }
59
60 func TestGetHealthCheckReturnsSuccess(t *testing.T) {
61         for Rmr.IsReady() == false {
62                 time.Sleep(time.Duration(2) * time.Second)
63         }
64
65         req, _ := http.NewRequest("GET", "/ric/v1/health/ready", nil)
66         response := executeRequest(req)
67
68         checkResponseCode(t, http.StatusOK, response.Code)
69 }
70
71 func TestInjectQuerySinglePath(t *testing.T) {
72         var handler = func(w http.ResponseWriter, r *http.Request) {
73         }
74
75         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar")
76
77         req, _ := http.NewRequest("GET", "/ric/v1/user?foo=bar", nil)
78         response := executeRequest(req)
79         checkResponseCode(t, http.StatusOK, response.Code)
80 }
81
82 func TestInjectQueryMultiplePaths(t *testing.T) {
83         var handler = func(w http.ResponseWriter, r *http.Request) {
84         }
85
86         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar", "id", "mykey")
87
88         req, _ := http.NewRequest("GET", "/ric/v1/user?foo=bar&id=mykey", nil)
89         response := executeRequest(req)
90         checkResponseCode(t, http.StatusOK, response.Code)
91 }
92
93 func TestInjectQueryFailures(t *testing.T) {
94         var handler = func(w http.ResponseWriter, r *http.Request) {
95         }
96
97         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar", "id", "mykey")
98
99         req, _ := http.NewRequest("GET", "/ric/v1/user?invalid=bar&no=mykey", nil)
100         response := executeRequest(req)
101         checkResponseCode(t, http.StatusNotFound, response.Code)
102 }
103
104 func TestMessagesReceivedSuccessfully(t *testing.T) {
105         for i := 0; i < 100; i++ {
106                 params := &RMRParams{}
107                 params.Mtype = 10004
108                 params.SubId = -1
109                 params.Payload = []byte{1, 2, 3, 4, 5, 6}
110                 params.Meid = &RMRMeid{PlmnID: "1234", EnbID: "7788", RanName: "RanName-1234"}
111                 params.Xid = "TestXID"
112                 Rmr.SendMsg(params)
113         }
114
115         // Allow time to process the messages
116         time.Sleep(time.Duration(2) * time.Second)
117
118         waitForSdl := viper.GetBool("db.waitForSdl")
119         stats := getMetrics(t)
120         if !strings.Contains(stats, "ricxapp_RMR_Transmitted 100") {
121                 t.Errorf("Error: ricxapp_RMR_Transmitted value incorrect")
122         }
123
124         if !strings.Contains(stats, "ricxapp_RMR_Received 100") {
125                 t.Errorf("Error: ricxapp_RMR_Received value incorrect")
126         }
127
128         if !strings.Contains(stats, "ricxapp_RMR_TransmitError 0") {
129                 t.Errorf("Error: ricxapp_RMR_TransmitError value incorrect")
130         }
131
132         if !strings.Contains(stats, "ricxapp_RMR_ReceiveError 0") {
133                 t.Errorf("Error: ricxapp_RMR_ReceiveError value incorrect")
134         }
135
136         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_Stored 100") {
137                 t.Errorf("Error: ricxapp_SDL_Stored value incorrect")
138         }
139
140         if waitForSdl && !strings.Contains(stats, "ricxapp_SDL_StoreError 0") {
141                 t.Errorf("Error: ricxapp_SDL_StoreError value incorrect")
142         }
143 }
144
145 func TestSubscribeChannels(t *testing.T) {
146         if !viper.GetBool("db.waitForSdl") {
147                 return
148         }
149
150         var NotificationCb = func(ch string, events ...string) {
151                 if ch != "channel1" {
152                         t.Errorf("Error: Callback function called with incorrect params")
153                 }
154         }
155
156         if err := Sdl.Subscribe(NotificationCb, "channel1"); err != nil {
157                 t.Errorf("Error: Subscribe failed: %v", err)
158         }
159         time.Sleep(time.Duration(2) * time.Second)
160
161         if err := Sdl.StoreAndPublish("channel1", "event", "key1", "data1"); err != nil {
162                 t.Errorf("Error: Publish failed: %v", err)
163         }
164 }
165
166 func TestGetRicMessageSuccess(t *testing.T) {
167         id, ok := Rmr.GetRicMessageId("RIC_SUB_REQ")
168         if !ok || id != 12010 {
169                 t.Errorf("Error: GetRicMessageId failed: id=%d", id)
170         }
171
172         name := Rmr.GetRicMessageName(12010)
173         if name != "RIC_SUB_REQ" {
174                 t.Errorf("Error: GetRicMessageName failed: name=%s", name)
175         }
176 }
177
178 func TestGetRicMessageFails(t *testing.T) {
179         ok := Rmr.IsRetryError(&RMRParams{status: 0})
180         if ok {
181                 t.Errorf("Error: IsRetryError returned wrong value")
182         }
183
184         ok = Rmr.IsRetryError(&RMRParams{status: 10})
185         if !ok {
186                 t.Errorf("Error: IsRetryError returned wrong value")
187         }
188
189         ok = Rmr.IsNoEndPointError(&RMRParams{status: 5})
190         if ok {
191                 t.Errorf("Error: IsNoEndPointError returned wrong value")
192         }
193
194         ok = Rmr.IsNoEndPointError(&RMRParams{status: 2})
195         if !ok {
196                 t.Errorf("Error: IsNoEndPointError returned wrong value")
197         }
198 }
199
200 func TestIsErrorFunctions(t *testing.T) {
201         id, ok := Rmr.GetRicMessageId("RIC_SUB_REQ")
202         if !ok || id != 12010 {
203                 t.Errorf("Error: GetRicMessageId failed: id=%d", id)
204         }
205
206         name := Rmr.GetRicMessageName(12010)
207         if name != "RIC_SUB_REQ" {
208                 t.Errorf("Error: GetRicMessageName failed: name=%s", name)
209         }
210 }
211
212 func TestTeardown(t *testing.T) {
213         Sdl.Clear()
214 }
215
216 // Helper functions
217 func executeRequest(req *http.Request) *httptest.ResponseRecorder {
218         rr := httptest.NewRecorder()
219         vars := map[string]string{"id": "1"}
220         req = mux.SetURLVars(req, vars)
221         Resource.router.ServeHTTP(rr, req)
222
223         return rr
224 }
225
226 func checkResponseCode(t *testing.T, expected, actual int) {
227         if expected != actual {
228                 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
229         }
230 }
231
232 func getMetrics(t *testing.T) string {
233         req, _ := http.NewRequest("GET", "/ric/v1/metrics", nil)
234         response := executeRequest(req)
235
236         return response.Body.String()
237 }