Removal of a committer
[ric-plt/ricdms.git] / pkg / resthooks / resthooks_test.go
1 // ==================================================================================
2 //
3 //      Copyright (c) 2022 Samsung
4 //
5 //       Licensed under the Apache License, Version 2.0 (the "License");
6 //       you may not use this file except in compliance with the License.
7 //       You may obtain a copy of the License at
8 //
9 //           http://www.apache.org/licenses/LICENSE-2.0
10 //
11 //       Unless required by applicable law or agreed to in writing, software
12 //       distributed under the License is distributed on an "AS IS" BASIS,
13 //       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 //       See the License for the specific language governing permissions and
15 //       limitations under the License.
16 //
17 //       This source code is part of the near-RT RIC (RAN Intelligent Controller)
18 //       platform project (RICP).
19 //
20 // ==================================================================================
21 package resthooks
22
23 import (
24         "encoding/json"
25         "fmt"
26         "io"
27         "io/ioutil"
28         "net"
29         "net/http"
30         "net/http/httptest"
31         "os"
32         "path/filepath"
33         "strings"
34         "testing"
35
36         ch "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/charts"
37         "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/deploy"
38         "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/health"
39         "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/models"
40         "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/onboard"
41         "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/restapi/operations/charts"
42         d "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/restapi/operations/deploy"
43         "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/restapi/operations/experiment"
44         h "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/restapi/operations/health"
45         "gerrit.o-ran-sc.org/r/ric-plt/ricdms/pkg/ricdms"
46         "github.com/stretchr/testify/assert"
47 )
48
49 var rh *Resthook
50 var successStatus *models.Status
51
52 func TestMain(m *testing.M) {
53
54         successStatus = &models.Status{
55                 Status: &health.HEALTHY,
56         }
57         ricdms.Init()
58         rh = &Resthook{
59                 HealthChecker: health.NewHealthChecker(),
60                 Onboarder:     onboard.NewOnboarder(),
61                 ChartMgr:      ch.NewChartmgr(),
62                 DeployMgr:     deploy.NewDeploymentManager(),
63         }
64         code := m.Run()
65         os.Exit(code)
66 }
67
68 func TestHealth(t *testing.T) {
69         resp := rh.GetDMSHealth()
70         switch resp.(type) {
71         case *h.GetHealthCheckOK:
72                 assert.Equal(t, successStatus, resp.(*h.GetHealthCheckOK).Payload)
73
74         case *h.GetHealthCheckInternalServerError:
75                 assert.Fail(t, "Internal Server generated: %v", resp)
76
77         default:
78                 assert.Fail(t, "Unknown type of resp : %v", resp)
79         }
80 }
81
82 func TestHealthxAppFail(t *testing.T) {
83         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
84                 w.WriteHeader(501)
85         }))
86
87         svr.Listener.Close()
88         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
89
90         svr.Start()
91         defer svr.Close()
92
93         resp := rh.GetxAppHealth("test", "test")
94         switch resp.(type) {
95         case *h.GetHealthCheckOK:
96                 assert.Fail(t, "Health check should not be okay: %v", resp)
97
98         case *h.GetHealthCheckInternalServerError:
99                 break
100
101         default:
102                 assert.Fail(t, "Unknown type of resp : %v", resp)
103         }
104 }
105
106 func TestHealthxApp(t *testing.T) {
107         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
108                 w.WriteHeader(http.StatusOK)
109         }))
110
111         svr.Listener.Close()
112         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
113
114         svr.Start()
115         defer svr.Close()
116
117         resp := rh.GetxAppHealth("test", "test")
118         switch resp.(type) {
119         case *h.GetHealthCheckOK:
120                 assert.Equal(t, successStatus, resp.(*h.GetHealthCheckOK).Payload)
121
122         case *h.GetHealthCheckInternalServerError:
123                 assert.Fail(t, "Internal Server generated: %v", resp)
124
125         default:
126                 assert.Fail(t, "Unknown type of resp : %v", resp)
127         }
128 }
129
130 func TestOnboard(t *testing.T) {
131         xApp := &models.Descriptor{
132                 Config: "SAMPLE_CONFIGURATION",
133                 Schema: "SAMPLE_SCHEMA",
134         }
135
136         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
137                 var d map[string]interface{}
138                 reqBytes, _ := ioutil.ReadAll(r.Body)
139                 defer r.Body.Close()
140
141                 err := json.Unmarshal(reqBytes, &d)
142
143                 ricdms.Logger.Debug("after unmarshal : %+v body: %+v", d, string(reqBytes))
144
145                 if err != nil {
146                         assert.Fail(t, "Not able to parse the request body")
147                 }
148
149                 assert.Equal(t, xApp.Config, d["config-file.json"])
150                 assert.Equal(t, xApp.Schema, d["controls-schema.json"])
151                 fmt.Fprintf(w, "SAMPLE_RESPONSE")
152         }))
153         svr.Listener.Close()
154         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
155
156         svr.Start()
157         defer svr.Close()
158
159         resp := rh.OnBoard(xApp)
160         assert.NotEqual(t, nil, resp)
161 }
162
163 func TestGetCharts(t *testing.T) {
164
165         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
166                 ricdms.Logger.Debug("Mock server running")
167                 fmt.Fprintf(w, "SAMPLE_RESPONSE")
168         }))
169         svr.Listener.Close()
170         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
171
172         svr.Start()
173         defer svr.Close()
174
175         resp := rh.GetCharts()
176         assert.NotEqual(t, nil, resp)
177
178         if _, ok := resp.(*charts.GetChartsListOK); !ok {
179                 assert.Fail(t, "response type did not match : %t", resp)
180         }
181 }
182
183 func TestDownloadChart(t *testing.T) {
184         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
185                 ricdms.Logger.Debug("request received by mock to download chart")
186                 reader := strings.NewReader("SAMPLE_RESPONSE")
187                 data, _ := io.ReadAll(reader)
188                 ricdms.Logger.Debug("writing : %+v", data)
189                 w.Write(data)
190         }))
191         svr.Listener.Close()
192         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
193
194         svr.Start()
195         defer svr.Close()
196
197         resp := rh.DownloadChart("CHART_NAME", "VERSION")
198         assert.IsType(t, &charts.DownloadHelmChartOK{}, resp, "response did not match type")
199 }
200
201 func TestGetChartsByName(t *testing.T) {
202         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
203                 ricdms.Logger.Debug("request received by mock to get chart by name")
204                 path, _ := filepath.Abs("./mocks/resp-get-charts-by-name.json")
205                 file, err := os.Open(path)
206
207                 if err != nil {
208                         ricdms.Logger.Error("error in reading file: %v", err)
209                 }
210
211                 jsonData, err := io.ReadAll(file)
212                 if err != nil {
213                         ricdms.Logger.Error("Error in rading file: %v", err)
214                 }
215                 w.Write(jsonData)
216         }))
217
218         svr.Listener.Close()
219         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
220
221         svr.Start()
222         defer svr.Close()
223
224         resp := rh.GetChartsByName("TEST_NAME")
225         ricdms.Logger.Debug("resp Data: %s", resp.(*charts.GetChartOK).Payload...)
226         assert.IsType(t, &charts.GetChartOK{}, resp, "response did not match type")
227 }
228
229 func TestGetChartsByNameAndVersion(t *testing.T) {
230         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
231                 ricdms.Logger.Debug("request received by mock to get chart by name and version")
232                 path, _ := filepath.Abs("./mocks/resp-get-charts-by-name-and-ver.json")
233                 file, err := os.Open(path)
234
235                 if err != nil {
236                         ricdms.Logger.Error("error in reading file: %v", err)
237                 }
238
239                 jsonData, err := io.ReadAll(file)
240                 if err != nil {
241                         ricdms.Logger.Error("Error in rading file: %v", err)
242                 }
243                 w.Write(jsonData)
244         }))
245
246         svr.Listener.Close()
247         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
248
249         svr.Start()
250         defer svr.Close()
251
252         resp := rh.GetChartByNameAndVersion("Test", "1.0.0")
253         ricdms.Logger.Debug("resp data: %s", resp.(*charts.GetChartsFetcherOK).Payload)
254         assert.IsType(t, &charts.GetChartsFetcherOK{}, resp, "response did not match type")
255 }
256
257 func TestDownloadAndInstall(t *testing.T) {
258         response := rh.DownloadAndInstallChart("sample app", "1.0.0", "test")
259         if _, ok := response.(*d.PostDeployInternalServerError); !ok {
260                 assert.Fail(t, "response type did not match (actual) %T", response)
261         }
262
263 }
264
265 func TestUninstallxApp(t *testing.T) {
266         response := rh.UninstallChart("test", "test", "test")
267         if _, ok := response.(*d.DeleteDeployInternalServerError); !ok {
268                 assert.Fail(t, "response type did not match actual: %T", response)
269         }
270 }
271
272 func TestCustomOnaboardEmptyPkg(t *testing.T) {
273         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
274                 ricdms.Logger.Debug("request received by mock to get chart by name and version")
275         }))
276
277         svr.Listener.Close()
278         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
279
280         svr.Start()
281         defer svr.Close()
282
283         resp := rh.Onboarder.CustomOnboard(nil)
284         ricdms.Logger.Debug("resp type:%T", resp)
285
286         switch resp.(type) {
287         case *experiment.PostCustomOnboardInternalServerError:
288                 break
289         default:
290                 assert.Failf(t, "case 1 response type did not match", "[actual: %T]", resp)
291         }
292 }