ca858eb32ed3658137699b4d59851c93393874cc
[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         "net/http"
25         "net/http/httptest"
26         "os"
27         "strings"
28         "testing"
29         "time"
30 )
31
32 var _ = func() bool {
33         testing.Init()
34         return true
35 }()
36
37 type Consumer struct {}
38
39 func (m Consumer) Consume(params *RMRParams) (err error) {
40         Sdl.Store("myKey", params.Payload)
41         return nil
42 }
43
44 // Test cases
45 func TestMain(m *testing.M) {
46         go Run(Consumer{})
47         time.Sleep(time.Duration(5) * time.Second)
48         code := m.Run()
49         os.Exit(code)
50 }
51
52 func TestGetHealthCheckRetursServiceUnavailableError(t *testing.T) {
53         req, _ := http.NewRequest("GET", "/ric/v1/health/ready", nil)
54         /*response :=*/ executeRequest(req)
55
56         //checkResponseCode(t, http.StatusServiceUnavailable, response.Code)
57 }
58
59 func TestGetHealthCheckReturnsSuccess(t *testing.T) {
60         for Rmr.IsReady() == false {
61                 time.Sleep(time.Duration(2) * time.Second)
62         }
63
64         req, _ := http.NewRequest("GET", "/ric/v1/health/ready", nil)
65         response := executeRequest(req)
66
67         checkResponseCode(t, http.StatusOK, response.Code)
68 }
69
70 func TestInjectQuerySinglePath(t *testing.T) {
71         var handler = func(w http.ResponseWriter, r *http.Request) {
72         }
73
74         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar")
75
76         req, _ := http.NewRequest("GET", "/ric/v1/user?foo=bar", nil)
77         response := executeRequest(req)
78         checkResponseCode(t, http.StatusOK, response.Code)
79 }
80
81 func TestInjectQueryMultiplePaths(t *testing.T) {
82         var handler = func(w http.ResponseWriter, r *http.Request) {
83         }
84
85         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar", "id", "mykey")
86
87         req, _ := http.NewRequest("GET", "/ric/v1/user?foo=bar&id=mykey", nil)
88         response := executeRequest(req)
89         checkResponseCode(t, http.StatusOK, response.Code)
90 }
91
92 func TestInjectQueryFailures(t *testing.T) {
93         var handler = func(w http.ResponseWriter, r *http.Request) {
94         }
95
96         Resource.InjectQueryRoute("/ric/v1/user", handler, "GET", "foo", "bar", "id", "mykey")
97
98         req, _ := http.NewRequest("GET", "/ric/v1/user?invalid=bar&no=mykey", nil)
99         response := executeRequest(req)
100         checkResponseCode(t, http.StatusNotFound, response.Code)
101 }
102
103 func TestMessagesReceivedSuccessfully(t *testing.T) {
104         for i := 0; i < 100; i++ {
105                 params := &RMRParams{}
106                 params.Mtype = 10004
107                 params.SubId = -1
108                 params.Payload = []byte{1, 2, 3, 4, 5, 6}
109                 params.Meid = &RMRMeid{PlmnID: "1234", EnbID: "7788", RanName: "RanName-1234"}
110                 params.Xid = "TestXID"
111                 Rmr.SendMsg(params)
112         }
113
114         // Allow time to process the messages
115         time.Sleep(time.Duration(2) * time.Second)
116
117         stats := getMetrics(t)
118         if !strings.Contains(stats, "ricxapp_RMR_Transmitted 100") {
119                 t.Errorf("Error: ricxapp_RMR_Transmitted value incorrect")
120         }
121
122         if !strings.Contains(stats, "ricxapp_RMR_Received 100") {
123                 t.Errorf("Error: ricxapp_RMR_Received value incorrect")
124         }
125
126         if !strings.Contains(stats, "ricxapp_RMR_TransmitError 0") {
127                 t.Errorf("Error: ricxapp_RMR_TransmitError value incorrect")
128         }
129
130         if !strings.Contains(stats, "ricxapp_RMR_ReceiveError 0") {
131                 t.Errorf("Error: ricxapp_RMR_ReceiveError value incorrect")
132         }
133
134         if !strings.Contains(stats, "ricxapp_SDL_Stored 100") {
135                 t.Errorf("Error: ricxapp_SDL_Stored value incorrect")
136         }
137
138         if !strings.Contains(stats, "ricxapp_SDL_StoreError 0") {
139                 t.Errorf("Error: ricxapp_SDL_StoreError value incorrect")
140         }
141 }
142
143 func TestSubscribeChannels(t *testing.T) {
144         var NotificationCb = func(ch string, events ...string) {
145                 if ch != "channel1" {
146                         t.Errorf("Error: Callback function called with incorrect params")
147                 }
148         }
149
150         if err := Sdl.Subscribe(NotificationCb, "channel1"); err != nil {
151                 t.Errorf("Error: Subscribe failed: %v", err)
152         }
153         time.Sleep(time.Duration(2) * time.Second)
154
155         if err := Sdl.StoreAndPublish("channel1", "event", "key1", "data1"); err != nil {
156                 t.Errorf("Error: Publish failed: %v", err)
157         }
158 }
159
160 func TestGetRicMessageSuccess(t *testing.T) {
161         id, ok := Rmr.GetRicMessageId("RIC_SUB_REQ")
162         if !ok || id != 12010 {
163                 t.Errorf("Error: GetRicMessageId failed: id=%d", id)
164         }
165
166         name := Rmr.GetRicMessageName(12010)
167         if name != "RIC_SUB_REQ" {
168                 t.Errorf("Error: GetRicMessageName failed: name=%s", name)
169         }
170 }
171
172 func TestGetRicMessageFails(t *testing.T) {
173         id, ok := Rmr.GetRicMessageId("INVALID")
174         if ok {
175                 t.Errorf("Error: GetRicMessageId returned invalid value id=%d", id)
176         }
177
178         name := Rmr.GetRicMessageName(123456)
179         if name != "" {
180                 t.Errorf("Error: GetRicMessageName returned invalid value: name=%s", name)
181         }
182 }
183
184 func TestTeardown(t *testing.T) {
185         Sdl.Clear()
186 }
187
188 // Helper functions
189 func executeRequest(req *http.Request) *httptest.ResponseRecorder {
190         rr := httptest.NewRecorder()
191         vars := map[string]string{"id": "1"}
192         req = mux.SetURLVars(req, vars)
193         Resource.router.ServeHTTP(rr, req)
194
195         return rr
196 }
197
198 func checkResponseCode(t *testing.T, expected, actual int) {
199         if expected != actual {
200                 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
201         }
202 }
203
204 func getMetrics(t *testing.T) string {
205         req, _ := http.NewRequest("GET", "/ric/v1/metrics", nil)
206         response := executeRequest(req)
207
208         return response.Body.String()
209 }