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