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