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