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