c59e7fb5dc25600605c6b6dd78a87a4cfb11c6c8
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2022 Nordix Foundation.
4  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
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  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.clamp.acm.participant.kubernetes.rest;
23
24 import static org.hamcrest.CoreMatchers.is;
25 import static org.mockito.ArgumentMatchers.any;
26 import static org.mockito.Mockito.doNothing;
27 import static org.mockito.Mockito.when;
28 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
29 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
30 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.nio.charset.StandardCharsets;
35 import java.util.List;
36 import org.apache.commons.io.FileUtils;
37 import org.json.JSONObject;
38 import org.junit.jupiter.api.BeforeAll;
39 import org.junit.jupiter.api.BeforeEach;
40 import org.junit.jupiter.api.Test;
41 import org.junit.jupiter.api.extension.ExtendWith;
42 import org.onap.policy.clamp.acm.participant.kubernetes.controller.ChartController;
43 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartInfo;
44 import org.onap.policy.clamp.acm.participant.kubernetes.models.ChartList;
45 import org.onap.policy.clamp.acm.participant.kubernetes.parameters.ParticipantK8sParameters;
46 import org.onap.policy.clamp.acm.participant.kubernetes.service.ChartService;
47 import org.onap.policy.common.utils.coder.Coder;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.boot.context.properties.EnableConfigurationProperties;
52 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
53 import org.springframework.boot.test.mock.mockito.MockBean;
54 import org.springframework.http.MediaType;
55 import org.springframework.mock.web.MockMultipartFile;
56 import org.springframework.test.context.junit.jupiter.SpringExtension;
57 import org.springframework.test.web.servlet.MockMvc;
58 import org.springframework.test.web.servlet.RequestBuilder;
59 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
60 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
61 import org.springframework.web.context.WebApplicationContext;
62
63
64 @ExtendWith(SpringExtension.class)
65 @WebMvcTest(value = ChartController.class, properties = "chart.api.enabled=true")
66 @EnableConfigurationProperties(value = ParticipantK8sParameters.class)
67 class ChartControllerTest {
68
69     private static final Coder CODER = new StandardCoder();
70     private static final String CHART_INFO_YAML = "src/test/resources/ChartList.json";
71     private static List<ChartInfo> charts;
72     private static String RETRIEVE_CHART_URL = "/helm/charts";
73     private static String INSTALL_CHART_URL = "/helm/install";
74     private static String UNINSTALL_CHART_URL = "/helm/uninstall/";
75     private static String ONBOARD_CHART_URL = "/helm/onboard/chart";
76     private static String DELETE_CHART_URL = "/helm/chart";
77     private static String CONFIGURE_REPO_URL = "/helm/repo";
78
79     @Autowired
80     private MockMvc mockMvc;
81
82     @MockBean
83     private ChartService chartService;
84
85     @Autowired
86     private WebApplicationContext context;
87
88     /**
89      * Read input chart info json.
90      * @throws Exception incase of error.
91      */
92     @BeforeAll
93     static void setupParams() throws CoderException {
94         charts = CODER.decode(new File(CHART_INFO_YAML), ChartList.class).getCharts();
95     }
96
97     /**
98      * Mock service layer in Controller.
99      * @throws Exception incase of error.
100      */
101     @BeforeEach
102     void mockServiceClass() {
103         when(chartService.getAllCharts()).thenReturn(charts);
104         when(chartService.getChart(charts.get(0).getChartId().getName(), charts.get(0).getChartId().getVersion()))
105             .thenReturn(charts.get(0));
106
107         this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
108     }
109
110     /**
111      * Test endpoint for retrieving all charts.
112      * @throws Exception incase of error.
113      */
114     @Test
115     void retrieveAllCharts() throws Exception {
116         RequestBuilder requestBuilder;
117         requestBuilder = MockMvcRequestBuilders.get(RETRIEVE_CHART_URL).accept(MediaType.APPLICATION_JSON_VALUE);
118
119         mockMvc.perform(requestBuilder).andExpect(status().isOk())
120             .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
121             .andExpect(jsonPath("$.charts.[0].chartId.name", is("HelloWorld")));
122     }
123
124     /**
125      * Test endpoint for installing a chart.
126      * @throws Exception incase of error.
127      */
128     @Test
129     void installChart() throws Exception {
130         RequestBuilder requestBuilder;
131
132         //Mocking successful installation for void install method
133         doNothing().when(chartService).installChart(charts.get(0));
134
135         requestBuilder = MockMvcRequestBuilders.post(INSTALL_CHART_URL).accept(MediaType.APPLICATION_JSON_VALUE)
136             .content(getInstallationJson(charts.get(0).getChartId().getName(), charts.get(0).getChartId().getVersion()))
137             .contentType(MediaType.APPLICATION_JSON_VALUE);
138
139         mockMvc.perform(requestBuilder).andExpect(status().isCreated());
140
141         //Install Invalid chart, expects HTTP status NOT_FOUND
142         requestBuilder = MockMvcRequestBuilders.post(INSTALL_CHART_URL).accept(MediaType.APPLICATION_JSON_VALUE)
143             .content(getInstallationJson("invalidName", "invalidVersion"))
144             .contentType(MediaType.APPLICATION_JSON_VALUE);
145
146         mockMvc.perform(requestBuilder).andExpect(status().isNotFound());
147     }
148
149     /**
150      * Test endpoint for uninstalling a chart.
151      * @throws Exception incase of error.
152      */
153     @Test
154     void uninstallChart() throws Exception {
155         RequestBuilder requestBuilder;
156
157         //Mocking successful scenario for void uninstall method
158         doNothing().when(chartService).uninstallChart(charts.get(0));
159
160         requestBuilder = MockMvcRequestBuilders.delete(UNINSTALL_CHART_URL + charts.get(0)
161             .getChartId().getName() + "/" + charts.get(0).getChartId().getVersion())
162             .accept(MediaType.APPLICATION_JSON_VALUE).contentType(MediaType.APPLICATION_JSON_VALUE);
163
164         mockMvc.perform(requestBuilder).andExpect(status().isNoContent());
165
166         //Invalid chart
167         requestBuilder = MockMvcRequestBuilders.delete(UNINSTALL_CHART_URL + "invalidName"
168             + "/" + "invalidVersion").accept(MediaType.APPLICATION_JSON_VALUE)
169             .contentType(MediaType.APPLICATION_JSON_VALUE);
170
171         mockMvc.perform(requestBuilder).andExpect(status().isNotFound());
172     }
173
174     /**
175      * Test endpoint for chart onboarding.
176      * @throws Exception incase of error.
177      */
178     @Test
179     void onboardChart() throws Exception {
180         RequestBuilder requestBuilder;
181         MockMultipartFile chartFile = new MockMultipartFile("chart", "hello.tgz",
182             MediaType.TEXT_PLAIN_VALUE, "Dummy data".getBytes());
183
184         MockMultipartFile overrideFile = new MockMultipartFile("values", "values.yaml",
185             MediaType.TEXT_PLAIN_VALUE, "Dummy data".getBytes());
186
187         //Mocking successful scenario for void uninstall method
188         when(chartService.saveChart(charts.get(0), chartFile, null)).thenReturn(charts.get(0));
189
190         requestBuilder = MockMvcRequestBuilders.multipart(ONBOARD_CHART_URL)
191             .file(chartFile).file(overrideFile).param("info", getChartInfoJson());
192
193         mockMvc.perform(requestBuilder).andExpect(status().isOk());
194     }
195
196     /**
197      * Test endpoint for deleting a chart.
198      * @throws Exception incase of error.
199      */
200     @Test
201     void deleteChart() throws Exception {
202         RequestBuilder requestBuilder;
203
204         //Mocking successful scenario for void uninstall method
205         doNothing().when(chartService).deleteChart(charts.get(0));
206
207         requestBuilder = MockMvcRequestBuilders.delete(DELETE_CHART_URL + "/" + charts.get(0)
208             .getChartId().getName() + "/" + charts.get(0).getChartId().getVersion())
209             .accept(MediaType.APPLICATION_JSON_VALUE)
210             .contentType(MediaType.APPLICATION_JSON_VALUE);
211
212         mockMvc.perform(requestBuilder).andExpect(status().isNoContent());
213         //Invalid chart
214         requestBuilder = MockMvcRequestBuilders.delete(UNINSTALL_CHART_URL + "invalidName"
215             + "/" + "invalidVersion").accept(MediaType.APPLICATION_JSON_VALUE)
216             .contentType(MediaType.APPLICATION_JSON_VALUE);
217
218         mockMvc.perform(requestBuilder).andExpect(status().isNotFound());
219
220     }
221
222     /**
223      * Test endpoint for configuring a helm repository.
224      * @throws Exception in case of error.
225      */
226     @Test
227     void testConfigureRepo() throws Exception {
228         RequestBuilder requestBuilder;
229         when(chartService.configureRepository(any())).thenReturn(true);
230
231         requestBuilder = MockMvcRequestBuilders.post(CONFIGURE_REPO_URL).accept(MediaType.APPLICATION_JSON_VALUE)
232             .content(getInstallationJson(charts.get(0).getChartId().getName(), charts.get(0).getChartId().getVersion()))
233             .contentType(MediaType.APPLICATION_JSON_VALUE);
234
235         mockMvc.perform(requestBuilder).andExpect(status().isCreated());
236
237     }
238
239     @Test
240     void testConfigureRepoAlreadyExist() throws Exception {
241         RequestBuilder requestBuilder;
242         when(chartService.configureRepository(any())).thenReturn(false);
243
244         requestBuilder = MockMvcRequestBuilders.post(CONFIGURE_REPO_URL).accept(MediaType.APPLICATION_JSON_VALUE)
245             .content(getInstallationJson(charts.get(0).getChartId().getName(), charts.get(0).getChartId().getVersion()))
246             .contentType(MediaType.APPLICATION_JSON_VALUE);
247
248         mockMvc.perform(requestBuilder).andExpect(status().isConflict());
249
250     }
251
252
253     private String getInstallationJson(String name, String version) {
254         JSONObject jsonObj = new JSONObject();
255         jsonObj.put("name", name);
256         jsonObj.put("version", version);
257         return jsonObj.toString();
258     }
259
260     private String getChartInfoJson() throws IOException {
261         return FileUtils.readFileToString(new File(CHART_INFO_YAML), StandardCharsets.UTF_8);
262     }
263
264 }