e64b2ac552f344f0b534581dd0e577eadc5db3d1
[vid.git] / vid-app-common / src / test / java / org / onap / vid / aai / util / AAIRestInterfaceTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2018 - 2019 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.vid.aai.util;
22
23
24 import org.mockito.Mock;
25 import org.mockito.Mockito;
26
27 import org.onap.vid.aai.ExceptionWithRequestInfo;
28 import org.onap.vid.aai.exceptions.InvalidPropertyException;
29 import org.onap.vid.exceptions.GenericUncheckedException;
30 import org.onap.vid.utils.Unchecked;
31 import org.springframework.http.HttpMethod;
32 import org.testng.Assert;
33 import org.testng.annotations.BeforeMethod;
34 import org.testng.annotations.Test;
35
36 import javax.servlet.http.HttpServletRequest;
37 import javax.ws.rs.client.Client;
38 import javax.ws.rs.client.Entity;
39 import javax.ws.rs.client.Invocation;
40 import javax.ws.rs.client.WebTarget;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import java.io.UnsupportedEncodingException;
44 import java.net.URI;
45 import java.util.Optional;
46 import java.util.UUID;
47
48 import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor;
49 import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters;
50 import static javax.ws.rs.core.Response.Status.*;
51 import static junit.framework.TestCase.assertSame;
52 import static junit.framework.TestCase.fail;
53 import static org.junit.Assert.assertThat;
54 import static org.mockito.ArgumentMatchers.any;
55 import static org.mockito.ArgumentMatchers.eq;
56 import static org.mockito.Mockito.verify;
57 import static org.mockito.Mockito.when;
58 import static org.mockito.MockitoAnnotations.initMocks;
59
60
61 public class AAIRestInterfaceTest {
62
63     private static final String PATH = "path";
64     private static final String HTTP_LOCALHOST = "http://localhost/";
65     @Mock
66     private Client client;
67     @Mock
68     private WebTarget webTarget;
69     @Mock
70     private Invocation.Builder builder;
71     @Mock
72     private Invocation invocation;
73     @Mock
74     private ServletRequestHelper servletRequestHelper;
75     @Mock
76     private HttpsAuthClient httpsAuthClient;
77     @Mock
78     private HttpServletRequest httpServletRequest;
79     @Mock
80     private Response response;
81     @Mock
82     private SystemPropertyHelper systemPropertyHelper;
83
84     private AAIRestInterface testSubject;
85
86     @BeforeMethod
87     public void setUp() throws Exception {
88         initMocks(this);
89         mockSystemProperties();
90         testSubject = createTestSubject();
91         when(client.target(HTTP_LOCALHOST+PATH)).thenReturn(webTarget);
92         when(webTarget.request()).thenReturn(builder);
93         when(builder.accept(Mockito.anyString())).thenReturn(builder);
94         when(builder.header(Mockito.anyString(), Mockito.anyString())).thenReturn(builder);
95         when(builder.build(Mockito.anyString())).thenReturn(invocation);
96         when(builder.build(Mockito.anyString(), any(Entity.class))).thenReturn(invocation);
97         when(invocation.invoke()).thenReturn(response);
98         when(servletRequestHelper.extractOrGenerateRequestId()).thenReturn(UUID.randomUUID().toString());
99     }
100
101     private AAIRestInterface createTestSubject() {
102         return new AAIRestInterface(Optional.of(client), httpsAuthClient, servletRequestHelper, systemPropertyHelper);
103     }
104
105     @Test
106     public void shouldEncodeURL() throws Exception {
107         String nodeKey = "some unusual uri";
108         String nodeKey2 = "some/usual/uri";
109         Assert.assertEquals(testSubject.encodeURL(nodeKey), "some%20unusual%20uri");
110         Assert.assertEquals(testSubject.encodeURL(nodeKey2), "some%2Fusual%2Furi");
111     }
112
113     @Test
114     public void shouldSetRestSrvrBaseURL() {
115         String baseUrl = "anything";
116         testSubject.setRestSrvrBaseURL(baseUrl);
117         Assert.assertEquals(testSubject.getRestSrvrBaseURL(), baseUrl);
118     }
119
120     @Test
121     public void shouldExecuteRestJsonPutMethodWithResponse200() {
122         // given
123         String payload = "{\"id\": 1}";
124         Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
125
126         // when
127         when(response.getStatusInfo()).thenReturn(OK);
128         Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse();
129
130         // then
131         verify(builder).build(HttpMethod.PUT.name(), entity);
132         Assert.assertEquals(response, finalResponse);
133     }
134
135     @Test(expectedExceptions = {ExceptionWithRequestInfo.class})
136     public void shouldFailWhenRestJsonPutMethodExecuted() {
137         // given
138         String payload = "{\"id\": 1}";
139
140         // when
141         when(builder.build(eq(HttpMethod.PUT.name()), any(Entity.class))).thenThrow(new GenericUncheckedException("msg"));
142         testSubject.RestPut("", PATH, payload, false, true);
143
144         //then
145     }
146
147     @Test
148     public void shouldExecuteRestJsonPutMethodWithResponse400() {
149         // given
150         String payload = "{\"id\": 1}";
151         Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
152
153         // when
154         when(response.getStatusInfo()).thenReturn(BAD_REQUEST);
155         when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode());
156         Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse();
157
158         // then
159         verify(builder).build(HttpMethod.PUT.name(), entity);
160         Assert.assertEquals(response, finalResponse);
161     }
162
163     @Test
164     public void shouldExecuteRestPostMethodWithResponse200() {
165         // given
166         String payload = "{\"id\": 1}";
167         Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
168
169         // when
170         when(builder.post(Mockito.any(Entity.class))).thenReturn(response);
171         when(response.getStatusInfo()).thenReturn(OK);
172         Response finalResponse = testSubject.RestPost("", PATH, payload, false);
173
174         // then
175         verify(builder).post(entity);
176         Assert.assertEquals(response, finalResponse);
177     }
178
179     @Test
180     public void shouldExecuteRestPostMethodWithResponse400() {
181         // given
182         String payload = "{\"id\": 1}";
183         Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
184
185         // when
186         when(builder.post(Mockito.any(Entity.class))).thenReturn(response);
187         when(response.getStatusInfo()).thenReturn(BAD_REQUEST);
188         when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode());
189         Response finalResponse = testSubject.RestPost("", PATH, payload, false);
190
191         // then
192         verify(builder).post(entity);
193         Assert.assertEquals(response, finalResponse);
194     }
195
196     @Test
197     public void shouldFailWhenRestPostMethodExecuted() {
198         // given
199         String payload = "{\"id\": 1}";
200         Entity<String> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
201
202         // when
203         when(builder.post(Mockito.any(Entity.class))).thenThrow(new RuntimeException());
204         Response finalResponse = testSubject.RestPost("", PATH, payload, false);
205
206         // then
207         verify(builder).post(entity);
208         Assert.assertNull(finalResponse);
209     }
210
211     @Test
212     public void shouldExecuteRestDeleteMethodWithResponse400() {
213         // given
214         // when
215         when(builder.delete()).thenReturn(response);
216         when(response.getStatusInfo()).thenReturn(BAD_REQUEST);
217         String reason = "Any reason";
218         when(response.readEntity(String.class)).thenReturn(reason);
219         when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode());
220         boolean finalResponse = testSubject.Delete("", "", PATH);
221
222         // then
223         verify(builder).delete();
224         Assert.assertFalse(finalResponse);
225     }
226
227     @Test
228     public void shouldExecuteRestDeleteMethodWithResponse404() {
229         // given
230         // when
231         when(builder.delete()).thenReturn(response);
232         when(response.getStatusInfo()).thenReturn(NOT_FOUND);
233         String reason = "Any reason";
234         when(response.readEntity(String.class)).thenReturn(reason);
235         when(response.getStatus()).thenReturn(NOT_FOUND.getStatusCode());
236         boolean finalResponse = testSubject.Delete("", "", PATH);
237
238         // then
239         verify(builder).delete();
240         Assert.assertFalse(finalResponse);
241     }
242
243     @Test
244     public void shouldFailWhenRestDeleteExecuted() {
245         // given
246         // when
247         when(builder.delete()).thenThrow(new RuntimeException());
248         boolean finalResponse = testSubject.Delete("", "", PATH);
249         // then
250         verify(builder).delete();
251         Assert.assertFalse(finalResponse);
252     }
253
254     @Test
255     public void shouldExecuteRestGetMethodWithResponse200() {
256         // given
257         // when
258         when(response.getStatusInfo()).thenReturn(OK);
259         Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse();
260
261         // then
262         Assert.assertEquals(response, finalResponse);
263     }
264
265     @Test
266     public void shouldExecuteRestGetMethodWithResponse400() {
267         // given
268         // when
269         when(response.getStatusInfo()).thenReturn(BAD_REQUEST);
270         when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode());
271         Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse();
272
273         // then
274         Assert.assertEquals(response, finalResponse);
275     }
276
277     @Test
278     public void shouldFailWhenRestGetMethodExecuted() {
279         // given
280         // when
281         when(builder.build(HttpMethod.GET.name())).thenThrow(new RuntimeException());
282         Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse();
283
284         // then
285         Assert.assertNull(finalResponse);
286     }
287
288     private void mockSystemProperties() throws UnsupportedEncodingException, InvalidPropertyException {
289         when(systemPropertyHelper.getEncodedCredentials()).thenReturn("someCredentials");
290         when(systemPropertyHelper.getFullServicePath(Mockito.anyString())).thenReturn("http://localhost/path");
291         when(systemPropertyHelper.getFullServicePath(Mockito.any(URI.class))).thenReturn("http://localhost/path");
292         when(systemPropertyHelper.getServiceBasePath(Mockito.anyString())).thenReturn("http://localhost/path");
293     }
294
295 }