aboutsummaryrefslogtreecommitdiffstats
path: root/src/test/java/org/onap/aai/restclient/client/RestfulClientTest.java
blob: 9fe09a12da6aa1adc9379350426a89dd95474f93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
 * ============LICENSE_START===========================================================================================
 * Copyright (c) 2017 AT&T Intellectual Property.
 * Copyright (c) 2017 Amdocs
 * Modification Copyright (c) 2018 IBM.
 * All rights reserved.
 * =====================================================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * ============LICENSE_END================================================== ===========================================
 *
 * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property.
 */
package org.onap.aai.restclient.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.onap.aai.restclient.enums.RestAuthenticationMode;
import org.onap.aai.restclient.rest.RestClientBuilder;

public class RestfulClientTest {

    private static final String TEST_URL = "http://localhost:9000/aai/v7";

    private final MultivaluedMap<String, String> emptyMap = new MultivaluedHashMap<>();

    private RestClientBuilder mockClientBuilder;
    private Client mockedClient;
    private WebTarget mockedWebTarget;
    private Builder mockedBuilder;
    private Response mockedClientResponse;

    /**
     * Test case initialization
     *
     * @throws Exception the exception
     */
    @Before
    public void init() throws Exception {
        mockedClientResponse = Mockito.mock(Response.class);
        setResponseStatus(Response.Status.OK);
        Mockito.when(mockedClientResponse.getHeaders()).thenReturn(new MultivaluedHashMap<>());
        Mockito.when(mockedClientResponse.readEntity(String.class)).thenReturn("hello");

        mockedBuilder = Mockito.mock(Builder.class);
        Mockito.when(mockedBuilder.get()).thenReturn(mockedClientResponse);
        Mockito.when(mockedBuilder.post(Mockito.any())).thenReturn(mockedClientResponse);
        Mockito.when(mockedBuilder.put(Mockito.any())).thenReturn(mockedClientResponse);
        Mockito.when(mockedBuilder.delete()).thenReturn(mockedClientResponse);
        Mockito.when(mockedBuilder.head()).thenReturn(mockedClientResponse);
        Mockito.when(mockedBuilder.accept(Mockito.any(MediaType.class))).thenReturn(mockedBuilder);

        mockedWebTarget = Mockito.mock(WebTarget.class);
        Mockito.when(mockedWebTarget.request()).thenReturn(mockedBuilder);

        mockedClient = Mockito.mock(Client.class);
        Mockito.when(mockedClient.target(Mockito.anyString())).thenReturn(mockedWebTarget);

        mockClientBuilder = Mockito.mock(RestClientBuilder.class);
        Mockito.when(mockClientBuilder.getClient()).thenReturn(mockedClient);
    }

    @Test
    public void validateConstructors() {
        RestClient restClient = new RestClient();
        assertNotNull(restClient);
        restClient = new RestClient(mockClientBuilder);
        assertNotNull(restClient);
    }

    @Test
    public void validateBasicClientConstruction() throws Exception {
        Client client = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.HTTP_NOAUTH)
                .connectTimeoutMs(1000).readTimeoutMs(500).getClient();
        assertNotNull(client);
    }

    @Test
    public void validateClientWithSslBasicAuthConstruction() throws Exception {
        Client client = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_BASIC)
                .connectTimeoutMs(1000).readTimeoutMs(500).basicAuthPassword("password").basicAuthUsername("username")
                .getClient();
        assertNotNull(client);
    }

    @Test
    public void validateClientWithSslCertConstruction() throws Exception {
        // This test covers the standard SSL settings, i.e. no validation
        assertNotNull(buildClient());

        RestClient restClient = new RestClient(mockClientBuilder);

        // Test with validation enabled
        Client client = restClient.authenticationMode(RestAuthenticationMode.SSL_CERT).connectTimeoutMs(1000)
                .readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password").validateServerCertChain(true)
                .validateServerHostname(true).getClient();
        assertNotNull(client);

        // Test with a trust store
        client = restClient.authenticationMode(RestAuthenticationMode.SSL_CERT).connectTimeoutMs(1000)
                .readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password").trustStore("truststore")
                .getClient();
        assertNotNull(client);
    }

    @Test
    public void validateSuccessfulPut() throws Exception {
        RestClient restClient = buildClient();

        OperationResult result = restClient.put(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE,
                MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());

        // Repeat the PUT operation, this time with a return code of 204
        setResponseToNoContent();
        result = restClient.put(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE,
                MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode());
        assertNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void validateSuccessfulPost() throws Exception {
        RestClient restClient = buildClient();

        OperationResult result = restClient.post(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE,
                MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());

        // Repeat the POST operation, this time with a return code of 204
        setResponseToNoContent();
        result = restClient.post(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE,
                MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode());
        assertNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void validateSuccessfulPost_withMultivaluedHeader() throws Exception {
        RestClient restClient = buildClient();

        MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>();

        headerMap.add("txnId", "123");
        headerMap.add("txnId", "456");
        headerMap.add("txnId", "789");

        OperationResult result = restClient.post(TEST_URL, "", headerMap, MediaType.APPLICATION_JSON_TYPE,
                MediaType.APPLICATION_JSON_TYPE);

        // capture the txnId header from the outgoing request
        ArgumentCaptor<String> txnIdHeaderName = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<String> txnIdHeaderValue = ArgumentCaptor.forClass(String.class);

        Mockito.verify(mockedBuilder, Mockito.atLeast(1)).header(txnIdHeaderName.capture(), txnIdHeaderValue.capture());
        assertEquals("123;456;789", txnIdHeaderValue.getValue());

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void validateSuccessfulGet() throws Exception {
        OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void validateSuccessfulGetWithBasicAuth() throws Exception {
        RestClient restClient = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_BASIC)
                .connectTimeoutMs(1000).readTimeoutMs(500).basicAuthUsername("username").basicAuthUsername("password");

        OperationResult result = restClient.get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void validateResourceNotFoundGet() throws Exception {
        setResponseStatus(Response.Status.NOT_FOUND);
        Mockito.when(mockedClientResponse.readEntity(String.class)).thenReturn("RNF");

        OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.NOT_FOUND.getStatusCode(), result.getResultCode());
        assertNull(result.getResult());
        assertNotNull(result.getFailureCause());
    }

    @Test
    public void validateHealthCheck() throws Exception {
        boolean targetServiceHealthy =
                buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService");

        assertEquals(true, targetServiceHealthy);
    }

    @Test
    public void validateHealthCheckFailureWith403() throws Exception {
        Mockito.when(mockedClientResponse.getStatus()).thenReturn(Response.Status.FORBIDDEN.getStatusCode());

        boolean targetServiceHealthy =
                buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService");

        assertEquals(false, targetServiceHealthy);
    }

    @Test
    public void validateHealthCheckFailureWithThrownException() throws Exception {
        Mockito.when(mockedBuilder.get()).thenThrow(new IllegalArgumentException("error"));

        boolean targetServiceHealthy =
                buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService");

        assertEquals(false, targetServiceHealthy);
    }

    @Test
    public void validateSuccessfulGetWithRetries() throws Exception {
        Mockito.when(mockedClientResponse.getStatus()).thenReturn(408).thenReturn(Response.Status.OK.getStatusCode());
        Mockito.when(mockedClientResponse.readEntity(String.class)).thenReturn("error").thenReturn("ok");

        OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());

    }

    @Test
    public void validateFailedGetWithRetriesCausedByResourceNotFound() throws Exception {
        setResponseStatus(Response.Status.NOT_FOUND);
        Mockito.when(mockedClientResponse.readEntity(String.class)).thenReturn("error").thenReturn("ok");

        OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3);

        assertEquals(Response.Status.NOT_FOUND.getStatusCode(), result.getResultCode());
        assertNull(result.getResult());
        assertNotNull(result.getFailureCause());

    }

    @Test
    public void validateFailedGetAfterMaxRetries() throws Exception {
        setResponseStatus(Response.Status.INTERNAL_SERVER_ERROR);
        Mockito.when(mockedClientResponse.readEntity(String.class)).thenReturn("error");

        OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3);

        assertEquals(504, result.getResultCode());
        assertNull(result.getResult());
        assertNotNull(result.getFailureCause());

    }

    @Test
    public void validateSuccessfulDelete() throws Exception {
        RestClient restClient = buildClient();

        OperationResult result = restClient.delete(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());

        // Repeat the DELETE operation, this time with a return code of 204
        setResponseToNoContent();
        result = restClient.delete(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode());
        assertNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void validateSuccessfulHead() throws Exception {
        OperationResult result = buildClient().head(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void validateSuccessfulPatch() throws Exception {
        Mockito.when(mockedBuilder.header("X-HTTP-Method-Override", "PATCH")).thenReturn(mockedBuilder);
        OperationResult result = buildClient().patch(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE,
                MediaType.APPLICATION_JSON_TYPE);

        assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode());
        assertNotNull(result.getResult());
        assertNull(result.getFailureCause());
    }

    @Test
    public void testGetClient() throws Exception {
        RestClientBuilder restClientBuilder = new RestClientBuilder();
        restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_BASIC);
        restClientBuilder.setTruststoreFilename("truststore");
        assertTrue(restClientBuilder.getClient() instanceof Client);
    }

    /**
     * Specify the status code of the response object returned by the mocked client
     *
     * @param status object storing the status code to mock in the ClientResponse
     */
    private void setResponseStatus(Status status) {
        Mockito.when(mockedClientResponse.getStatus()).thenReturn(status.getStatusCode());
    }

    /**
     * Set the mocked client to return a response of "204 No Content"
     */
    private void setResponseToNoContent() {
        setResponseStatus(Response.Status.NO_CONTENT);
        // The Jersey client throws an exception when readEntity() is called following a 204 response
        ProcessingException processingException = new ProcessingException("No content");
        Mockito.when(mockedClientResponse.readEntity(String.class)).thenThrow(processingException);
    }

    /**
     * @return a mocked Rest Client object using standard SSL settings
     */
    private RestClient buildClient() {
        return new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_CERT)
                .connectTimeoutMs(1000).readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password");
    }
}