d58776198a6082cb2a5ea4dfbc09f57f44e42cd1
[dcaegen2/collectors/ves.git] / src / test / java / org / onap / dcae / ApplicationSettingsTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dcaegen2.collectors.ves
4  * ================================================================================
5  * Copyright (C) 2018 - 2021 Nokia. All rights reserved.
6  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.dcae;
23
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.networknt.schema.JsonSchema;
27 import io.vavr.collection.HashMap;
28 import io.vavr.collection.Map;
29 import org.junit.Ignore;
30 import org.junit.Test;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.util.Arrays;
38 import java.util.Objects;
39
40 import static java.util.Collections.singletonList;
41 import static org.junit.Assert.assertEquals;
42 import static org.junit.Assert.assertTrue;
43 import static org.junit.Assert.assertFalse;
44 import static org.junit.Assert.assertNull;
45 import static org.onap.dcae.CLIUtils.processCmdLine;
46 import static org.onap.dcae.TestingUtilities.createTemporaryFile;
47
48 public class ApplicationSettingsTest {
49
50     private static final String SAMPLE_JSON_SCHEMA = "{"
51             + "  \"type\": \"object\","
52             + "  \"properties\": {"
53             + "     \"state\": { \"type\": \"string\" }"
54             + "  }"
55             + "}";
56
57     @Test
58     public void shouldMakeApplicationSettingsOutOfCLIArguments() {
59         // given
60         String[] cliArguments = {"-param1", "param1value", "-param2", "param2value"};
61
62         // when
63         ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
64         String param1value = configurationAccessor.getStringDirectly("param1");
65         String param2value = configurationAccessor.getStringDirectly("param2");
66
67         // then
68         assertEquals("param1value", param1value);
69         assertEquals("param2value", param2value);
70     }
71
72     @Test
73     public void shouldMakeApplicationSettingsOutOfCLIArgumentsAndAConfigurationFile()
74             throws IOException {
75         // given
76         File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
77         Files.write(tempConfFile.toPath(), Arrays.asList("section.subSection1=abc", "section.subSection2=zxc"));
78         tempConfFile.deleteOnExit();
79         String[] cliArguments = {"-param1", "param1value", "-param2", "param2value", "-c", tempConfFile.toString()};
80
81         // when
82         ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
83         String param1value = configurationAccessor.getStringDirectly("param1");
84         String param2value = configurationAccessor.getStringDirectly("param2");
85         String fromFileParam1Value = configurationAccessor.getStringDirectly("section.subSection1");
86         String fromFileParam2Value = configurationAccessor.getStringDirectly("section.subSection2");
87
88         // then
89         assertEquals("param1value", param1value);
90         assertEquals("param2value", param2value);
91         assertEquals("abc", fromFileParam1Value);
92         assertEquals("zxc", fromFileParam2Value);
93     }
94
95     @Test
96     public void shouldCLIArgumentsOverrideConfigFileParameters() throws IOException {
97         // given
98         String[] cliArguments = {"-section.subSection1", "abc"};
99         File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
100         Files.write(tempConfFile.toPath(), singletonList("section.subSection1=zxc"));
101         tempConfFile.deleteOnExit();
102
103         // when
104         ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine);
105         String actuallyOverridenByCLIParam = configurationAccessor.getStringDirectly("section.subSection1");
106
107         // then
108         assertEquals("abc", actuallyOverridenByCLIParam);
109     }
110
111     @Test
112     public void shouldReturnHTTPPort() throws IOException {
113         // when
114         int applicationPort = fromTemporaryConfiguration("collector.service.port=8090")
115                 .httpPort();
116
117         // then
118         assertEquals(8090, applicationPort);
119     }
120
121     @Test
122     public void shouldReturnDefaultHTTPPort() throws IOException {
123         // when
124         int applicationPort = fromTemporaryConfiguration().httpPort();
125
126         // then
127         assertEquals(8080, applicationPort);
128     }
129
130     @Test
131     public void shouldReturnIfHTTPSIsEnabled() throws IOException {
132         // when
133         boolean httpsEnabled = fromTemporaryConfiguration("collector.service.secure.port=8443")
134                 .httpsEnabled();
135
136         // then
137         assertTrue(httpsEnabled);
138     }
139
140     @Test
141     public void shouldReturnIfHTTPIsEnabled() throws IOException {
142         // when
143         boolean httpsEnabled = fromTemporaryConfiguration("collector.service.port=8080").httpsEnabled();
144         // then
145         assertTrue(httpsEnabled);
146     }
147
148     @Test
149     public void shouldByDefaultHTTPSBeDisabled() throws IOException {
150         // when
151         boolean httpsEnabled = fromTemporaryConfiguration().httpsEnabled();
152
153         // then
154         assertTrue(httpsEnabled);
155     }
156
157     @Test
158     public void shouldReturnHTTPSPort() throws IOException {
159         // when
160         int httpsPort = fromTemporaryConfiguration("collector.service.secure.port=8443")
161                 .httpsPort();
162
163         // then
164         assertEquals(8443, httpsPort);
165     }
166
167     @Test
168     public void shouldReturnConfigurationUpdateInterval() throws IOException {
169         // when
170         int updateFrequency = fromTemporaryConfiguration("collector.dynamic.config.update.frequency=10")
171                 .configurationUpdateFrequency();
172
173         // then
174         assertEquals(10, updateFrequency);
175     }
176
177     @Test
178     public void shouldReturnDefaultConfigurationUpdateInterval() throws IOException {
179         // when
180         int updateFrequency = fromTemporaryConfiguration()
181                 .configurationUpdateFrequency();
182
183         // then
184         assertEquals(5, updateFrequency);
185     }
186
187     @Test
188     public void shouldReturnLocationOfThePasswordFile() throws IOException {
189         // when
190         String passwordFileLocation = fromTemporaryConfiguration("collector.keystore.passwordfile=/somewhere/password")
191                 .keystorePasswordFileLocation();
192
193         // then
194         assertEquals(sanitizePath("/somewhere/password"), passwordFileLocation);
195     }
196
197     @Test
198     public void shouldReturnDefaultLocationOfThePasswordFile() throws IOException {
199         // when
200         String passwordFileLocation = fromTemporaryConfiguration().keystorePasswordFileLocation();
201
202         // then
203         assertEquals(sanitizePath("etc/passwordfile"), passwordFileLocation);
204     }
205
206     @Test
207     public void shouldReturnLocationOfTheKeystoreFile() throws IOException {
208         // when
209         String keystoreFileLocation = fromTemporaryConfiguration("collector.keystore.file.location=/somewhere/keystore")
210                 .keystoreFileLocation();
211
212         // then
213         assertEquals(sanitizePath("/somewhere/keystore"), keystoreFileLocation);
214     }
215
216     @Test
217     public void shouldReturnLocationOfTheDefaultKeystoreFile() throws IOException {
218         // when
219         String keystoreFileLocation = fromTemporaryConfiguration().keystoreFileLocation();
220
221         // then
222         assertEquals(sanitizePath("etc/keystore"), keystoreFileLocation);
223     }
224
225     @Test
226     public void shouldReturnDMAAPConfigFileLocation() throws IOException {
227         // when
228         String dmaapConfigFileLocation = fromTemporaryConfiguration("collector.dmaapfile=/somewhere/dmaapFile")
229                 .dMaaPConfigurationFileLocation();
230
231         // then
232         assertEquals(sanitizePath("/somewhere/dmaapFile"), dmaapConfigFileLocation);
233     }
234
235     @Test
236     public void shouldTellIfSchemaValidationIsEnabled() throws IOException {
237         // when
238         boolean jsonSchemaValidationEnabled = fromTemporaryConfiguration("collector.schema.checkflag=1")
239                 .eventSchemaValidationEnabled();
240
241         // then
242         assertTrue(jsonSchemaValidationEnabled);
243     }
244
245     @Test
246     public void shouldByDefaultSchemaValidationBeDisabled() throws IOException {
247         // when
248         boolean jsonSchemaValidationEnabled = fromTemporaryConfiguration().eventSchemaValidationEnabled();
249
250         // then
251         assertFalse(jsonSchemaValidationEnabled);
252     }
253
254     @Test
255     public void shouldReportValidateJSONSchemaErrorWhenJsonContainsIntegerValueNotString() throws IOException {
256         // when
257         Path temporarySchemaFile = createTemporaryFile(SAMPLE_JSON_SCHEMA);
258
259         // when
260         JsonSchema schema = fromTemporaryConfiguration(
261                 String.format("collector.schema.file={\"v1\": \"%s\"}", temporarySchemaFile))
262                 .jsonSchema("v1");
263
264         // then
265         JsonNode incorrectTestObject = new ObjectMapper().readTree("{ \"state\": 1 }");
266
267         assertFalse(schema.validate(incorrectTestObject).isEmpty());
268
269     }
270
271     @Test
272     public void shouldDoNotReportAnyValidateJSONSchemaError() throws IOException {
273         // when
274         Path temporarySchemaFile = createTemporaryFile(SAMPLE_JSON_SCHEMA);
275
276         // when
277         JsonSchema schema = fromTemporaryConfiguration(
278                 String.format("collector.schema.file={\"v1\": \"%s\"}", temporarySchemaFile))
279                 .jsonSchema("v1");
280
281         // then
282         JsonNode correctTestObject = new ObjectMapper().readTree("{ \"state\": \"hi\" }");
283         assertTrue(schema.validate(correctTestObject).isEmpty());
284     }
285
286     @Test
287     public void shouldReturnExceptionConfigFileLocation() throws IOException {
288         // when
289         String exceptionConfigFileLocation = fromTemporaryConfiguration("exceptionConfig=/somewhere/exceptionFile")
290                 .exceptionConfigFileLocation();
291
292         // then
293         assertEquals("/somewhere/exceptionFile", exceptionConfigFileLocation);
294     }
295
296     @Test
297     public void shouldReturnDefaultExceptionConfigFileLocation() throws IOException {
298         // when
299         String exceptionConfigFileLocation = fromTemporaryConfiguration().exceptionConfigFileLocation();
300
301         // then
302         assertNull(exceptionConfigFileLocation);
303     }
304
305
306     @Test
307     public void shouldReturnDMAAPStreamId() throws IOException {
308         // given
309         Map<String, String> expected = HashMap.of(
310                 "log", "ves-syslog",
311                 "fault", "ves-fault"
312         );
313
314         // when
315         Map<String, String> dmaapStreamID = fromTemporaryConfiguration(
316                 "collector.dmaap.streamid=fault=ves-fault,stream1|log=ves-syslog,stream2,stream3")
317                 .getDmaapStreamIds();
318
319         // then
320         assertEquals(expected.get("log").get(), Objects.requireNonNull(dmaapStreamID).get("log").get());
321         assertEquals(expected.get("fault").get(), Objects.requireNonNull(dmaapStreamID).get("fault").get());
322         assertEquals(expected.keySet(), dmaapStreamID.keySet());
323     }
324
325     @Test
326     public void shouldReturnDefaultDMAAPStreamId() throws IOException {
327         // when
328         Map<String, String> dmaapStreamID = fromTemporaryConfiguration().getDmaapStreamIds();
329
330         // then
331         assertEquals(dmaapStreamID, HashMap.empty());
332     }
333
334     @Test
335     public void shouldAuthorizationBeDisabledByDefault() throws IOException {
336         // when
337         boolean authorizationEnabled = fromTemporaryConfiguration().authMethod().contains("noAuth");
338
339         // then
340         assertTrue(authorizationEnabled);
341     }
342
343     @Test
344     public void shouldReturnValidCredentials() throws IOException {
345         // when
346         Map<String, String> allowedUsers = fromTemporaryConfiguration(
347                 "header.authlist=pasza,c2ltcGxlcGFzc3dvcmQNCg==|someoneelse,c2ltcGxlcGFzc3dvcmQNCg=="
348         ).validAuthorizationCredentials();
349
350         // then
351         assertEquals("c2ltcGxlcGFzc3dvcmQNCg==", allowedUsers.get("pasza").get());
352         assertEquals("c2ltcGxlcGFzc3dvcmQNCg==", allowedUsers.get("someoneelse").get());
353     }
354
355     @Test
356     public void shouldbyDefaultThereShouldBeNoValidCredentials() throws IOException {
357         // when
358         Map<String, String> userToBase64PasswordDelimitedByCommaSeparatedByPipes = fromTemporaryConfiguration().
359                 validAuthorizationCredentials();
360
361         // then
362         assertTrue(userToBase64PasswordDelimitedByCommaSeparatedByPipes.isEmpty());
363     }
364
365     @Test
366     public void shouldReturnIfEventTransformingIsEnabled() throws IOException {
367         // when
368         boolean isEventTransformingEnabled = fromTemporaryConfiguration("event.transform.flag=0")
369                 .eventTransformingEnabled();
370
371         // then
372         assertFalse(isEventTransformingEnabled);
373     }
374
375     @Test
376     public void shouldEventTransformingBeEnabledByDefault() throws IOException {
377         // when
378         boolean isEventTransformingEnabled = fromTemporaryConfiguration().eventTransformingEnabled();
379
380         // then
381         assertTrue(isEventTransformingEnabled);
382     }
383
384     @Test
385     public void shouldReturnConfigurationFileLocation() throws IOException {
386         // when
387         String configurationFileLocation = fromTemporaryConfiguration(
388                 "collector.dmaapfile=/somewhere/etc/ves-dmaap-config.json")
389                 .dMaaPConfigurationFileLocation();
390
391         // then
392         assertEquals(sanitizePath("/somewhere/etc/ves-dmaap-config.json"), configurationFileLocation);
393     }
394
395     @Test
396     public void shouldReturnDefaultConfigurationFileLocation() throws IOException {
397         // when
398         String configurationFileLocation = fromTemporaryConfiguration()
399                 .dMaaPConfigurationFileLocation();
400
401         // then
402         assertEquals(sanitizePath("etc/ves-dmaap-config.json"), configurationFileLocation);
403     }
404
405     @Test
406     public void shouldReturnDefaultExternalSchemaSchemasLocation() throws IOException {
407         //when
408         String externalSchemaSchemasLocation = fromTemporaryConfiguration()
409                 .getExternalSchemaSchemasLocation();
410
411         //then
412         assertEquals(sanitizePath("./etc/externalRepo"), externalSchemaSchemasLocation);
413     }
414
415     @Test
416     public void shouldReturnDefaultExternalSchemaMappingFileLocation() throws IOException {
417         //when
418         String externalSchemaMappingFileLocation = fromTemporaryConfiguration()
419                 .getExternalSchemaMappingFileLocation();
420
421         //then
422         assertEquals(sanitizePath("./etc/externalRepo/schema-map.json"), externalSchemaMappingFileLocation);
423     }
424
425     @Test
426     public void shouldReturnDefaultExternalSchemaSchemaRefPath() throws IOException {
427         //when
428         String externalSchemaSchemaRefPath = fromTemporaryConfiguration()
429                 .getExternalSchemaSchemaRefPath();
430
431         //then
432         assertEquals(sanitizePath("/event/stndDefinedFields/schemaReference"), externalSchemaSchemaRefPath);
433     }
434
435     @Test
436     public void shouldReturnDefaultExternalSchemaStndDefinedDataPath() throws IOException {
437         //when
438         String externalSchemaStndDefinedDataPath = fromTemporaryConfiguration()
439                 .getExternalSchemaStndDefinedDataPath();
440
441         //then
442         assertEquals(sanitizePath("/event/stndDefinedFields/data"), externalSchemaStndDefinedDataPath);
443     }
444
445     @Test
446     public void shouldReturnEnabledExternalSchema2ndStageValidation() throws IOException {
447         //when
448         boolean externalSchema2ndStageValidation = fromTemporaryConfiguration("collector.externalSchema.2ndStageValidation=-1")
449                 .getExternalSchemaValidationCheckflag();
450
451         //then
452         assertFalse(externalSchema2ndStageValidation);
453     }
454
455     private static ApplicationSettings fromTemporaryConfiguration(String... fileLines)
456             throws IOException {
457         File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter");
458         Files.write(tempConfFile.toPath(), Arrays.asList(fileLines));
459         tempConfFile.deleteOnExit();
460         return new ApplicationSettings(new String[]{"-c", tempConfFile.toString()}, args -> processCmdLine(args), "");
461     }
462
463     private String sanitizePath(String path) {
464         return Paths.get(path).toString();
465     }
466 }