e21bbd7bfd37a0a8914e71ad445efa03fe4c17d6
[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 import java.net.URI;
30 import java.nio.charset.StandardCharsets;
31 import java.security.KeyManagementException;
32 import java.security.KeyStoreException;
33 import java.security.NoSuchAlgorithmException;
34 import java.time.Duration;
35 import java.util.HashMap;
36 import java.util.Map;
37 import java.util.concurrent.Future;
38 import javax.net.ssl.SSLContext;
39 import org.apache.commons.codec.binary.Base64;
40 import org.apache.http.Header;
41 import org.apache.http.HttpResponse;
42 import org.apache.http.client.config.RequestConfig;
43 import org.apache.http.client.methods.HttpGet;
44 import org.apache.http.client.methods.HttpPut;
45 import org.apache.http.client.methods.HttpUriRequest;
46 import org.apache.http.conn.ssl.NoopHostnameVerifier;
47 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
48 import org.junit.jupiter.api.BeforeEach;
49 import org.junit.jupiter.api.Test;
50 import org.mockito.ArgumentCaptor;
51 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
52 import org.onap.dcaegen2.collectors.datafile.http.HttpAsyncClientBuilderWrapper;
53 import org.onap.dcaegen2.collectors.datafile.web.PublishRedirectStrategy;
54 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
55
56 /**
57  * Test for DmaapProducerHttpClient.
58  *
59  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18
60  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
61  */
62 class DmaapProducerHttpClientTest {
63
64     private static final String HOST = "54.45.33.2";
65     private static final String HTTPS_SCHEME = "https";
66     private static final int PORT = 1234;
67     private static final String USER_NAME = "dradmin";
68     private static final Duration TWO_SECOND_TIMEOUT = Duration.ofSeconds(2);
69
70     private static final Map<String, String> CONTEXT_MAP = new HashMap<>();
71
72
73     private DmaapProducerHttpClient producerClientUnderTestSpy;
74
75     private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
76
77     private HttpAsyncClientBuilderWrapper clientBuilderMock;
78
79     private CloseableHttpAsyncClient clientMock;
80     @SuppressWarnings("unchecked")
81     private Future<HttpResponse> futureMock = mock(Future.class);
82
83     @BeforeEach
84     void setUp() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
85         when(dmaapPublisherConfigurationMock.dmaapHostName()).thenReturn(HOST);
86         when(dmaapPublisherConfigurationMock.dmaapProtocol()).thenReturn(HTTPS_SCHEME);
87         when(dmaapPublisherConfigurationMock.dmaapPortNumber()).thenReturn(PORT);
88         when(dmaapPublisherConfigurationMock.dmaapUserName()).thenReturn("dradmin");
89         when(dmaapPublisherConfigurationMock.dmaapUserPassword()).thenReturn("dradmin");
90
91         producerClientUnderTestSpy = spy(new DmaapProducerHttpClient(dmaapPublisherConfigurationMock));
92
93         clientBuilderMock = mock(HttpAsyncClientBuilderWrapper.class);
94         clientMock = mock(CloseableHttpAsyncClient.class);
95     }
96
97     @Test
98     void getHttpResponseWithRederict_Success() throws Exception {
99         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
100         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
101         when(clientBuilderMock.setSslHostnameVerifier(any(NoopHostnameVerifier.class))).thenReturn(clientBuilderMock);
102         when(clientBuilderMock.build()).thenReturn(clientMock);
103         when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock);
104         HttpResponse responseMock = mock(HttpResponse.class);
105         when(futureMock.get()).thenReturn(responseMock);
106
107         HttpGet request = new HttpGet();
108         producerClientUnderTestSpy.getDmaapProducerResponseWithRedirect(request, CONTEXT_MAP);
109
110         verify(clientBuilderMock).setSslContext(any(SSLContext.class));
111         verify(clientBuilderMock).setSslHostnameVerifier(any(NoopHostnameVerifier.class));
112         verify(clientBuilderMock).setRedirectStrategy(any(PublishRedirectStrategy.class));
113         verify(clientBuilderMock).setDefaultRequestConfig(any());
114         verify(clientBuilderMock).build();
115         verifyNoMoreInteractions(clientBuilderMock);
116
117         verify(clientMock).start();
118         verify(clientMock).close();
119
120         verify(futureMock).get();
121         verifyNoMoreInteractions(futureMock);
122     }
123
124     @Test
125     void getHttpResponseWithCustomTimeout_Success() throws Exception {
126         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
127         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
128         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
129         when(clientBuilderMock.build()).thenReturn(clientMock);
130         when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock);
131         HttpResponse responseMock = mock(HttpResponse.class);
132         when(futureMock.get()).thenReturn(responseMock);
133
134         HttpGet request = new HttpGet();
135         producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT, CONTEXT_MAP);
136
137         ArgumentCaptor<RequestConfig> requestConfigCaptor = ArgumentCaptor.forClass(RequestConfig.class);
138         verify(clientBuilderMock).setSslContext(any(SSLContext.class));
139         verify(clientBuilderMock).setSslHostnameVerifier(any(NoopHostnameVerifier.class));
140         verify(clientBuilderMock).setDefaultRequestConfig(requestConfigCaptor.capture());
141         RequestConfig requestConfig = requestConfigCaptor.getValue();
142         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getSocketTimeout());
143         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectTimeout());
144         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectionRequestTimeout());
145         verify(clientBuilderMock).build();
146         verifyNoMoreInteractions(clientBuilderMock);
147
148         verify(clientMock).start();
149         verify(clientMock).close();
150
151         verify(futureMock).get();
152         verifyNoMoreInteractions(futureMock);
153     }
154
155     @Test
156     public void getResponseWithException_throwsException() throws Exception {
157         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
158         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
159         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
160         when(clientBuilderMock.build()).thenReturn(clientMock);
161         HttpPut request = new HttpPut();
162         when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock);
163
164         try {
165             when(futureMock.get()).thenThrow(new InterruptedException("Interrupted"));
166
167             producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT,
168                     CONTEXT_MAP);
169
170             fail("Should have got an exception.");
171         } catch (DatafileTaskException e) {
172             assertTrue(e.getCause() instanceof InterruptedException);
173             assertEquals("Interrupted", e.getCause().getMessage());
174         } catch (Exception e) {
175             fail("Wrong exception");
176         }
177
178         verify(clientMock).start();
179         verify(clientMock).close();
180     }
181
182     @Test
183     public void addCredentialsToHead_success() {
184         HttpPut request = new HttpPut();
185
186         producerClientUnderTestSpy.addUserCredentialsToHead(request);
187
188         String plainCreds = USER_NAME + ":" + USER_NAME;
189         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
190         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
191         String base64Creds = "Basic " + new String(base64CredsBytes);
192         Header[] authorizationHeaders = request.getHeaders("Authorization");
193         assertEquals(base64Creds, authorizationHeaders[0].getValue());
194     }
195
196     @Test
197     public void getBaseUri_success() {
198         URI uri = producerClientUnderTestSpy.getBaseUri().build();
199         assertEquals(HTTPS_SCHEME + "://" + HOST + ":" + PORT, uri.toString());
200     }
201 }