92835baf8fba229537efe7bf3858577762dd446f
[ric-plt/o1.git] / agent / pkg / nbi / nbi_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 nbi
21
22 import (
23         "encoding/json"
24         "fmt"
25         "github.com/stretchr/testify/assert"
26         "net"
27         "net/http"
28         "net/http/httptest"
29         "os"
30         "testing"
31         "time"
32
33         "errors"
34         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
35         apimodel "gerrit.oran-osc.org/r/ric-plt/o1mediator/pkg/appmgrmodel"
36         "gerrit.oran-osc.org/r/ric-plt/o1mediator/pkg/sbi"
37         "github.com/stretchr/testify/mock"
38 )
39
40 var XappConfig = `{
41         "o-ran-sc-ric-ueec-config-v1:ric": {
42           "config": {
43                 "name": "ueec",
44                 "namespace": "ricxapp",
45                 "control": {
46                   "active": true,
47                   "interfaceId": {
48                         "globalENBId": {
49                           "plmnId": "1234",
50                           "eNBId": "55"
51                         }
52                   }
53                 }
54           }
55         }
56   }`
57
58 var XappDescriptor = `{
59         "o-ran-sc-ric-xapp-desc-v1:ric": {
60           "xapps": {
61                 "xapp": [
62                   {
63                         "name": "ueec",
64                         "release-name": "ueec-xapp",
65                         "version": "0.0.1",
66                         "namespace": "ricxapp"
67                   }
68                 ]
69           }
70         }
71   }`
72
73 var n *Nbi
74 var rnibM *rnibMock
75
76 // Test cases
77 func TestMain(M *testing.M) {
78         rnibM = new(rnibMock)
79         rnib = rnibM
80         n = NewNbi(sbi.NewSBIClient("localhost:8080", "localhost:9093", 5))
81         go n.Start()
82         time.Sleep(time.Duration(1) * time.Second)
83
84         os.Exit(M.Run())
85 }
86
87 func TestModifyConfigmap(t *testing.T) {
88         ts := CreateHTTPServer(t, "PUT", "/ric/v1/config", 8080, http.StatusOK, apimodel.ConfigValidationErrors{})
89         defer ts.Close()
90
91         var f interface{}
92         err := json.Unmarshal([]byte(XappConfig), &f)
93         assert.Equal(t, true, err == nil)
94
95         err = n.ManageConfigmaps("o-ran-sc-ric-ueec-config-v1", XappConfig, 1)
96         assert.Equal(t, true, err == nil)
97 }
98
99 func TestXappDescModuleChangeCB(t *testing.T) {
100         ok := n.testModuleChangeCB("o-ran-sc-ric-xapp-desc-v1")
101         assert.True(t, ok)
102 }
103
104 func TestUeecConfigModuleChangeCB(t *testing.T) {
105         ok := n.testModuleChangeCB("o-ran-sc-ric-ueec-config-v1")
106         assert.True(t, ok)
107 }
108
109 func TestUeecConfigDoneModuleChangeCB(t *testing.T) {
110         ok := n.testModuleChangeCBDone("o-ran-sc-ric-ueec-config-v1")
111         assert.True(t, ok)
112 }
113
114 func TestXappDescGnbStateCB(t *testing.T) {
115         ok := n.testGnbStateCB("o-ran-sc-ric-xapp-desc-v1")
116         assert.True(t, ok)
117 }
118
119 func TestAlarmGnbStateCB(t *testing.T) {
120         ok := n.testGnbStateCB("o-ran-sc-ric-alarm-v1")
121         assert.True(t, ok)
122 }
123
124 func TestGnbStateCB(t *testing.T) {
125         var rnibOk xapp.RNIBIRNibError
126         var gNbIDs []*xapp.RNIBNbIdentity
127         gNbID := xapp.RNIBNbIdentity{
128                 InventoryName: "test-gnb",
129         }
130         gNbIDs = append(gNbIDs, &gNbID)
131         nodeInfo := xapp.RNIBNodebInfo{}
132
133         rnibM.On("GetListGnbIds").Return(gNbIDs, rnibOk).Once()
134         rnibM.On("GetNodeb", mock.Anything).Return(&nodeInfo, rnibOk).Once()
135         ok := n.testGnbStateCB("")
136         assert.True(t, ok)
137 }
138
139 func TestGnbStateCBWhenRnibGetListGnbIdsFails(t *testing.T) {
140         var rnibErr xapp.RNIBIRNibError = errors.New("Some RNIB Error")
141
142         rnibM.On("GetListGnbIds").Return(nil, rnibErr).Once()
143         ok := n.testGnbStateCB("")
144         assert.True(t, ok)
145 }
146
147 func TestGnbStateCBWhenRnibGetNodebFails(t *testing.T) {
148         var rnibOk xapp.RNIBIRNibError
149         var rnibErr xapp.RNIBIRNibError = errors.New("Some RNIB Error")
150         var gNbIDs []*xapp.RNIBNbIdentity
151         gNbID := xapp.RNIBNbIdentity{
152                 InventoryName: "test-gnb",
153         }
154         gNbIDs = append(gNbIDs, &gNbID)
155
156         rnibM.On("GetListGnbIds").Return(gNbIDs, rnibOk).Once()
157         rnibM.On("GetNodeb", mock.Anything).Return(nil, rnibErr).Once()
158         ok := n.testGnbStateCB("")
159         assert.True(t, ok)
160 }
161
162 func TestDeployXApp(t *testing.T) {
163         ts := CreateHTTPServer(t, "POST", "/ric/v1/xapps", 8080, http.StatusCreated, apimodel.Xapp{})
164         defer ts.Close()
165
166         var f interface{}
167         err := json.Unmarshal([]byte(XappDescriptor), &f)
168         assert.Equal(t, true, err == nil)
169
170         err = n.ManageXapps("o-ran-sc-ric-xapp-desc-v1", XappDescriptor, 0)
171         assert.Equal(t, true, err == nil)
172 }
173
174 func TestUnDeployXApp(t *testing.T) {
175         ts := CreateHTTPServer(t, "DELETE", "/ric/v1/xapps/ueec-xapp", 8080, http.StatusNoContent, apimodel.Xapp{})
176         defer ts.Close()
177
178         var f interface{}
179         err := json.Unmarshal([]byte(XappDescriptor), &f)
180         assert.Equal(t, true, err == nil)
181
182         err = n.ManageXapps("o-ran-sc-ric-xapp-desc-v1", XappDescriptor, 2)
183         assert.Equal(t, true, err == nil)
184 }
185
186 func TestGetDeployedXapps(t *testing.T) {
187         ts := CreateHTTPServer(t, "GET", "/ric/v1/xapps", 8080, http.StatusOK, apimodel.AllDeployedXapps{})
188         defer ts.Close()
189
190         err := sbiClient.GetDeployedXapps()
191         assert.Equal(t, true, err == nil)
192 }
193
194 func TestErrorCases(t *testing.T) {
195         // Invalid config
196         err := n.ManageXapps("o-ran-sc-ric-xapp-desc-v1", "", 2)
197         assert.Equal(t, true, err == nil)
198
199         // Invalid module
200         err = n.ManageXapps("", "{}", 2)
201         assert.Equal(t, true, err == nil)
202
203         // Unexpected module
204         err = n.ManageXapps("o-ran-sc-ric-ueec-config-v1", "{}", 2)
205         assert.Equal(t, true, err == nil)
206
207         // Invalid operation
208         err = n.ManageXapps("o-ran-sc-ric-ueec-config-v1", XappDescriptor, 1)
209         assert.Equal(t, true, err == nil)
210
211         // Invalid config
212         err = n.ManageConfigmaps("o-ran-sc-ric-ueec-config-v1", "", 1)
213         assert.Equal(t, true, err == nil)
214
215         // Invalid operation
216         err = n.ManageConfigmaps("o-ran-sc-ric-ueec-config-v1", "{}", 0)
217         assert.Equal(t, true, err != nil)
218 }
219
220 func TestConnStatus2Str(t *testing.T) {
221         assert.Equal(t, n.ConnStatus2Str(0), "not-specified")
222         assert.Equal(t, n.ConnStatus2Str(1), "connected")
223         assert.Equal(t, n.ConnStatus2Str(2), "disconnected")
224         assert.Equal(t, n.ConnStatus2Str(3), "setup-failed")
225         assert.Equal(t, n.ConnStatus2Str(4), "connecting")
226         assert.Equal(t, n.ConnStatus2Str(5), "shutting-down")
227         assert.Equal(t, n.ConnStatus2Str(6), "shutdown")
228         assert.Equal(t, n.ConnStatus2Str(1234), "not-specified")
229 }
230
231 func TestE2APProt2Str(t *testing.T) {
232         assert.Equal(t, n.E2APProt2Str(0), "not-specified")
233         assert.Equal(t, n.E2APProt2Str(1), "x2-setup-request")
234         assert.Equal(t, n.E2APProt2Str(2), "endc-x2-setup-request")
235         assert.Equal(t, n.E2APProt2Str(1111), "not-specified")
236 }
237
238 func TestNodeType2Str(t *testing.T) {
239         assert.Equal(t, n.NodeType2Str(0), "not-specified")
240         assert.Equal(t, n.NodeType2Str(1), "enb")
241         assert.Equal(t, n.NodeType2Str(2), "gnb")
242         assert.Equal(t, n.NodeType2Str(1111), "not-specified")
243 }
244
245 func TestTeardown(t *testing.T) {
246         n.Stop()
247 }
248
249 func CreateHTTPServer(t *testing.T, method, url string, port, status int, respData interface{}) *httptest.Server {
250         l, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
251         if err != nil {
252                 t.Error("Failed to create listener: " + err.Error())
253         }
254         ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
255                 assert.Equal(t, r.Method, method)
256                 assert.Equal(t, r.URL.String(), url)
257                 w.Header().Add("Content-Type", "application/json")
258                 w.WriteHeader(status)
259                 b, _ := json.Marshal(respData)
260                 w.Write(b)
261         }))
262         ts.Listener.Close()
263         ts.Listener = l
264
265         ts.Start()
266
267         return ts
268 }
269
270 func DescMatcher(result, expected *apimodel.XappDescriptor) bool {
271         if *result.XappName == *expected.XappName && result.HelmVersion == expected.HelmVersion &&
272                 result.Namespace == expected.Namespace && result.ReleaseName == expected.ReleaseName {
273                 return true
274         }
275         return false
276 }
277
278 func ConfigMatcher(result, expected *apimodel.XAppConfig) bool {
279         if *result.Metadata.XappName == *expected.Metadata.XappName &&
280                 *result.Metadata.Namespace == *expected.Metadata.Namespace {
281                 return true
282         }
283         return false
284 }
285
286 type rnibMock struct {
287         mock.Mock
288 }
289
290 func (m *rnibMock) GetListGnbIds() ([]*xapp.RNIBNbIdentity, xapp.RNIBIRNibError) {
291         a := m.Called()
292         if a.Get(0) == nil {
293                 return nil, a.Error(1)
294         }
295         return a.Get(0).([]*xapp.RNIBNbIdentity), a.Error(1)
296 }
297
298 func (m *rnibMock) GetNodeb(invName string) (*xapp.RNIBNodebInfo, xapp.RNIBIRNibError) {
299         a := m.Called(invName)
300         if a.Get(0) == nil {
301                 return nil, a.Error(1)
302         }
303         return a.Get(0).(*xapp.RNIBNodebInfo), a.Error(1)
304 }