ed8b93f1626349cc8f18a34b468bee3f412aa6ea
[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.tasks;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertTrue;
21 import static org.mockito.ArgumentMatchers.any;
22 import static org.mockito.Mockito.doReturn;
23 import static org.mockito.Mockito.mock;
24 import static org.mockito.Mockito.spy;
25 import static org.mockito.Mockito.times;
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.io.ByteArrayInputStream;
31 import java.io.InputStream;
32 import java.net.URI;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.time.Duration;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40
41 import org.apache.http.Header;
42 import org.apache.http.HttpResponse;
43 import org.apache.http.StatusLine;
44 import org.apache.http.client.methods.HttpPut;
45 import org.apache.http.client.methods.HttpUriRequest;
46 import org.junit.jupiter.api.BeforeAll;
47 import org.junit.jupiter.api.Test;
48 import org.mockito.ArgumentCaptor;
49 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
50 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
51 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
52 import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel;
53 import org.onap.dcaegen2.collectors.datafile.service.producer.DmaapProducerReactiveHttpClient;
54 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
55 import org.springframework.http.HttpStatus;
56 import org.springframework.web.util.DefaultUriBuilderFactory;
57 import org.springframework.web.util.UriBuilder;
58
59 import reactor.test.StepVerifier;
60
61 /**
62  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/17/18
63  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
64  */
65 class DataRouterPublisherTest {
66     private static final String PRODUCT_NAME = "NrRadio";
67     private static final String VENDOR_NAME = "Ericsson";
68     private static final String LAST_EPOCH_MICROSEC = "8745745764578";
69     private static final String SOURCE_NAME = "oteNB5309";
70     private static final String START_EPOCH_MICROSEC = "8745745764578";
71     private static final String TIME_ZONE_OFFSET = "UTC+05:00";
72     private static final String PM_FILE_NAME = "A20161224.1030-1045.bin.gz";
73     private static final String FTPES_ADDRESS = "ftpes://192.168.0.101:22/ftp/rop/" + PM_FILE_NAME;
74     private static final String LOCAL_FILE_NAME = SOURCE_NAME + "_" + PM_FILE_NAME;
75
76     private static final String COMPRESSION = "gzip";
77     private static final String FILE_FORMAT_TYPE = "org.3GPP.32.435#measCollec";
78     private static final String FILE_FORMAT_VERSION = "V10";
79     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
80
81     private static final String HOST = "54.45.33.2";
82     private static final String HTTPS_SCHEME = "https";
83     private static final int PORT = 1234;
84     private static final String APPLICATION_OCTET_STREAM_CONTENT_TYPE = "application/octet-stream";
85     private static final String PUBLISH_TOPIC = "publish";
86     private static final String FEED_ID = "1";
87     private static final String FILE_CONTENT = "Just a string.";
88
89     private static final Map<String, String> CONTEXT_MAP = new HashMap<>();
90
91     private static ConsumerDmaapModel consumerDmaapModel;
92     private static DmaapProducerReactiveHttpClient httpClientMock;
93     private static AppConfig appConfig;
94     private static DmaapPublisherConfiguration publisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
95
96     private static DataRouterPublisher publisherTaskUnderTestSpy;
97
98     /**
99      * Sets up data for tests.
100      */
101     @BeforeAll
102     public static void setUp() {
103         when(publisherConfigurationMock.dmaapHostName()).thenReturn(HOST);
104         when(publisherConfigurationMock.dmaapProtocol()).thenReturn(HTTPS_SCHEME);
105         when(publisherConfigurationMock.dmaapPortNumber()).thenReturn(PORT);
106
107         consumerDmaapModel = ImmutableConsumerDmaapModel.builder() //
108                 .productName(PRODUCT_NAME) //
109                 .vendorName(VENDOR_NAME) //
110                 .lastEpochMicrosec(LAST_EPOCH_MICROSEC) //
111                 .sourceName(SOURCE_NAME) //
112                 .startEpochMicrosec(START_EPOCH_MICROSEC) //
113                 .timeZoneOffset(TIME_ZONE_OFFSET) //
114                 .name(PM_FILE_NAME) //
115                 .location(FTPES_ADDRESS) //
116                 .internalLocation(Paths.get("target/" + LOCAL_FILE_NAME)) //
117                 .compression("gzip") //
118                 .fileFormatType(FILE_FORMAT_TYPE) //
119                 .fileFormatVersion(FILE_FORMAT_VERSION) //
120                 .build(); //
121         appConfig = mock(AppConfig.class);
122         publisherTaskUnderTestSpy = spy(new DataRouterPublisher(appConfig));
123     }
124
125     @Test
126     public void whenPassedObjectFits_ReturnsCorrectStatus() throws Exception {
127         prepareMocksForTests(null, Integer.valueOf(HttpStatus.OK.value()));
128
129         StepVerifier
130                 .create(publisherTaskUnderTestSpy.execute(consumerDmaapModel, 1, Duration.ofSeconds(0), CONTEXT_MAP))
131                 .expectNext(consumerDmaapModel) //
132                 .verifyComplete();
133
134         ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class);
135         verify(httpClientMock).getBaseUri();
136         verify(httpClientMock).addUserCredentialsToHead(any(HttpUriRequest.class));
137         verify(httpClientMock).getDmaapProducerResponseWithRedirect(requestCaptor.capture(), any());
138         verifyNoMoreInteractions(httpClientMock);
139
140         HttpPut actualPut = (HttpPut) requestCaptor.getValue();
141         URI actualUri = actualPut.getURI();
142         assertEquals(HTTPS_SCHEME, actualUri.getScheme());
143         assertEquals(HOST, actualUri.getHost());
144         assertEquals(PORT, actualUri.getPort());
145         Path actualPath = Paths.get(actualUri.getPath());
146         assertTrue(PUBLISH_TOPIC.equals(actualPath.getName(0).toString()));
147         assertTrue(FEED_ID.equals(actualPath.getName(1).toString()));
148         assertTrue(LOCAL_FILE_NAME.equals(actualPath.getName(2).toString()));
149
150         Header[] contentHeaders = actualPut.getHeaders("content-type");
151         assertEquals(APPLICATION_OCTET_STREAM_CONTENT_TYPE, contentHeaders[0].getValue());
152
153         Header[] metaHeaders = actualPut.getHeaders(X_DMAAP_DR_META);
154         Map<String, String> metaHash = getMetaDataAsMap(metaHeaders);
155         assertTrue(10 == metaHash.size());
156         assertEquals(PRODUCT_NAME, metaHash.get("productName"));
157         assertEquals(VENDOR_NAME, metaHash.get("vendorName"));
158         assertEquals(LAST_EPOCH_MICROSEC, metaHash.get("lastEpochMicrosec"));
159         assertEquals(SOURCE_NAME, metaHash.get("sourceName"));
160         assertEquals(START_EPOCH_MICROSEC, metaHash.get("startEpochMicrosec"));
161         assertEquals(TIME_ZONE_OFFSET, metaHash.get("timeZoneOffset"));
162         assertEquals(COMPRESSION, metaHash.get("compression"));
163         assertEquals(FTPES_ADDRESS, metaHash.get("location"));
164         assertEquals(FILE_FORMAT_TYPE, metaHash.get("fileFormatType"));
165         assertEquals(FILE_FORMAT_VERSION, metaHash.get("fileFormatVersion"));
166     }
167
168     @Test
169     void whenPassedObjectFits_firstFailsWithExceptionThenSucceeds() throws Exception {
170         prepareMocksForTests(new DatafileTaskException("Error"), HttpStatus.OK.value());
171
172         StepVerifier
173                 .create(publisherTaskUnderTestSpy.execute(consumerDmaapModel, 2, Duration.ofSeconds(0), CONTEXT_MAP))
174                 .expectNext(consumerDmaapModel) //
175                 .verifyComplete();
176     }
177
178     @Test
179     public void whenPassedObjectFits_firstFailsThenSucceeds() throws Exception {
180         prepareMocksForTests(null, Integer.valueOf(HttpStatus.BAD_GATEWAY.value()),
181                 Integer.valueOf(HttpStatus.OK.value()));
182
183         StepVerifier
184                 .create(publisherTaskUnderTestSpy.execute(consumerDmaapModel, 1, Duration.ofSeconds(0), CONTEXT_MAP))
185                 .expectNext(consumerDmaapModel) //
186                 .verifyComplete();
187
188         verify(httpClientMock, times(2)).getBaseUri();
189         verify(httpClientMock, times(2)).addUserCredentialsToHead(any(HttpUriRequest.class));
190         verify(httpClientMock, times(2)).getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any());
191         verifyNoMoreInteractions(httpClientMock);
192     }
193
194     @Test
195     public void whenPassedObjectFits_firstFailsThenFails() throws Exception {
196         prepareMocksForTests(null, Integer.valueOf(HttpStatus.BAD_GATEWAY.value()),
197                 Integer.valueOf((HttpStatus.BAD_GATEWAY.value())));
198
199         StepVerifier
200                 .create(publisherTaskUnderTestSpy.execute(consumerDmaapModel, 1, Duration.ofSeconds(0), CONTEXT_MAP))
201                 .expectErrorMessage("Retries exhausted: 1/1") //
202                 .verify();
203
204         verify(httpClientMock, times(2)).getBaseUri();
205         verify(httpClientMock, times(2)).addUserCredentialsToHead(any(HttpUriRequest.class));
206         verify(httpClientMock, times(2)).getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any());
207         verifyNoMoreInteractions(httpClientMock);
208     }
209
210     @SafeVarargs
211     final void prepareMocksForTests(Exception exception, Integer firstResponse, Integer... nextHttpResponses)
212             throws Exception {
213         httpClientMock = mock(DmaapProducerReactiveHttpClient.class);
214         when(appConfig.getDmaapPublisherConfiguration()).thenReturn(publisherConfigurationMock);
215         doReturn(publisherConfigurationMock).when(publisherTaskUnderTestSpy).resolveConfiguration();
216         doReturn(httpClientMock).when(publisherTaskUnderTestSpy).resolveClient();
217
218         UriBuilder uriBuilder = new DefaultUriBuilderFactory().builder().scheme(HTTPS_SCHEME).host(HOST).port(PORT);
219         when(httpClientMock.getBaseUri()).thenReturn(uriBuilder);
220
221         HttpResponse httpResponseMock = mock(HttpResponse.class);
222         if (exception == null) {
223             when(httpClientMock.getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any()))
224                     .thenReturn(httpResponseMock);
225         } else {
226             when(httpClientMock.getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any()))
227                     .thenThrow(exception).thenReturn(httpResponseMock);
228         }
229         StatusLine statusLineMock = mock(StatusLine.class);
230         when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock);
231         when(statusLineMock.getStatusCode()).thenReturn(firstResponse, nextHttpResponses);
232
233         InputStream fileStream = new ByteArrayInputStream(FILE_CONTENT.getBytes());
234         doReturn(fileStream).when(publisherTaskUnderTestSpy).createInputStream(Paths.get("target", LOCAL_FILE_NAME));
235     }
236
237     private Map<String, String> getMetaDataAsMap(Header[] metaHeaders) {
238         Map<String, String> metaHash = new HashMap<>();
239         String actualMetaData = metaHeaders[0].getValue();
240         actualMetaData = actualMetaData.substring(1, actualMetaData.length() - 1);
241         actualMetaData = actualMetaData.replace("\"", "");
242         String[] commaSplitedMetaData = actualMetaData.split(",");
243         for (int i = 0; i < commaSplitedMetaData.length; i++) {
244             String[] keyValuePair = commaSplitedMetaData[i].split(":");
245             if (keyValuePair.length > 2) {
246                 List<String> arrayKeyValuePair = new ArrayList<>(keyValuePair.length);
247                 for (int j = 1; j < keyValuePair.length; j++) {
248                     arrayKeyValuePair.add(keyValuePair[j]);
249                 }
250                 keyValuePair[1] = String.join(":", arrayKeyValuePair);
251             }
252             metaHash.put(keyValuePair[0], keyValuePair[1]);
253         }
254         return metaHash;
255     }
256 }