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