a71521cd1e1eff2c35e1c63a5d8052e3e3ee2da7
[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.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.exceptions.DatafileTaskException;
54 import org.onap.dcaegen2.collectors.datafile.http.HttpAsyncClientBuilderWrapper;
55 import org.onap.dcaegen2.collectors.datafile.web.PublishRedirectStrategy;
56 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
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
75     private DmaapProducerHttpClient producerClientUnderTestSpy;
76
77     private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
78
79     private HttpAsyncClientBuilderWrapper clientBuilderMock;
80
81     private CloseableHttpAsyncClient clientMock;
82     @SuppressWarnings("unchecked")
83     private Future<HttpResponse> futureMock = mock(Future.class);
84
85     @BeforeEach
86     void setUp() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
87         when(dmaapPublisherConfigurationMock.dmaapHostName()).thenReturn(HOST);
88         when(dmaapPublisherConfigurationMock.dmaapProtocol()).thenReturn(HTTPS_SCHEME);
89         when(dmaapPublisherConfigurationMock.dmaapPortNumber()).thenReturn(PORT);
90         when(dmaapPublisherConfigurationMock.dmaapUserName()).thenReturn("dradmin");
91         when(dmaapPublisherConfigurationMock.dmaapUserPassword()).thenReturn("dradmin");
92
93         producerClientUnderTestSpy = spy(new DmaapProducerHttpClient(dmaapPublisherConfigurationMock));
94
95         clientBuilderMock = mock(HttpAsyncClientBuilderWrapper.class);
96         clientMock = mock(CloseableHttpAsyncClient.class);
97     }
98
99     @Test
100     void getHttpResponseWithRederict_Success() throws Exception {
101         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
102         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
103         when(clientBuilderMock.setSslHostnameVerifier(any(NoopHostnameVerifier.class))).thenReturn(clientBuilderMock);
104         when(clientBuilderMock.build()).thenReturn(clientMock);
105         when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock);
106         HttpResponse responseMock = mock(HttpResponse.class);
107         when(futureMock.get()).thenReturn(responseMock);
108
109         HttpGet request = new HttpGet();
110         producerClientUnderTestSpy.getDmaapProducerResponseWithRedirect(request, CONTEXT_MAP);
111
112         verify(clientBuilderMock).setSslContext(any(SSLContext.class));
113         verify(clientBuilderMock).setSslHostnameVerifier(any(NoopHostnameVerifier.class));
114         verify(clientBuilderMock).setRedirectStrategy(any(PublishRedirectStrategy.class));
115         verify(clientBuilderMock).setDefaultRequestConfig(any());
116         verify(clientBuilderMock).build();
117         verifyNoMoreInteractions(clientBuilderMock);
118
119         verify(clientMock).start();
120         verify(clientMock).close();
121
122         verify(futureMock).get();
123         verifyNoMoreInteractions(futureMock);
124     }
125
126     @Test
127     void getHttpResponseWithCustomTimeout_Success() throws Exception {
128         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
129         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
130         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
131         when(clientBuilderMock.build()).thenReturn(clientMock);
132         when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock);
133         HttpResponse responseMock = mock(HttpResponse.class);
134         when(futureMock.get()).thenReturn(responseMock);
135
136         HttpGet request = new HttpGet();
137         producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT, CONTEXT_MAP);
138
139         ArgumentCaptor<RequestConfig> requestConfigCaptor = ArgumentCaptor.forClass(RequestConfig.class);
140         verify(clientBuilderMock).setSslContext(any(SSLContext.class));
141         verify(clientBuilderMock).setSslHostnameVerifier(any(NoopHostnameVerifier.class));
142         verify(clientBuilderMock).setDefaultRequestConfig(requestConfigCaptor.capture());
143         RequestConfig requestConfig = requestConfigCaptor.getValue();
144         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getSocketTimeout());
145         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectTimeout());
146         assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectionRequestTimeout());
147         verify(clientBuilderMock).build();
148         verifyNoMoreInteractions(clientBuilderMock);
149
150         verify(clientMock).start();
151         verify(clientMock).close();
152
153         verify(futureMock).get();
154         verifyNoMoreInteractions(futureMock);
155     }
156
157     @Test
158     public void getResponseWithException_throwsException() throws Exception {
159         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
160         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
161         when(clientBuilderMock.setSslContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
162         when(clientBuilderMock.build()).thenReturn(clientMock);
163         HttpPut request = new HttpPut();
164         when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock);
165
166         try {
167             when(futureMock.get()).thenThrow(new InterruptedException("Interrupted"));
168
169             producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT,
170                     CONTEXT_MAP);
171
172             fail("Should have got an exception.");
173         } catch (DatafileTaskException e) {
174             assertTrue(e.getCause() instanceof InterruptedException);
175             assertEquals("Interrupted", e.getCause().getMessage());
176         } catch (Exception e) {
177             fail("Wrong exception");
178         }
179
180         verify(clientMock).start();
181         verify(clientMock).close();
182     }
183
184     @Test
185     public void addCredentialsToHead_success() {
186         HttpPut request = new HttpPut();
187
188         producerClientUnderTestSpy.addUserCredentialsToHead(request);
189
190         String plainCreds = USER_NAME + ":" + USER_NAME;
191         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
192         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
193         String base64Creds = "Basic " + new String(base64CredsBytes);
194         Header[] authorizationHeaders = request.getHeaders("Authorization");
195         assertEquals(base64Creds, authorizationHeaders[0].getValue());
196     }
197 }