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