ddc279c236eb4cf03a20c05d22338eccb66f1eb7
[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.Assert.assertEquals;
20 import static org.junit.Assert.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 ch.qos.logback.classic.spi.ILoggingEvent;
31 import ch.qos.logback.core.read.ListAppender;
32 import java.io.File;
33 import java.net.URI;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.time.Duration;
37 import java.util.ArrayList;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Map;
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.BeforeEach;
48 import org.junit.jupiter.api.Test;
49 import org.mockito.ArgumentCaptor;
50 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
51 import org.onap.dcaegen2.collectors.datafile.configuration.PublisherConfiguration;
52 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
53 import org.onap.dcaegen2.collectors.datafile.model.Counters;
54 import org.onap.dcaegen2.collectors.datafile.model.FilePublishInformation;
55 import org.onap.dcaegen2.collectors.datafile.model.ImmutableFilePublishInformation;
56 import org.onap.dcaegen2.collectors.datafile.service.producer.DmaapProducerHttpClient;
57 import org.onap.dcaegen2.collectors.datafile.utils.LoggingUtils;
58 import org.springframework.http.HttpStatus;
59 import reactor.test.StepVerifier;
60
61 /**
62  * Tests the DataRouter publisher.
63  *
64  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/17/18
65  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
66  */
67 class DataRouterPublisherTest {
68
69     private static final String PRODUCT_NAME = "NrRadio";
70     private static final String VENDOR_NAME = "Ericsson";
71     private static final String LAST_EPOCH_MICROSEC = "8745745764578";
72     private static final String SOURCE_NAME = "oteNB5309";
73     private static final String START_EPOCH_MICROSEC = "8745745764578";
74     private static final String TIME_ZONE_OFFSET = "UTC+05:00";
75     private static final String PM_FILE_NAME = "A20161224.1030-1045.bin.gz";
76     private static final String FTPES_ADDRESS = "ftpes://192.168.0.101:22/ftp/rop/" + PM_FILE_NAME;
77     private static final String CHANGE_IDENTIFIER = "PM_MEAS_FILES";
78
79     private static final String COMPRESSION = "gzip";
80     private static final String FILE_FORMAT_TYPE = "org.3GPP.32.435#measCollec";
81     private static final String FILE_FORMAT_VERSION = "V10";
82     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
83
84     private static final String HOST = "54.45.33.2";
85     private static final String HTTPS_SCHEME = "https";
86     private static final int PORT = 1234;
87     private static final String APPLICATION_OCTET_STREAM_CONTENT_TYPE = "application/octet-stream";
88     private static final String PUBLISH_TOPIC = "publish";
89     private static final String FEED_ID = "1";
90
91     // "https://54.45.333.2:1234/publish/1";
92     private static final String PUBLISH_URL =
93         HTTPS_SCHEME + "://" + HOST + ":" + PORT + "/" + PUBLISH_TOPIC + "/" + FEED_ID;
94
95     private static FilePublishInformation filePublishInformation;
96     private static DmaapProducerHttpClient httpClientMock;
97     private static AppConfig appConfig;
98     private static PublisherConfiguration publisherConfigurationMock = mock(PublisherConfiguration.class);
99     private static Map<String, String> context = new HashMap<>();
100     private static DataRouterPublisher publisherTaskUnderTestSpy;
101     private static final Counters counters = new Counters();
102
103     @BeforeAll
104     public static void setUp() {
105         when(publisherConfigurationMock.publishUrl()).thenReturn(PUBLISH_URL);
106
107         filePublishInformation = ImmutableFilePublishInformation.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/" + PM_FILE_NAME)) //
117             .compression("gzip") //
118             .fileFormatType(FILE_FORMAT_TYPE) //
119             .fileFormatVersion(FILE_FORMAT_VERSION) //
120             .context(context) //
121             .changeIdentifier(CHANGE_IDENTIFIER) //
122             .build(); //
123         appConfig = mock(AppConfig.class);
124         publisherTaskUnderTestSpy = spy(new DataRouterPublisher(appConfig, counters));
125     }
126
127     @BeforeEach
128     void setUpTest() {
129         counters.clear();
130     }
131
132     @Test
133     public void whenPassedObjectFits_ReturnsCorrectStatus() throws Exception {
134         prepareMocksForTests(null, Integer.valueOf(HttpStatus.OK.value()));
135         StepVerifier //
136             .create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 1, Duration.ofSeconds(0)))
137             .expectNext(filePublishInformation) //
138             .verifyComplete();
139
140         ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class);
141         verify(httpClientMock).addUserCredentialsToHead(any(HttpUriRequest.class));
142         verify(httpClientMock).getDmaapProducerResponseWithRedirect(requestCaptor.capture(), any());
143         verifyNoMoreInteractions(httpClientMock);
144
145         HttpPut actualPut = (HttpPut) requestCaptor.getValue();
146         URI actualUri = actualPut.getURI();
147         assertEquals(HTTPS_SCHEME, actualUri.getScheme());
148         assertEquals(HOST, actualUri.getHost());
149         assertEquals(PORT, actualUri.getPort());
150
151         Path actualPath = Paths.get(actualUri.getPath());
152         assertTrue(PUBLISH_TOPIC.equals(actualPath.getName(0).toString()));
153         assertTrue(FEED_ID.equals(actualPath.getName(1).toString()));
154         assertTrue(PM_FILE_NAME.equals(actualPath.getName(2).toString()));
155
156         Header[] contentHeaders = actualPut.getHeaders("content-type");
157         assertEquals(APPLICATION_OCTET_STREAM_CONTENT_TYPE, contentHeaders[0].getValue());
158
159         Header[] metaHeaders = actualPut.getHeaders(X_DMAAP_DR_META);
160         Map<String, String> metaHash = getMetaDataAsMap(metaHeaders);
161
162         assertEquals(PRODUCT_NAME, metaHash.get("productName"));
163         assertEquals(VENDOR_NAME, metaHash.get("vendorName"));
164         assertEquals(LAST_EPOCH_MICROSEC, metaHash.get("lastEpochMicrosec"));
165         assertEquals(SOURCE_NAME, metaHash.get("sourceName"));
166         assertEquals(START_EPOCH_MICROSEC, metaHash.get("startEpochMicrosec"));
167         assertEquals(TIME_ZONE_OFFSET, metaHash.get("timeZoneOffset"));
168         assertEquals(COMPRESSION, metaHash.get("compression"));
169         assertEquals(FTPES_ADDRESS, metaHash.get("location"));
170         assertEquals(FILE_FORMAT_TYPE, metaHash.get("fileFormatType"));
171         assertEquals(FILE_FORMAT_VERSION, metaHash.get("fileFormatVersion"));
172
173         // Note that the following line checks the number of properties that are sent to the data
174         // router.
175         // This should be 10 unless the API is updated (which is the fields checked above)
176         assertEquals(10, metaHash.size());
177
178         assertEquals("totalPublishedFiles should have been 1", 1, counters.getTotalPublishedFiles());
179         assertEquals("noOfFailedPublishAttempts should have been 0", 0, counters.getNoOfFailedPublishAttempts());
180     }
181
182     @Test
183     void whenPassedObjectFits_firstFailsWithExceptionThenSucceeds() throws Exception {
184         prepareMocksForTests(new DatafileTaskException("Error"), HttpStatus.OK.value());
185
186         ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DataRouterPublisher.class);
187         StepVerifier.create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 2, Duration.ofSeconds(0)))
188             .expectNext(filePublishInformation) //
189             .verifyComplete();
190
191         assertTrue("Warning missing in log",
192             logAppender.list.toString().contains("[WARN] Publishing file " + PM_FILE_NAME + " to DR unsuccessful."));
193
194         assertEquals("totalPublishedFiles should have been 1", 1, counters.getTotalPublishedFiles());
195         assertEquals("noOfFailedPublishAttempts should have been 1", 1, counters.getNoOfFailedPublishAttempts());
196     }
197
198     @Test
199     public void whenPassedObjectFits_firstFailsThenSucceeds() throws Exception {
200         prepareMocksForTests(null, Integer.valueOf(HttpStatus.BAD_GATEWAY.value()),
201             Integer.valueOf(HttpStatus.OK.value()));
202
203         StepVerifier //
204             .create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 1, Duration.ofSeconds(0)))
205             .expectNext(filePublishInformation) //
206             .verifyComplete();
207
208         verify(httpClientMock, times(2)).addUserCredentialsToHead(any(HttpUriRequest.class));
209         verify(httpClientMock, times(2)).getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any());
210         verifyNoMoreInteractions(httpClientMock);
211
212         assertEquals("totalPublishedFiles should have been 1", 1, counters.getTotalPublishedFiles());
213         assertEquals("noOfFailedPublishAttempts should have been 1", 1, counters.getNoOfFailedPublishAttempts());
214     }
215
216     @Test
217     public void whenPassedObjectFits_firstFailsThenFails() throws Exception {
218         prepareMocksForTests(null, Integer.valueOf(HttpStatus.BAD_GATEWAY.value()),
219             Integer.valueOf((HttpStatus.BAD_GATEWAY.value())));
220
221         ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DataRouterPublisher.class);
222         StepVerifier.create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 1, Duration.ofSeconds(0)))
223             .expectErrorMessage("Retries exhausted: 1/1") //
224             .verify();
225
226         assertTrue("Warning missing in log", logAppender.list.toString().contains("[WARN] Publishing file "
227             + PM_FILE_NAME + " to DR unsuccessful. Response code: " + HttpStatus.BAD_GATEWAY));
228
229         verify(httpClientMock, times(2)).addUserCredentialsToHead(any(HttpUriRequest.class));
230         verify(httpClientMock, times(2)).getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any());
231         verifyNoMoreInteractions(httpClientMock);
232
233         assertEquals("totalPublishedFiles should have been 0", 0, counters.getTotalPublishedFiles());
234         assertEquals("noOfFailedPublishAttempts should have been 2", 2, counters.getNoOfFailedPublishAttempts());
235     }
236
237     @SafeVarargs
238     final void prepareMocksForTests(Exception exception, Integer firstResponse, Integer... nextHttpResponses)
239         throws Exception {
240         httpClientMock = mock(DmaapProducerHttpClient.class);
241         when(appConfig.getPublisherConfiguration(CHANGE_IDENTIFIER)).thenReturn(publisherConfigurationMock);
242         doReturn(publisherConfigurationMock).when(publisherTaskUnderTestSpy).resolveConfiguration(CHANGE_IDENTIFIER);
243         doReturn(httpClientMock).when(publisherTaskUnderTestSpy).resolveClient(CHANGE_IDENTIFIER);
244
245         HttpResponse httpResponseMock = mock(HttpResponse.class);
246         if (exception == null) {
247             when(httpClientMock.getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any()))
248                 .thenReturn(httpResponseMock);
249         } else {
250             when(httpClientMock.getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any()))
251                 .thenThrow(exception).thenReturn(httpResponseMock);
252         }
253         StatusLine statusLineMock = mock(StatusLine.class);
254         when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock);
255         when(statusLineMock.getStatusCode()).thenReturn(firstResponse, nextHttpResponses);
256
257         File file = File.createTempFile("DFC", "tmp");
258         doReturn(file).when(publisherTaskUnderTestSpy).createInputFile(Paths.get("target", PM_FILE_NAME));
259     }
260
261     private Map<String, String> getMetaDataAsMap(Header[] metaHeaders) {
262         Map<String, String> metaHash = new HashMap<>();
263         String actualMetaData = metaHeaders[0].getValue();
264         actualMetaData = actualMetaData.substring(1, actualMetaData.length() - 1);
265         actualMetaData = actualMetaData.replace("\"", "");
266         String[] commaSplitedMetaData = actualMetaData.split(",");
267         for (int i = 0; i < commaSplitedMetaData.length; i++) {
268             String[] keyValuePair = commaSplitedMetaData[i].split(":");
269             if (keyValuePair.length > 2) {
270                 List<String> arrayKeyValuePair = new ArrayList<>(keyValuePair.length);
271                 for (int j = 1; j < keyValuePair.length; j++) {
272                     arrayKeyValuePair.add(keyValuePair[j]);
273                 }
274                 keyValuePair[1] = String.join(":", arrayKeyValuePair);
275             }
276             metaHash.put(keyValuePair[0], keyValuePair[1]);
277         }
278         return metaHash;
279     }
280 }