dae16c7c317bb8fe46429a8a7d13879443ad4e62
[integration.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * PNF-REGISTRATION-HANDLER
4  * ================================================================================
5  * Copyright (C) 2018 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.pnfsimulator.rest;
22
23 import com.google.common.collect.ImmutableMap;
24 import com.google.gson.Gson;
25 import com.google.gson.JsonObject;
26 import org.junit.jupiter.api.BeforeAll;
27 import org.junit.jupiter.api.BeforeEach;
28 import org.junit.jupiter.api.Test;
29 import org.mockito.InjectMocks;
30 import org.mockito.Mock;
31 import org.mockito.Mockito;
32 import org.mockito.MockitoAnnotations;
33 import org.onap.pnfsimulator.rest.model.FullEvent;
34 import org.onap.pnfsimulator.rest.model.SimulatorParams;
35 import org.onap.pnfsimulator.rest.model.SimulatorRequest;
36 import org.onap.pnfsimulator.rest.util.JsonObjectDeserializer;
37 import org.onap.pnfsimulator.simulator.SimulatorService;
38 import org.onap.pnfsimulator.simulatorconfig.SimulatorConfig;
39 import org.quartz.SchedulerException;
40 import org.springframework.http.MediaType;
41 import org.springframework.test.web.servlet.MockMvc;
42 import org.springframework.test.web.servlet.MvcResult;
43 import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
44 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
45
46 import java.io.IOException;
47 import java.net.URL;
48 import java.security.GeneralSecurityException;
49
50 import static org.assertj.core.api.Java6Assertions.assertThat;
51 import static org.mockito.ArgumentMatchers.any;
52 import static org.mockito.ArgumentMatchers.eq;
53 import static org.mockito.Mockito.verify;
54 import static org.mockito.Mockito.when;
55 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
56 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
57 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
58 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
59 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
60
61 class SimulatorControllerTest {
62
63     private static final String START_ENDPOINT = "/simulator/start";
64     private static final String CONFIG_ENDPOINT = "/simulator/config";
65     private static final String EVENT_ENDPOINT = "/simulator/event";
66     private static final String JSON_MSG_EXPRESSION = "$.message";
67
68     private static final String NEW_URL = "http://0.0.0.0:8090/eventListener/v7";
69     private static final String UPDATE_SIM_CONFIG_VALID_JSON = "{\"vesServerUrl\": \"" + NEW_URL + "\"}";
70     private static final String SAMPLE_ID = "sampleId";
71     private static final Gson GSON_OBJ = new Gson();
72     private static String simulatorRequestBody;
73     private MockMvc mockMvc;
74     @InjectMocks
75     private SimulatorController controller;
76     @Mock
77     private SimulatorService simulatorService;
78
79     @BeforeAll
80     static void beforeAll() {
81         SimulatorParams simulatorParams = new SimulatorParams("http://0.0.0.0:8080", 1, 1);
82         SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams,
83                 "testTemplate.json", new JsonObject());
84
85         simulatorRequestBody = GSON_OBJ.toJson(simulatorRequest);
86     }
87
88     @BeforeEach
89     void setup() throws IOException, SchedulerException, GeneralSecurityException {
90         MockitoAnnotations.initMocks(this);
91         when(simulatorService.triggerEvent(any())).thenReturn("jobName");
92         mockMvc = MockMvcBuilders
93                 .standaloneSetup(controller)
94                 .build();
95     }
96
97     @Test
98     void shouldStartSimulatorProperly() throws Exception {
99         startSimulator();
100         SimulatorRequest simulatorRequest = new Gson().fromJson(simulatorRequestBody, SimulatorRequest.class);
101
102         verify(simulatorService).triggerEvent(eq(simulatorRequest));
103     }
104
105     @Test
106     void testShouldGetConfigurationWhenRequested() throws Exception {
107         String newUrl = "http://localhost:8090/eventListener/v7";
108         SimulatorConfig expectedConfig = new SimulatorConfig(SAMPLE_ID, new URL(newUrl));
109         when(simulatorService.getConfiguration()).thenReturn(expectedConfig);
110
111         MvcResult getResult = mockMvc
112                 .perform(get(CONFIG_ENDPOINT)
113                         .contentType(MediaType.APPLICATION_JSON)
114                         .content(UPDATE_SIM_CONFIG_VALID_JSON))
115                 .andExpect(status().isOk())
116                 .andReturn();
117
118         String expectedVesUrlJsonPart = createStringReprOfJson("vesServerUrl", newUrl);
119         assertThat(getResult.getResponse().getContentAsString()).contains(expectedVesUrlJsonPart);
120     }
121
122     @Test
123     void testShouldSuccessfullyUpdateConfigurationWithNewVesUrl() throws Exception {
124         String oldUrl = "http://localhost:8090/eventListener/v7";
125         SimulatorConfig expectedConfigBeforeUpdate = new SimulatorConfig(SAMPLE_ID, new URL(oldUrl));
126         SimulatorConfig expectedConfigAfterUpdate = new SimulatorConfig(SAMPLE_ID, new URL(NEW_URL));
127
128         when(simulatorService.getConfiguration()).thenReturn(expectedConfigBeforeUpdate);
129         when(simulatorService.updateConfiguration(any(SimulatorConfig.class))).thenReturn(expectedConfigAfterUpdate);
130
131         MvcResult postResult = mockMvc
132                 .perform(put(CONFIG_ENDPOINT)
133                         .contentType(MediaType.APPLICATION_JSON)
134                         .content(UPDATE_SIM_CONFIG_VALID_JSON))
135                 .andExpect(status().isOk())
136                 .andReturn();
137
138         String expectedVesUrlJsonPart = createStringReprOfJson("vesServerUrl", expectedConfigAfterUpdate.getVesServerUrl().toString());
139         assertThat(postResult.getResponse().getContentAsString()).contains(expectedVesUrlJsonPart);
140     }
141
142     @Test
143     void testShouldRaiseExceptionWhenUpdateConfigWithIncorrectPayloadWasSent() throws Exception {
144         mockMvc
145                 .perform(put(CONFIG_ENDPOINT)
146                         .contentType(MediaType.APPLICATION_JSON)
147                         .content("{\"vesUrl\": \"" + NEW_URL + "\"}"))
148                 .andExpect(status().isBadRequest());
149     }
150
151     @Test
152     void testShouldRaiseExceptionWhenUrlInInvalidFormatIsSent() throws Exception {
153         mockMvc
154                 .perform(put(CONFIG_ENDPOINT)
155                         .contentType(MediaType.APPLICATION_JSON)
156                         .content("{\"vesUrl\": \"http://0.0.0.0:VES-PORT/eventListener/v7\"}"))
157                 .andExpect(status().isBadRequest());
158     }
159
160     @Test
161     void testShouldSendEventDirectly() throws Exception {
162         String contentAsString = mockMvc
163                 .perform(post(EVENT_ENDPOINT)
164                         .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
165                         .content("{\"vesServerUrl\":\"http://0.0.0.0:8080/simulator/v7\",\n" +
166                                 "      \"event\":{  \n" +
167                                 "         \"commonEventHeader\":{  \n" +
168                                 "            \"domain\":\"notification\",\n" +
169                                 "            \"eventName\":\"vFirewallBroadcastPackets\"\n" +
170                                 "         },\n" +
171                                 "         \"notificationFields\":{  \n" +
172                                 "            \"arrayOfNamedHashMap\":[  \n" +
173                                 "               {  \n" +
174                                 "                  \"name\":\"A20161221.1031-1041.bin.gz\",\n" +
175                                 "                  \"hashMap\":{  \n" +
176                                 "                     \"fileformatType\":\"org.3GPP.32.435#measCollec\"}}]}}}"))
177                 .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString();
178         assertThat(contentAsString).contains("One-time direct event sent successfully");
179     }
180
181     @Test
182     void testShouldReplaceKeywordsAndSendEventDirectly() throws Exception {
183         String contentAsString = mockMvc
184                 .perform(post(EVENT_ENDPOINT)
185                         .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
186                         .content("{\"vesServerUrl\": \"http://localhost:9999/eventListener\",\n" +
187                                 "    \"event\": {\n" +
188                                 "        \"commonEventHeader\": {\n" +
189                                 "            \"eventId\": \"#RandomString(20)\",\n" +
190                                 "            \"sourceName\": \"PATCHED_sourceName\",\n" +
191                                 "            \"version\": 3.0\n}}}"))
192                 .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString();
193         assertThat(contentAsString).contains("One-time direct event sent successfully");
194
195         verify(simulatorService, Mockito.times(1)).triggerOneTimeEvent(any(FullEvent.class));
196     }
197
198
199     private void startSimulator() throws Exception {
200         mockMvc
201                 .perform(post(START_ENDPOINT)
202                         .content(simulatorRequestBody)
203                         .contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8"))
204                 .andExpect(status().isOk())
205                 .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Request started"));
206
207     }
208
209     private String createStringReprOfJson(String key, String value) {
210         return GSON_OBJ.toJson(ImmutableMap.of(key, value));
211     }
212 }