91c4c334a1c5a901095f927dc7cf493e9ae91401
[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.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.IHttpAsyncClientBuilder;
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  * @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 DmaapProducerReactiveHttpClientTest {
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 int TWO_SECOND_TIMEOUT = 2000;
69
70     private static final Map<String, String> CONTEXT_MAP = new HashMap<>();
71
72
73     private DmaapProducerReactiveHttpClient producerClientUnderTestSpy;
74
75     private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
76
77     private IHttpAsyncClientBuilder 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 DmaapProducerReactiveHttpClient(dmaapPublisherConfigurationMock));
92
93         clientBuilderMock = mock(IHttpAsyncClientBuilder.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(PublishRedirectStrategy.INSTANCE);
113         verify(clientBuilderMock).build();
114         verifyNoMoreInteractions(clientBuilderMock);
115
116         verify(clientMock).start();
117         verify(clientMock).close();
118
119         verify(futureMock).get();
120         verifyNoMoreInteractions(futureMock);
121     }
122
123     @Test
124     void getHttpResponseWithCustomTimeout_Success() throws Exception {
125         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
126         when(clientBuilderMock.setSSLContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
127         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
128         when(clientBuilderMock.build()).thenReturn(clientMock);
129         when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock);
130         HttpResponse responseMock = mock(HttpResponse.class);
131         when(futureMock.get()).thenReturn(responseMock);
132
133         HttpGet request = new HttpGet();
134         producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT, CONTEXT_MAP);
135
136         ArgumentCaptor<RequestConfig> requestConfigCaptor = ArgumentCaptor.forClass(RequestConfig.class);
137         verify(clientBuilderMock).setSSLContext(any(SSLContext.class));
138         verify(clientBuilderMock).setSSLHostnameVerifier(any(NoopHostnameVerifier.class));
139         verify(clientBuilderMock).setDefaultRequestConfig(requestConfigCaptor.capture());
140         RequestConfig requestConfig = requestConfigCaptor.getValue();
141         assertEquals(TWO_SECOND_TIMEOUT, requestConfig.getSocketTimeout());
142         assertEquals(TWO_SECOND_TIMEOUT, requestConfig.getConnectTimeout());
143         assertEquals(TWO_SECOND_TIMEOUT, requestConfig.getConnectionRequestTimeout());
144         verify(clientBuilderMock).build();
145         verifyNoMoreInteractions(clientBuilderMock);
146
147         verify(clientMock).start();
148         verify(clientMock).close();
149
150         verify(futureMock).get();
151         verifyNoMoreInteractions(futureMock);
152     }
153
154     @Test
155     public void getResponseWithException_throwsException() throws Exception {
156         doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder();
157         when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock);
158         when(clientBuilderMock.setSSLContext(any(SSLContext.class))).thenReturn(clientBuilderMock);
159         when(clientBuilderMock.build()).thenReturn(clientMock);
160         HttpPut request = new HttpPut();
161         when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock);
162
163         try {
164             when(futureMock.get()).thenThrow(new InterruptedException("Interrupted"));
165
166             producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT,
167                     CONTEXT_MAP);
168
169             fail("Should have got an exception.");
170         } catch (DatafileTaskException e) {
171             assertTrue(e.getCause() instanceof InterruptedException);
172             assertEquals("Interrupted", e.getCause().getMessage());
173         } catch (Exception e) {
174             fail("Wrong exception");
175         }
176
177         verify(clientMock).start();
178         verify(clientMock).close();
179     }
180
181     @Test
182     public void addCredentialsToHead_success() {
183         HttpPut request = new HttpPut();
184
185         producerClientUnderTestSpy.addUserCredentialsToHead(request);
186
187         String plainCreds = USER_NAME + ":" + USER_NAME;
188         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
189         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
190         String base64Creds = "Basic " + new String(base64CredsBytes);
191         Header[] authorizationHeaders = request.getHeaders("Authorization");
192         assertEquals(base64Creds, authorizationHeaders[0].getValue());
193     }
194
195     @Test
196     public void getBaseUri_success() {
197         URI uri = producerClientUnderTestSpy.getBaseUri().build();
198         assertEquals(HTTPS_SCHEME + "://" + HOST + ":" + PORT, uri.toString());
199     }
200 }