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