Adding scope of RICPlatform that are under Apache License
[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/sdl"
42         "routing-manager/pkg/stub"
43         "testing"
44         "time"
45
46         "github.com/go-openapi/swag"
47 )
48
49 var BasicXAppLists = []byte(`[
50  {
51  "name":"xapp-01","status":"unknown","version":"1.2.3",
52     "instances":[
53         {"name":"xapp-01-instance-01","status":"pending","ip":"172.16.1.103","port":4555,
54             "txMessages":["ControlIndication"],
55             "rxMessages":["LoadIndication","Reset"]
56         },
57         {"name":"xapp-01-instance-02","status":"pending","ip":"10.244.1.12","port":4561,
58             "txMessages":["ControlIndication","SNStatusTransfer"],
59             "rxMessages":["LoadIndication","HandoverPreparation"]
60         }
61     ]
62 }
63 ]`)
64
65 var SubscriptionResp = []byte(`{"ID":"deadbeef1234567890", "Version":0, "EventType":"all"}`)
66
67 var InvalidSubResp = []byte(`{"Version":0, "EventType":all}`)
68
69 func createMockAppmgrWithData(url string, g []byte, p []byte) *httptest.Server {
70         l, err := net.Listen("tcp", url)
71         if err != nil {
72                 fmt.Println("Failed to create listener: " + err.Error())
73         }
74         ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
75                 if r.Method == "GET" && r.URL.String() == "/ric/v1/xapps" {
76                         w.Header().Add("Content-Type", "application/json")
77                         w.WriteHeader(http.StatusOK)
78                         w.Write(g)
79                 }
80                 if r.Method == "POST" && r.URL.String() == "/ric/v1/subscriptions" {
81                         w.Header().Add("Content-Type", "application/json")
82                         w.WriteHeader(http.StatusCreated)
83                         w.Write(p)
84                 }
85
86         }))
87         ts.Listener.Close()
88         ts.Listener = l
89         return ts
90 }
91
92 func createMockPlatformComponents() {
93         var filename = "config.json"
94         file, _ := json.MarshalIndent(stub.ValidPlatformComponents, "", "")
95         filestr := string(file)
96         filestr = "{\"PlatformComponents\":" + filestr + "}"
97         file = []byte(filestr)
98         _ = ioutil.WriteFile(filename, file, 644)
99 }
100
101 func TestRecvXappCallbackData(t *testing.T) {
102         data := models.XappCallbackData{
103                 XApps:   *swag.String("[]"),
104                 Version: *swag.Int64(1),
105                 Event:   *swag.String("any"),
106                 ID:      *swag.String("123456"),
107         }
108
109         ch := make(chan *models.XappCallbackData)
110         defer close(ch)
111         httpRestful := NewHttpRestful()
112         go func() { ch <- &data }()
113         time.Sleep(1 * time.Second)
114         t.Log(string(len(ch)))
115         xappList, err := httpRestful.RecvXappCallbackData(ch)
116         if err != nil {
117                 t.Error("Receive failed: " + err.Error())
118         } else {
119                 if xappList == nil {
120                         t.Error("Expected an XApp notification list")
121                 } else {
122                         t.Log("whatever")
123                 }
124         }
125 }
126
127 func TestProvideXappHandleHandlerImpl(t *testing.T) {
128         datach := make(chan *models.XappCallbackData, 10)
129         defer close(datach)
130         data := models.XappCallbackData{
131                 XApps:   *swag.String("[]"),
132                 Version: *swag.Int64(1),
133                 Event:   *swag.String("someevent"),
134                 ID:      *swag.String("123456")}
135         var httpRestful, _ = GetNbi("httpRESTful")
136         err := httpRestful.(*HttpRestful).ProvideXappHandleHandlerImpl(datach, &data)
137         if err != nil {
138                 t.Error("Error occured: " + err.Error())
139         } else {
140                 recv := <-datach
141                 if recv == nil {
142                         t.Error("Something gone wrong: " + err.Error())
143                 } else {
144                         if recv != &data {
145                                 t.Error("Malformed data on channel")
146                         }
147                 }
148         }
149 }
150
151 func TestValidateXappCallbackData(t *testing.T) {
152         data := models.XappCallbackData{
153                 XApps:   *swag.String("[]"),
154                 Version: *swag.Int64(1),
155                 Event:   *swag.String("someevent"),
156                 ID:      *swag.String("123456")}
157
158         err := validateXappCallbackData(&data)
159         if err != nil {
160                 t.Error("Invalid XApp callback data: " + err.Error())
161         }
162 }
163
164 func TestValidateXappCallbackDataWithInvalidData(t *testing.T) {
165         data := models.XappCallbackData{
166                 XApps:   *swag.String("{}"),
167                 Version: *swag.Int64(1),
168                 Event:   *swag.String("someevent"),
169                 ID:      *swag.String("123456")}
170
171         err := validateXappCallbackData(&data)
172         if err == nil {
173                 t.Error("Invalid XApp callback data: " + err.Error())
174         }
175 }
176
177 func TestHttpGetXAppsInvalidData(t *testing.T) {
178         _, err := httpGetXApps(XMURL)
179         if err == nil {
180                 t.Error("No XApp data received: " + err.Error())
181         }
182 }
183
184 func TestHttpGetXAppsWithValidData(t *testing.T) {
185         var expected = 1
186         ts := createMockAppmgrWithData("127.0.0.1:3000", BasicXAppLists, nil)
187
188         ts.Start()
189         defer ts.Close()
190         xapplist, err := httpGetXApps(XMURL)
191         if err != nil {
192                 t.Error("Error occured: " + err.Error())
193         } else {
194                 if len(*xapplist) != expected {
195                         t.Error("Invalid XApp data: got " + string(len(*xapplist)) + ", expected " + string(expected))
196                 }
197         }
198 }
199
200 func TestRetrieveStartupDataTimeout(t *testing.T) {
201         sdlEngine, _ := sdl.GetSdl("file")
202         createMockPlatformComponents()
203         err := retrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
204         if err == nil {
205                 t.Error("Cannot retrieve startup data: " + err.Error())
206         }
207         os.Remove("rt.json")
208         os.Remove("config.json")
209 }
210
211 func TestRetrieveStartupData(t *testing.T) {
212         ts := createMockAppmgrWithData("127.0.0.1:3000", BasicXAppLists, SubscriptionResp)
213         ts.Start()
214         defer ts.Close()
215         sdlEngine, _ := sdl.GetSdl("file")
216         var httpRestful, _ = GetNbi("httpRESTful")
217         createMockPlatformComponents()
218         err := httpRestful.(*HttpRestful).RetrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
219         //err := retrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
220         if err != nil {
221                 t.Error("Cannot retrieve startup data: " + err.Error())
222         }
223         os.Remove("rt.json")
224         os.Remove("config.json")
225 }
226
227 func TestRetrieveStartupDataWithInvalidSubResp(t *testing.T) {
228         ts := createMockAppmgrWithData("127.0.0.1:3000", BasicXAppLists, InvalidSubResp)
229         ts.Start()
230         defer ts.Close()
231         sdlEngine, _ := sdl.GetSdl("file")
232         var httpRestful, _ = GetNbi("httpRESTful")
233         createMockPlatformComponents()
234         err := httpRestful.(*HttpRestful).RetrieveStartupData(XMURL, "httpgetter", "rt.json", "config.json", sdlEngine)
235         if err == nil {
236                 t.Error("Cannot retrieve startup data: " + err.Error())
237         }
238         os.Remove("rt.json")
239         os.Remove("config.json")
240 }