add47b0a439ca272be7d8496eb68e32f0cb16fdc
[dcaegen2/collectors/datafile.git] /
1 /*
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018 NOKIA Intellectual Property, 2018-2019 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.onap.dcaegen2.collectors.datafile.service.producer;
18
19 import static org.junit.Assert.assertTrue;
20 import static org.junit.Assert.fail;
21 import static org.junit.jupiter.api.Assertions.assertEquals;
22 import static org.mockito.ArgumentMatchers.any;
23 import static org.mockito.Mockito.doReturn;
24 import static org.mockito.Mockito.mock;
25 import static org.mockito.Mockito.spy;
26 import static org.mockito.Mockito.verify;
27 import static org.mockito.Mockito.verifyNoMoreInteractions;
28 import static org.mockito.Mockito.when;
29
30 import java.net.URI;
31 import java.nio.charset.StandardCharsets;
32 import java.security.KeyManagementException;
33 import java.security.KeyStoreException;
34 import java.security.NoSuchAlgorithmException;
35 import java.time.Duration;
36 import java.util.HashMap;
37 import java.util.Map;
38 import java.util.concurrent.Future;
39 import javax.net.ssl.SSLContext;
40 import org.apache.commons.codec.binary.Base64;
41 import org.apache.http.Header;
42 import org.apache.http.HttpResponse;
43 import org.apache.http.client.config.RequestConfig;
44 import org.apache.http.client.methods.HttpGet;
45 import org.apache.http.client.methods.HttpPut;
46 import org.apache.http.client.methods.HttpUriRequest;
47 import org.apache.http.conn.ssl.NoopHostnameVerifier;
48 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
49 import org.junit.jupiter.api.BeforeEach;
50 import org.junit.jupiter.api.Test;
51 import org.mockito.ArgumentCaptor;
52 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
53 import org.onap.dcaegen2.collectors.datafile.http.HttpAsyncClientBuilderWrapper;
54 import org.onap.dcaegen2.collectors.datafile.web.PublishRedirectStrategy;
55 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
56
57 /**
58  * Test for DmaapProducerHttpClient.
59  *
60  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18
61  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
62  */
63 class DmaapProducerHttpClientTest {
64
65     private static final String HOST = "54.45.33.2";
66     private static final String HTTPS_SCHEME = "https";
67     private static final int PORT = 1234;
68     private static final String USER_NAME = "dradmin";
69     private static final Duration TWO_SECOND_TIMEOUT = Duration.ofSeconds(2);
70
71     private static final Map<String, String> CONTEXT_MAP = new HashMap<>();
72
73
74     private DmaapProducerHttpClient producerClientUnderTestSpy;
75
76     private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
77
78     private HttpAsyncClientBuilderWrapper clientBuilderMock;
79
80     private CloseableHttpAsyncClient clientMock;
81     @SuppressWarnings("unchecked")
82     private Future<HttpResponse> futureMock = mock(Future.class);
83
84     @BeforeEach
85     void setUp() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
86         when(dmaapPublisherConfigurationMock.dmaapHostName()).thenReturn(HOST);
87         when(dmaapPublisherConfigurationMock.dmaapProtocol()).thenReturn(HTTPS_SCHEME);
88         when(dmaapPublisherConfigurationMock.dmaapPortNumber()).thenReturn(PORT);
89         when(dmaapPublisherConfigurationMock.dmaapUserName()).thenReturn("dradmin");
90         when(dmaapPublisherConfigurationMock.dmaapUserPassword()).thenReturn("dradmin");
91
92         producerClientUnderTestSpy = spy(new DmaapProducerHttpClient(dmaapPublisherConfigurationMock));
93
94         clientBuilderMock = mock(HttpAsyncClientBuilderWrapper.class);
95         clientMock = mock(CloseableHttpAsyncClient.class);
96     }
97
98     @Test
99     void getHttpResponseWithRederict_Success() throws Exception {
100         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
101         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
102         when(clientBuilderMock.setSslHostnameVerifier(any(NoopHostnameVerifier.class))).thenReturn(clientBuilderMock);
103         when(clientBuilderMock.build()).thenReturn(clientMock);
104         when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock);
105         HttpResponse responseMock = mock(HttpResponse.class);
106         when(futureMock.get()).thenReturn(responseMock);
107
108         HttpGet request = new HttpGet();
109         producerClientUnderTestSpy.getDmaapProducerResponseWithRedirect(request, CONTEXT_MAP);
110
111         verify(clientBuilderMock).setSslContext(any(SSLContext.class));
112         verify(clientBuilderMock).setSslHostnameVerifier(any(NoopHostnameVerifier.class));
113         verify(clientBuilderMock).setRedirectStrategy(PublishRedirectStrategy.INSTANCE);
114         verify(clientBuilderMock).setDefaultRequestConfig(any());
115         verify(clientBuilderMock).build();
116         verifyNoMoreInteractions(clientBuilderMock);
117
118         verify(clientMock).start();
119         verify(clientMock).close();
120
121         verify(futureMock).get();
122         verifyNoMoreInteractions(futureMock);
123     }
124
125     @Test
126     void getHttpResponseWithCustomTimeout_Success() throws Exception {
127         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
128         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
129         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
130         when(clientBuilderMock.build()).thenReturn(clientMock);
131         when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock);
132         HttpResponse responseMock = mock(HttpResponse.class);
133         when(futureMock.get()).thenReturn(responseMock);
134
135         HttpGet request = new HttpGet();
136         producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT, CONTEXT_MAP);
137
138         ArgumentCaptor<RequestConfig> requestConfigCaptor = ArgumentCaptor.forClass(RequestConfig.class);
139         verify(clientBuilderMock).setSslContext(any(SSLContext.class));
140         verify(clientBuilderMock).setSslHostnameVerifier(any(NoopHostnameVerifier.class));
141         verify(clientBuilderMock).setDefaultRequestConfig(requestConfigCaptor.capture());
142         RequestConfig requestConfig = requestConfigCaptor.getValue();
143         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getSocketTimeout());
144         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectTimeout());
145         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectionRequestTimeout());
146         verify(clientBuilderMock).build();
147         verifyNoMoreInteractions(clientBuilderMock);
148
149         verify(clientMock).start();
150         verify(clientMock).close();
151
152         verify(futureMock).get();
153         verifyNoMoreInteractions(futureMock);
154     }
155
156     @Test
157     public void getResponseWithException_throwsException() throws Exception {
158         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
159         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
160         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
161         when(clientBuilderMock.build()).thenReturn(clientMock);
162         HttpPut request = new HttpPut();
163         when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock);
164
165         try {
166             when(futureMock.get()).thenThrow(new InterruptedException("Interrupted"));
167
168             producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT,
169                     CONTEXT_MAP);
170
171             fail("Should have got an exception.");
172         } catch (DatafileTaskException e) {
173             assertTrue(e.getCause() instanceof InterruptedException);
174             assertEquals("Interrupted", e.getCause().getMessage());
175         } catch (Exception e) {
176             fail("Wrong exception");
177         }
178
179         verify(clientMock).start();
180         verify(clientMock).close();
181     }
182
183     @Test
184     public void addCredentialsToHead_success() {
185         HttpPut request = new HttpPut();
186
187         producerClientUnderTestSpy.addUserCredentialsToHead(request);
188
189         String plainCreds = USER_NAME + ":" + USER_NAME;
190         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
191         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
192         String base64Creds = "Basic " + new String(base64CredsBytes);
193         Header[] authorizationHeaders = request.getHeaders("Authorization");
194         assertEquals(base64Creds, authorizationHeaders[0].getValue());
195     }
196
197     @Test
198     public void getBaseUri_success() {
199         URI uri = producerClientUnderTestSpy.getBaseUri().build();
200         assertEquals(HTTPS_SCHEME + "://" + HOST + ":" + PORT, uri.toString());
201     }
202 }