Enable test cases to execute
[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         if _, ok := resp.(*charts.GetChartsListOK); !ok {
130                 assert.Fail(t, "response type did not match : %t", resp)
131         }
132 }
133
134 func TestDownloadChart(t *testing.T) {
135         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
136                 ricdms.Logger.Debug("request received by mock to download chart")
137                 reader := strings.NewReader("SAMPLE_RESPONSE")
138                 data, _ := io.ReadAll(reader)
139                 ricdms.Logger.Debug("writing : %+v", data)
140                 w.Write(data)
141         }))
142         svr.Listener.Close()
143         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
144
145         svr.Start()
146         defer svr.Close()
147
148         resp := rh.DownloadChart("CHART_NAME", "VERSION")
149         assert.IsType(t, &charts.DownloadHelmChartOK{}, resp, "response did not match type")
150 }
151
152 func TestGetChartsByName(t *testing.T) {
153         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
154                 ricdms.Logger.Debug("request received by mock to get chart by name")
155                 path, _ := filepath.Abs("./mocks/resp-get-charts-by-name.json")
156                 file, err := os.Open(path)
157
158                 if err != nil {
159                         ricdms.Logger.Error("error in reading file: %v", err)
160                 }
161
162                 jsonData, err := io.ReadAll(file)
163                 if err != nil {
164                         ricdms.Logger.Error("Error in rading file: %v", err)
165                 }
166                 w.Write(jsonData)
167         }))
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.GetChartsByName("TEST_NAME")
176         ricdms.Logger.Debug("resp Data: %s", resp.(*charts.GetChartOK).Payload...)
177         assert.IsType(t, &charts.GetChartOK{}, resp, "response did not match type")
178 }
179
180 func TestGetChartsByNameAndVersion(t *testing.T) {
181         svr := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
182                 ricdms.Logger.Debug("request received by mock to get chart by name and version")
183                 path, _ := filepath.Abs("./mocks/resp-get-charts-by-name-and-ver.json")
184                 file, err := os.Open(path)
185
186                 if err != nil {
187                         ricdms.Logger.Error("error in reading file: %v", err)
188                 }
189
190                 jsonData, err := io.ReadAll(file)
191                 if err != nil {
192                         ricdms.Logger.Error("Error in rading file: %v", err)
193                 }
194                 w.Write(jsonData)
195         }))
196
197         svr.Listener.Close()
198         svr.Listener, _ = net.Listen("tcp", ricdms.Config.MockServer)
199
200         svr.Start()
201         defer svr.Close()
202
203         resp := rh.GetChartByNameAndVersion("Test", "1.0.0")
204         ricdms.Logger.Debug("resp data: %s", resp.(*charts.GetChartsFetcherOK).Payload)
205         assert.IsType(t, &charts.GetChartsFetcherOK{}, resp, "response did not match type")
206 }
207
208 func TestDownloadAndInstall(t *testing.T) {
209         response := rh.DownloadAndInstallChart("sample app", "1.0.0", "test")
210         if _, ok := response.(*d.PostDeployInternalServerError); !ok {
211                 assert.Fail(t, "response type did not match (actual) %T", response)
212         }
213
214 }
215
216 type HealthCheckerMock struct {
217         mock.Mock
218 }
219
220 func (h HealthCheckerMock) GetStatus() *models.Status {
221         return successStatus
222 }