Multiple E2T instance feature - Introduced APIs Delete E2T Instance and associate...
[ric-plt/rtmgr.git] / pkg / nbi / httprestful_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    This source code is part of the near-RT RIC (RAN Intelligent Controller)
20    platform project (RICP).
21
22 ==================================================================================
23 */
24 /*
25   Mnemonic:     httprestful_test.go
26   Abstract:     HTTPRestful unit tests
27   Date:         15 May 2019
28 */
29
30 package nbi
31
32 import (
33         "encoding/json"
34         "fmt"
35         "io/ioutil"
36         "net"
37         "net/http"
38         "net/http/httptest"
39         "os"
40         "routing-manager/pkg/models"
41         "routing-manager/pkg/rpe"
42         "routing-manager/pkg/rtmgr"
43         "routing-manager/pkg/sdl"
44         "routing-manager/pkg/stub"
45         "testing"
46         "time"
47         "sync"
48
49         "github.com/go-openapi/swag"
50 )
51
52 var BasicXAppLists = []byte(`[
53  {
54  "name":"xapp-01","status":"unknown","version":"1.2.3",
55     "instances":[
56         {"name":"xapp-01-instance-01","status":"pending","ip":"172.16.1.103","port":4555,
57             "txMessages":["ControlIndication"],
58             "rxMessages":["LoadIndication","Reset"]
59         },
60         {"name":"xapp-01-instance-02","status":"pending","ip":"10.244.1.12","port":4561,
61             "txMessages":["ControlIndication","SNStatusTransfer"],
62             "rxMessages":["LoadIndication","HandoverPreparation"]
63         }
64     ]
65 }
66 ]`)
67
68 var SubscriptionResp = []byte(`{"ID":"deadbeef1234567890", "Version":0, "EventType":"all"}`)
69
70 var InvalidSubResp = []byte(`{"Version":0, "EventType":all}`)
71
72 func TestValidateXappCallbackData_1(t *testing.T) {
73         data := models.XappCallbackData{
74                 XApps:   *swag.String("[]"),
75                 Version: *swag.Int64(1),
76                 Event:   *swag.String("someevent"),
77                 ID:      *swag.String("123456")}
78
79         err := validateXappCallbackData(&data)
80         if err != nil {
81                 t.Error("Invalid XApp callback data: " + err.Error())
82         }
83 }
84
85 func TestValidateXappSubscriptionsData(t *testing.T) {
86
87         ep := make(map[string]*rtmgr.Endpoint)
88         ep["dummy"] = &rtmgr.Endpoint{Uuid: "10.0.0.1:0", Name: "E2TERM", XAppType: "app1", Ip: "", Port: 0, TxMessages: []string{"", ""}, RxMessages: []string{"", ""}, Socket: nil, IsReady: true, Keepalive: true}
89         p := uint16(1234)
90         data := models.XappSubscriptionData{
91                 Address:        swag.String("10.1.1.1"),
92                 Port:           &p,
93                 SubscriptionID: swag.Int32(123456)}
94
95         var err error
96         err = validateXappSubscriptionData(&data)
97         t.Log(err)
98
99         rtmgr.Eps = ep
100         p = uint16(0)
101         data1 := models.XappSubscriptionData{
102                 Address:        swag.String(""),
103                 Port:           &p,
104                 SubscriptionID: swag.Int32(123456)}
105         err = validateXappSubscriptionData(&data1)
106         t.Log(err)
107
108         //Validate E2tData
109         data2 := models.E2tData{
110                 E2TAddress: swag.String(""),
111         }
112         err = validateE2tData(&data2)
113
114         e2tchannel := make(chan *models.E2tData, 10)
115         _ = createNewE2tHandleHandlerImpl(e2tchannel, &data2)
116         defer close(e2tchannel)
117
118         //test case for provideXappSubscriptionHandleImp
119         datachannel := make(chan *models.XappSubscriptionData, 10)
120         _ = provideXappSubscriptionHandleImpl(datachannel, &data1)
121         defer close(datachannel)
122
123         //test case for deleteXappSubscriptionHandleImpl
124         _ = deleteXappSubscriptionHandleImpl(datachannel, &data1)
125 }
126
127 func TestvalidateE2tData(t *testing.T) {
128         data := models.E2tData{
129                 E2TAddress: swag.String(""),
130         }
131         err := validateE2tData(&data)
132         t.Log(err)
133 }
134
135 func TestSubscriptionExists(t *testing.T) {
136         p := uint16(0)
137         data := models.XappSubscriptionData{
138                 Address:        swag.String("10.0.0.0"),
139                 Port:           &p,
140                 SubscriptionID: swag.Int32(1234)}
141
142         rtmgr.Subs = *stub.ValidSubscriptions
143
144         yes_no := subscriptionExists(&data)
145         yes_no = addSubscription(&rtmgr.Subs, &data)
146         yes_no = addSubscription(&rtmgr.Subs, &data)
147         yes_no = delSubscription(&rtmgr.Subs, &data)
148         yes_no = delSubscription(&rtmgr.Subs, &data)
149         t.Log(yes_no)
150 }
151
152 func TestaddSubscriptions(t *testing.T) {
153         p := uint16(1)
154         subdata := models.XappSubscriptionData{
155                 Address:        swag.String("10.0.0.0"),
156                 Port:           &p,
157                 SubscriptionID: swag.Int32(1234)}
158
159         rtmgr.Subs = *stub.ValidSubscriptions
160         yes_no := addSubscription(&rtmgr.Subs, &subdata)
161         t.Log(yes_no)
162 }
163
164 func TestHttpInstance(t *testing.T) {
165         sdlEngine, _ := sdl.GetSdl("file")
166         rpeEngine, _ := rpe.GetRpe("rmrpush")
167         httpinstance := NewHttpRestful()
168         err := httpinstance.Terminate()
169         t.Log(err)
170
171         triggerSBI := make(chan bool)
172         createMockPlatformComponents()
173         //ts := createMockAppmgrWithData("127.0.0.1:3000", BasicXAppLists, nil)
174         //ts.Start()
175         //defer ts.Close()
176         var m sync.Mutex
177         err = httpinstance.Initialize(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine, rpeEngine, triggerSBI, &m)
178 }
179
180 func TestXappCallbackDataChannelwithdata(t *testing.T) {
181         data := models.XappCallbackData{
182                 XApps:   *swag.String("[]"),
183                 Version: *swag.Int64(1),
184                 Event:   *swag.String("someevent"),
185                 ID:      *swag.String("123456")}
186         datach := make(chan *models.XappCallbackData, 1)
187         go func() { _, _ = recvXappCallbackData(datach) }()
188         defer close(datach)
189         datach <- &data
190 }
191 func TestXappCallbackDataChannelNodata(t *testing.T) {
192         datach := make(chan *models.XappCallbackData, 1)
193         go func() { _, _ = recvXappCallbackData(datach) }()
194         defer close(datach)
195 }
196
197 func TestE2TChannelwithData(t *testing.T) {
198         data2 := models.E2tData{
199                 E2TAddress: swag.String(""),
200         }
201         dataChannel := make(chan *models.E2tData, 10)
202         go func() { _, _ = recvNewE2Tdata(dataChannel) }()
203         defer close(dataChannel)
204         dataChannel <- &data2
205 }
206
207 func TestE2TChannelwithNoData(t *testing.T) {
208         dataChannel := make(chan *models.E2tData, 10)
209         go func() { _, _ = recvNewE2Tdata(dataChannel) }()
210         defer close(dataChannel)
211 }
212
213 func TestprovideXappSubscriptionHandleImpl(t *testing.T) {
214         p := uint16(0)
215         data := models.XappSubscriptionData{
216                 Address:        swag.String("10.0.0.0"),
217                 Port:           &p,
218                 SubscriptionID: swag.Int32(1234)}
219         datachannel := make(chan *models.XappSubscriptionData, 10)
220         go func() { _ = provideXappSubscriptionHandleImpl(datachannel, &data) }()
221         defer close(datachannel)
222         datachannel <- &data
223
224         //subdel test
225 }
226
227 func TestdeleteXappSubscriptionHandleImpl(t *testing.T) {
228         p := uint16(1)
229         subdeldata := models.XappSubscriptionData{
230                 Address:        swag.String("10.0.0.0"),
231                 Port:           &p,
232                 SubscriptionID: swag.Int32(1234)}
233         subdelchannel := make(chan *models.XappSubscriptionData, 10)
234         go func() { _ = deleteXappSubscriptionHandleImpl(subdelchannel, &subdeldata) }()
235         defer close(subdelchannel)
236         subdelchannel <- &subdeldata
237 }
238
239 func createMockAppmgrWithData(url string, g []byte, p []byte) *httptest.Server {
240         l, err := net.Listen("tcp", url)
241         if err != nil {
242                 fmt.Println("Failed to create listener: " + err.Error())
243         }
244         ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
245                 if r.Method == "GET" && r.URL.String() == "/ric/v1/xapps" {
246                         w.Header().Add("Content-Type", "application/json")
247                         w.WriteHeader(http.StatusOK)
248                         w.Write(g)
249                 }
250                 if r.Method == "POST" && r.URL.String() == "/ric/v1/subscriptions" {
251                         w.Header().Add("Content-Type", "application/json")
252                         w.WriteHeader(http.StatusCreated)
253                         w.Write(p)
254                 }
255
256         }))
257         ts.Listener.Close()
258         ts.Listener = l
259         return ts
260 }
261
262 func createMockPlatformComponents() {
263         var filename = "config.json"
264         file, _ := json.MarshalIndent(stub.ValidPlatformComponents, "", "")
265         filestr := string(file)
266         filestr = "{\"PlatformComponents\":" + filestr + "}"
267         file = []byte(filestr)
268         _ = ioutil.WriteFile(filename, file, 644)
269 }
270
271 func TestRecvXappCallbackData(t *testing.T) {
272         data := models.XappCallbackData{
273                 XApps:   *swag.String("[]"),
274                 Version: *swag.Int64(1),
275                 Event:   *swag.String("any"),
276                 ID:      *swag.String("123456"),
277         }
278
279         ch := make(chan *models.XappCallbackData)
280         defer close(ch)
281         httpRestful := NewHttpRestful()
282         go func() { ch <- &data }()
283         time.Sleep(1 * time.Second)
284         t.Log(string(len(ch)))
285         xappList, err := httpRestful.RecvXappCallbackData(ch)
286         if err != nil {
287                 t.Error("Receive failed: " + err.Error())
288         } else {
289                 if xappList == nil {
290                         t.Error("Expected an XApp notification list")
291                 } else {
292                         t.Log("whatever")
293                 }
294         }
295 }
296
297 func TestProvideXappHandleHandlerImpl(t *testing.T) {
298         datach := make(chan *models.XappCallbackData, 10)
299         defer close(datach)
300         data := models.XappCallbackData{
301                 XApps:   *swag.String("[]"),
302                 Version: *swag.Int64(1),
303                 Event:   *swag.String("someevent"),
304                 ID:      *swag.String("123456")}
305         var httpRestful, _ = GetNbi("httpRESTful")
306         err := httpRestful.(*HttpRestful).ProvideXappHandleHandlerImpl(datach, &data)
307         if err != nil {
308                 t.Error("Error occured: " + err.Error())
309         } else {
310                 recv := <-datach
311                 if recv == nil {
312                         t.Error("Something gone wrong: " + err.Error())
313                 } else {
314                         if recv != &data {
315                                 t.Error("Malformed data on channel")
316                         }
317                 }
318         }
319 }
320
321 func TestValidateXappCallbackData(t *testing.T) {
322         data := models.XappCallbackData{
323                 XApps:   *swag.String("[]"),
324                 Version: *swag.Int64(1),
325                 Event:   *swag.String("someevent"),
326                 ID:      *swag.String("123456")}
327
328         err := validateXappCallbackData(&data)
329         if err != nil {
330                 t.Error("Invalid XApp callback data: " + err.Error())
331         }
332 }
333
334 func TestValidateXappCallbackDataWithInvalidData(t *testing.T) {
335         data := models.XappCallbackData{
336                 XApps:   *swag.String("{}"),
337                 Version: *swag.Int64(1),
338                 Event:   *swag.String("someevent"),
339                 ID:      *swag.String("123456")}
340
341         err := validateXappCallbackData(&data)
342         if err == nil {
343                 t.Error("Invalid XApp callback data: " + err.Error())
344         }
345 }
346
347 func TestHttpGetXAppsInvalidData(t *testing.T) {
348         _, err := httpGetXApps(XMURL)
349         if err == nil {
350                 t.Error("No XApp data received: " + err.Error())
351         }
352 }
353
354 func TestHttpGetXAppsWithValidData(t *testing.T) {
355         var expected = 1
356         ts := createMockAppmgrWithData("127.0.0.1:3000", BasicXAppLists, nil)
357
358         ts.Start()
359         defer ts.Close()
360         xapplist, err := httpGetXApps(XMURL)
361         if err != nil {
362                 t.Error("Error occured: " + err.Error())
363         } else {
364                 if len(*xapplist) != expected {
365                         t.Error("Invalid XApp data: got " + string(len(*xapplist)) + ", expected " + string(expected))
366                 }
367         }
368 }
369 func TestRetrieveStartupDataTimeout(t *testing.T) {
370         sdlEngine, _ := sdl.GetSdl("file")
371         createMockPlatformComponents()
372         err := retrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
373         if err == nil {
374                 t.Error("Cannot retrieve startup data: " + err.Error())
375         }
376         os.Remove("rt.json")
377         os.Remove("config.json")
378 }
379
380 func TestRetrieveStartupData(t *testing.T) {
381         ts := createMockAppmgrWithData("127.0.0.1:3000", BasicXAppLists, SubscriptionResp)
382         ts.Start()
383         defer ts.Close()
384         sdlEngine, _ := sdl.GetSdl("file")
385         var httpRestful, _ = GetNbi("httpRESTful")
386         createMockPlatformComponents()
387         err := httpRestful.(*HttpRestful).RetrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
388         //err := retrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
389         if err != nil {
390                 t.Error("Cannot retrieve startup data: " + err.Error())
391         }
392         os.Remove("rt.json")
393         os.Remove("config.json")
394 }
395
396 func TestRetrieveStartupDataWithInvalidSubResp(t *testing.T) {
397         ts := createMockAppmgrWithData("127.0.0.1:3000", BasicXAppLists, InvalidSubResp)
398         ts.Start()
399         defer ts.Close()
400         sdlEngine, _ := sdl.GetSdl("file")
401         var httpRestful, _ = GetNbi("httpRESTful")
402         createMockPlatformComponents()
403         err := httpRestful.(*HttpRestful).RetrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
404         if err == nil {
405                 t.Error("Cannot retrieve startup data: " + err.Error())
406         }
407         os.Remove("rt.json")
408         os.Remove("config.json")
409 }
410
411 func TestrecvXappCallbackData(t *testing.T) {
412         data := models.E2tData{
413                 E2TAddress: swag.String("123456")}
414
415         var err error
416
417         e2tch := make(chan *models.E2tData)
418         go func() { e2tch <- &data }()
419         time.Sleep(1 * time.Second)
420         t.Log(string(len(e2tch)))
421         defer close(e2tch)
422
423         var httpRestful, _ = GetNbi("httpRESTful")
424         _, err = httpRestful.(*HttpRestful).RecvNewE2Tdata(e2tch)
425         t.Log(err)
426 }