Initial version
[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, len int, payload []byte) (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, 100, []byte{1, 2, 3, 4, 5, 6})
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 TestGetgNBList(t *testing.T) {
136         Rnib.Store("Kiikale", "Hello")
137         Rnib.Store("mykey", "myval")
138
139         v, _ := Rnib.GetgNBList()
140         if v["Kiikale"] != "Hello" || v["mykey"] != "myval" {
141                 t.Errorf("Error: GetgNBList failed!")
142         }
143 }
144
145 func TestSubscribeChannels(t *testing.T) {
146         var NotificationCb = func(ch string, events ...string) {
147                 if ch != "channel1" {
148                         t.Errorf("Error: Callback function called with incorrect params")
149                 }
150         }
151
152         if err := Sdl.Subscribe(NotificationCb, "channel1"); err != nil {
153                 t.Errorf("Error: Subscribe failed: %v", err)
154         }
155         time.Sleep(time.Duration(2) * time.Second)
156
157         if err := Sdl.StoreAndPublish("channel1", "event", "key1", "data1"); err != nil {
158                 t.Errorf("Error: Publish failed: %v", err)
159         }
160 }
161
162 func TestTeardown(t *testing.T) {
163         Sdl.Clear()
164         Rnib.Clear()
165 }
166
167 // Helper functions
168 func executeRequest(req *http.Request) *httptest.ResponseRecorder {
169         rr := httptest.NewRecorder()
170         vars := map[string]string{"id": "1"}
171         req = mux.SetURLVars(req, vars)
172         Resource.router.ServeHTTP(rr, req)
173
174         return rr
175 }
176
177 func checkResponseCode(t *testing.T, expected, actual int) {
178         if expected != actual {
179                 t.Errorf("Expected response code %d. Got %d\n", expected, actual)
180         }
181 }
182
183 func getMetrics(t *testing.T) string {
184         req, _ := http.NewRequest("GET", "/ric/v1/metrics", nil)
185         response := executeRequest(req)
186
187         return response.Body.String()
188 }