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