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