diff options
Diffstat (limited to 'src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator')
27 files changed, 2792 insertions, 0 deletions
diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/DbTemplateReaderTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/DbTemplateReaderTest.java new file mode 100644 index 0000000..cc03d8a --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/DbTemplateReaderTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.assertj.core.api.Assertions; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.integration.simulators.nfsimulator.vesclient.template.Template; +import org.onap.integration.simulators.nfsimulator.vesclient.template.TemplateService; + +import java.io.IOException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DbTemplateReaderTest { + + public static final String SOME_TEMPLATE = "someTemplate"; + public static final String KEY = "key"; + public static final String VALUE = "value"; + public static final long LMOD = 10L; + private TemplateService service; + private DbTemplateReader dbTemplateReader; + + @BeforeEach + void setUp() { + this.service = mock(TemplateService.class); + this.dbTemplateReader = new DbTemplateReader(this.service, new Gson()); + } + + @Test + public void shouldReportErrorWhenTemplateDoesNotExistInTemplateService() { + // given + when(this.service.get(SOME_TEMPLATE)).thenReturn(Optional.empty()); + + // when/then + assertThrows(IOException.class, + () -> this.dbTemplateReader.readTemplate(SOME_TEMPLATE) + ); + } + + @Test + public void shouldReturnTemplateFromService() throws IOException { + // given + Template template = givenTemplate(SOME_TEMPLATE); + when(this.service.get(SOME_TEMPLATE)).thenReturn(Optional.of(template)); + + // when + final JsonObject someTemplate = this.dbTemplateReader.readTemplate(SOME_TEMPLATE); + + // then + Assertions.assertThat(someTemplate).isNotNull(); + Assertions.assertThat(someTemplate.get(KEY).getAsString()).isEqualTo(VALUE); + } + + private Template givenTemplate(String templateName) { + return new Template(templateName, new Document(KEY, VALUE), LMOD); + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/IncrementProviderImplTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/IncrementProviderImplTest.java new file mode 100644 index 0000000..d57b653 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/IncrementProviderImplTest.java @@ -0,0 +1,79 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.onap.integration.simulators.nfsimulator.vesclient.event.EventData; +import org.onap.integration.simulators.nfsimulator.vesclient.event.EventDataRepository; + +public class IncrementProviderImplTest { + private IncrementProvider incrementProvider; + + @Mock + private EventDataRepository eventDataRepositoryMock; + + @BeforeEach + void setUp() { + eventDataRepositoryMock = mock(EventDataRepository.class); + incrementProvider = new IncrementProviderImpl(eventDataRepositoryMock); + } + + @Test + public void getAndIncrementTest() { + ArgumentCaptor<EventData> eventDataArgumentCaptor = ArgumentCaptor.forClass(EventData.class); + String eventId = "1"; + int initialIncrementValue = 0; + int expectedValue = initialIncrementValue + 1; + EventData eventData = EventData.builder().id(eventId).incrementValue(initialIncrementValue).build(); + Optional<EventData> optional = Optional.of(eventData); + + when(eventDataRepositoryMock.findById(eventId)).thenReturn(optional); + + int value = incrementProvider.getAndIncrement(eventId); + + verify(eventDataRepositoryMock).save(eventDataArgumentCaptor.capture()); + + assertThat(value).isEqualTo(expectedValue); + assertThat(eventDataArgumentCaptor.getValue().getIncrementValue()).isEqualTo(expectedValue); + + } + + @Test + public void shouldThrowOnNonExistingEvent() { + Optional<EventData> emptyOptional = Optional.empty(); + String nonExistingEventId = "THIS_DOES_NOT_EXIST"; + when(eventDataRepositoryMock.findById(nonExistingEventId)).thenReturn(emptyOptional); + + assertThrows(EventNotFoundException.class, + () -> incrementProvider.getAndIncrement(nonExistingEventId)); + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidRandomIntegerTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidRandomIntegerTest.java new file mode 100644 index 0000000..e6a1213 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidRandomIntegerTest.java @@ -0,0 +1,67 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorInvalidRandomIntegerTest { + + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection INVALID_INTEGER_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandoInteger"}, + {"#Randominteger(23,11)"}, + {"#randomInteger(11,34)"}, + {"#Random_Integer(11,13)"}, + {"#RandomInteger(11)"}, + {"RandomInteger(11)"}, + {"RandomInteger"} + }); + + public KeywordsExtractorInvalidRandomIntegerTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return INVALID_INTEGER_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1), this.keyword); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidRandomStringTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidRandomStringTest.java new file mode 100644 index 0000000..fad4ff9 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidRandomStringTest.java @@ -0,0 +1,67 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorInvalidRandomStringTest { + + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection INVALID_STRING_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandoString"}, + {"#Randomstring(23)"}, + {"#randomString(11)"}, + {"#Random_String(11)"}, + {"#RandomString(11,10)"}, + {"RandomString(11)"}, + {"RandomString"} + }); + + public KeywordsExtractorInvalidRandomStringTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return INVALID_STRING_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1).length(), this.keyword.length()); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidTimestampTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidTimestampTest.java new file mode 100644 index 0000000..54a72a9 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorInvalidTimestampTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorInvalidTimestampTest { + + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection INVALID_TIMESTAMP_KEYWORDS = Arrays.asList(new Object[][]{ + {"#Timesamp"}, + {"#Timestamp(10)"}, + {"#timestamp"}, + {"#Timestamp(11,13)"}, + {"Timestamp"} + }); + + public KeywordsExtractorInvalidTimestampTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return INVALID_TIMESTAMP_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1), this.keyword); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomIntegerTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomIntegerTest.java new file mode 100644 index 0000000..5befed8 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomIntegerTest.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidRandomIntegerTest { + + private final String keyword; + private final String shouldParseTo; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_INTEGER_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandomInteger(23,23)", "23"}, + {"#RandomInteger(6, 6)12", "612"}, + {"1#RandomInteger(11,11)", "111"}, + {"1#RandomInteger(11,11)2", "1112"} + }); + + public KeywordsExtractorValidRandomIntegerTest(String keyword, String shouldParseTo) { + this.keyword = keyword; + this.shouldParseTo = shouldParseTo; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_INTEGER_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1), this.shouldParseTo); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java new file mode 100644 index 0000000..4747e4e --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidRandomPrimitiveIntegerTest { + + private final String keyword; + private final Integer shouldParseTo; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_INTEGER_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandomPrimitiveInteger(23,23)", 23}, + {"#RandomPrimitiveInteger(6, 6)12", 6}, + {"1#RandomPrimitiveInteger(11,11)", 11}, + {"1#RandomPrimitiveInteger(11,11)2", 11} + }); + + public KeywordsExtractorValidRandomPrimitiveIntegerTest(String keyword, Integer shouldParseTo) { + this.keyword = keyword; + this.shouldParseTo = shouldParseTo; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_INTEGER_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substitutePrimitiveKeyword(this.keyword), Long.valueOf(this.shouldParseTo)); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomStringTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomStringTest.java new file mode 100644 index 0000000..69d603c --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidRandomStringTest.java @@ -0,0 +1,68 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidRandomStringTest { + + private final String keyword; + private final int length; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_STRING_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandomString", KeywordsValueProvider.DEFAULT_STRING_LENGTH}, + {"1#RandomString2", 1 + KeywordsValueProvider.DEFAULT_STRING_LENGTH + 1}, + {"#RandomString(23)", 23}, + {"#RandomString(11)12", 11 + 2}, + {"1#RandomString(11)", 1 + 11}, + {"1#RandomString(11)2", 1 + 11 + 1} + }); + + public KeywordsExtractorValidRandomStringTest(String keyword, int length) { + this.keyword = keyword; + this.length = length; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_STRING_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1).length(), this.length); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java new file mode 100644 index 0000000..af5fd8e --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2019 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidTimestampPrimitiveTest { + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_TIMESTAMP_KEYWORDS = Arrays.asList(new Object[][]{ + {"#TimestampPrimitive"} + }); + + public KeywordsExtractorValidTimestampPrimitiveTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_TIMESTAMP_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + long currentTimestamp = Instant.now().getEpochSecond(); + Long timestamp = keywordsExtractor.substitutePrimitiveKeyword(this.keyword); + long afterExecution = Instant.now().getEpochSecond(); + + assertThat(timestamp).isBetween(currentTimestamp, afterExecution); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidTimestampTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidTimestampTest.java new file mode 100644 index 0000000..11c709b --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsExtractorValidTimestampTest.java @@ -0,0 +1,68 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidTimestampTest { + + private final String keyword; + private final int length; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_TIMESTAMP_KEYWORDS = Arrays.asList(new Object[][]{ + {"#Timestamp", 10}, + {"#Timestamp12", 10 + 2}, + {"1#Timestamp", 1 + 10}, + {"1#Timestamp2", 1 + 10 + 1} + }); + + public KeywordsExtractorValidTimestampTest(String keyword, Integer length) { + this.keyword = keyword; + this.length = length; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_TIMESTAMP_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + String substitution = keywordsExtractor.substituteStringKeyword(this.keyword, 1); + assertEquals(substitution.length(), this.length); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsHandlerTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsHandlerTest.java new file mode 100644 index 0000000..09bb46f --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsHandlerTest.java @@ -0,0 +1,305 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; + +import org.junit.jupiter.api.Test; + +class KeywordsHandlerTest { + + private static final String TEMPLATE_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_JSON_WITH_MANY_KEYWORDS_INSIDE_SINGLE_VALUE = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain1\": \"#RandomString(1) #RandomString(2) #RandomString(3)\",\n" + + " \"domain2\": \"1 #RandomString(1) 2\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_JSON_WITH_ARRAY = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString(1)\",\n" + + " \"version\": 2.0\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"additionalMeasurements\": [\n" + + " {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"arrayOfFields\": [\n" + + " {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " },\n" + + " {\n" + + " \"name\": [\"1\",\"2\"],\n" + + " \"value\": \"#RandomString(2)\"\n" + + " },\n" + + " {\n" + + " \"name\": \"G722AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_ONE_INCREMENT_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"#Increment\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_WITH_SIMPLE_VALUE = "\"#RandomString(4)\""; + + private static final String TEMPLATE_WITH_ARRAY_OF_PRIMITIVES = "[ 1, \"#RandomString(5)\", 3]"; + + private static final String TEMPLATE_TWO_INCREMENT_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"#Increment\",\n" + + " \"otherValue\": \"#Increment\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private Gson gson = new Gson(); + + @Test + void shouldReplaceRandomStringKeyword() { + // given + JsonObject templateJson = gson.fromJson(TEMPLATE_JSON, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "").getAsJsonObject(); + + // then + String extraFields = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("name").getAsString(); + String newDomain = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); + + assertThat(extraFields.length()).isEqualTo(4); + assertThat(newDomain.length()).isEqualTo(KeywordsValueProvider.DEFAULT_STRING_LENGTH); + } + + @Test + void shouldReplaceRandomStringKeywordsInsideSingleValue() { + // given + JsonObject templateJson = gson.fromJson(TEMPLATE_JSON_WITH_MANY_KEYWORDS_INSIDE_SINGLE_VALUE, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "").getAsJsonObject(); + + // then + String newDomain1 = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain1").getAsString(); + String newDomain2 = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain2").getAsString(); + + assertThat(newDomain1.length()).isEqualTo(1 + 1 + 2 + 1 + 3); + assertThat(newDomain2.length()).isEqualTo(1 + 1 + 1 + 1 + 1); + } + + @Test + void shouldReplaceRandomStringKeywordInTeplateAsArrayWithPrimitves() { + // given + JsonElement templateJson = gson.fromJson(TEMPLATE_WITH_ARRAY_OF_PRIMITIVES, JsonElement.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonElement resultJson = keywordsHandler.substituteKeywords(templateJson, ""); + assertThat(resultJson.getAsJsonArray().get(1).getAsString().length()).isEqualTo(5); + } + + @Test + void shouldReplaceRandomStringKeywordInTeplateAsSimpleValue() { + // given + JsonElement templateJson = gson.fromJson(TEMPLATE_WITH_SIMPLE_VALUE, JsonElement.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonElement resultJson = keywordsHandler.substituteKeywords(templateJson, ""); + + // then + assertThat(resultJson.getAsString().length()).isEqualTo(4); + } + + @Test + void shouldReplaceRandomStringKeywordInTeplateWithJsonArray() { + // given + JsonElement templateJson = gson.fromJson(TEMPLATE_JSON_WITH_ARRAY, JsonElement.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "").getAsJsonObject(); + + // then + String actualValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonArray() + .get(0).getAsJsonObject() + .get("arrayOfFields").getAsJsonArray() + .get(1).getAsJsonObject() + .get("value").getAsString(); + String otherActualValue = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); + + assertThat(otherActualValue.length()).isEqualTo(1); + assertThat(actualValue.length()).isEqualTo(2); + } + + @Test + void shouldReplaceOneIncrementKeyword() { + // given + final Integer newIncrementedValue = 2; + JsonObject templateJson = gson.fromJson(TEMPLATE_ONE_INCREMENT_JSON, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> newIncrementedValue); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "some random id").getAsJsonObject(); + + // then + String actualValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("value").getAsString(); + + assertThat(actualValue).isEqualTo(newIncrementedValue.toString()); + } + + @Test + void shouldReplaceTwoIncrementKeyword() { + // given + final Integer firstIncrementValue = 2; + final Integer secondIncrementValue = 3; + JsonObject templateJson = gson.fromJson(TEMPLATE_TWO_INCREMENT_JSON, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), new IncrementProvider() { + Queue<Integer> sequenceOfValues = new LinkedList<>( + Arrays.asList(firstIncrementValue, secondIncrementValue)); + + @Override + public int getAndIncrement(String id) { + return sequenceOfValues.poll(); + } + }); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "some random id").getAsJsonObject(); + resultJson = keywordsHandler.substituteKeywords(templateJson, "some random id").getAsJsonObject(); + + // then + String actualValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("value").getAsString(); + + String actualOtherValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("otherValue").getAsString(); + + assertThat(actualValue).isEqualTo(secondIncrementValue.toString()); + assertThat(actualOtherValue).isEqualTo(secondIncrementValue.toString()); + + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsValueProviderTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsValueProviderTest.java new file mode 100644 index 0000000..43d6b73 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/KeywordsValueProviderTest.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Random; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; + +class KeywordsValueProviderTest { + + @RepeatedTest(10) + void randomLimitedStringTest() { + String supplierResult = KeywordsValueProvider.getRandomLimitedString().apply(); + Assertions.assertEquals(KeywordsValueProvider.DEFAULT_STRING_LENGTH, supplierResult.length()); + } + + @RepeatedTest(10) + void randomStringTest() { + int length = new Random().nextInt(15) + 1; + String supplierResult = KeywordsValueProvider.getRandomString().apply(length); + assertEquals(length, supplierResult.length()); + } + + @RepeatedTest(10) + void randomIntegerTest() { + int min = new Random().nextInt(10) + 1; + int max = new Random().nextInt(1000) + 20; + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(min, max); + assertTrue(Integer.parseInt(supplierResult) >= min); + assertTrue(Integer.parseInt(supplierResult) <= max); + } + + @Test + void randomIntegerContainsMaximalAndMinimalValuesTest() { + int anyNumber = new Random().nextInt(10) + 1; + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(anyNumber, anyNumber); + assertEquals(Integer.parseInt(supplierResult), anyNumber); + } + + @Test + void randomIntegerFromNegativeRangeTest() { + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(-20, -20); + assertEquals(Integer.parseInt(supplierResult), -20); + } + + @RepeatedTest(10) + void randomIntegerFromParametersWithDifferentOrdersTest() { + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(-20, -10); + assertTrue(Integer.parseInt(supplierResult) >= -20); + assertTrue(Integer.parseInt(supplierResult) <= -10); + } + + @RepeatedTest(10) + void epochSecondGeneratedInCorrectFormatTest() { + String supplierResult = KeywordsValueProvider.getEpochSecond().apply(); + assertEquals(10, supplierResult.length()); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/SimulatorServiceTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/SimulatorServiceTest.java new file mode 100644 index 0000000..4580714 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/SimulatorServiceTest.java @@ -0,0 +1,309 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import org.apache.http.HttpStatus; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.onap.integration.simulators.nfsimulator.vesclient.rest.model.FullEvent; +import org.onap.integration.simulators.nfsimulator.vesclient.rest.model.SimulatorParams; +import org.onap.integration.simulators.nfsimulator.vesclient.rest.model.SimulatorRequest; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpClientAdapter; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpResponseAdapter; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl.SslAuthenticationHelper; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.scheduler.EventScheduler; +import org.onap.integration.simulators.nfsimulator.vesclient.simulatorconfig.SimulatorConfig; +import org.onap.integration.simulators.nfsimulator.vesclient.simulatorconfig.SimulatorConfigService; +import org.onap.integration.simulators.nfsimulator.vesclient.event.EventData; +import org.onap.integration.simulators.nfsimulator.vesclient.event.EventDataService; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpTestUtils; +import org.quartz.SchedulerException; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.GeneralSecurityException; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +class SimulatorServiceTest { + + private static final String VES_URL = "http://0.0.0.0:8080"; + private static final String IN_DB_VES_URL = "http://0.0.0.0:8080/eventListener/v6"; + private static final Gson GSON = new Gson(); + private static final JsonObject VALID_PATCH = GSON.fromJson("{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"sourceName\": \"SomeCustomSource\"}}}\n", JsonObject.class); + private static final JsonObject VALID_FULL_EVENT = GSON.fromJson("{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\"}}]}}}", JsonObject.class); + private static final JsonObject FULL_EVENT_WITH_KEYWORDS = GSON.fromJson("{\"event\":{ \n" + + " \"commonEventHeader\":{ \n" + + " \"domain\":\"notification\",\n" + + " \"eventName\":\"#RandomString(20)\",\n" + + " \"eventOrderNo\":\"#Increment\"}}}", JsonObject.class); + private static final JsonObject VALID_VARIABLES = GSON.fromJson("{\"dn\": \"TestDN-1\", \"measurement\":{\n" + + " \"name\": \"AdditionalM\",\n" + + " \"value\": \"1.5\"\n" + + " }}", JsonObject.class); + private static final String SOME_CUSTOM_SOURCE = "SomeCustomSource"; + private static final String CLOSED_LOOP_VNF = "ClosedLoopVNF"; + private static final String SAMPLE_ID = "sampleId"; + private static final EventData SAMPLE_EVENT = EventData.builder().id("1").build(); + private static URL inDbVesUrl; + private final ArgumentCaptor<JsonObject> bodyCaptor = ArgumentCaptor.forClass(JsonObject.class); + private final ArgumentCaptor<Integer> intervalCaptor = ArgumentCaptor.forClass(Integer.class); + private final ArgumentCaptor<Integer> repeatCountCaptor = ArgumentCaptor + .forClass(Integer.class); + private final ArgumentCaptor<String> templateNameCaptor = ArgumentCaptor.forClass(String.class); + private final ArgumentCaptor<String> eventIdCaptor = ArgumentCaptor.forClass(String.class); + private final ArgumentCaptor<String> vesUrlCaptor = ArgumentCaptor.forClass(String.class); + private final ArgumentCaptor<String> eventContentCaptor = ArgumentCaptor.forClass(String.class); + private final SslAuthenticationHelper sslAuthenticationHelper = new SslAuthenticationHelper(); + private final TemplatePatcher templatePatcher = new TemplatePatcher(); + private final TemplateReader templateReader = new FilesystemTemplateReader( + "src/test/resources/org/onap/integration/simulators/nfsimulator/vesclient/simulator/", GSON); + + private SimulatorService simulatorService; + private EventDataService eventDataService; + private EventScheduler eventScheduler; + private SimulatorConfigService simulatorConfigService; + + @BeforeEach + void setUp() throws MalformedURLException { + inDbVesUrl = new URL(IN_DB_VES_URL); + eventDataService = mock(EventDataService.class); + eventScheduler = mock(EventScheduler.class); + simulatorConfigService = mock(SimulatorConfigService.class); + + simulatorService = new SimulatorService(templatePatcher, templateReader, + eventScheduler, eventDataService, simulatorConfigService, + new TemplateVariablesReplacer(),new SslAuthenticationHelper()); + } + + @Test + void shouldTriggerEventWithGivenParams() throws IOException, SchedulerException, GeneralSecurityException { + String templateName = "validExampleMeasurementEvent.json"; + SimulatorParams simulatorParams = new SimulatorParams(VES_URL, 1, 1); + SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, + templateName, VALID_PATCH, VALID_VARIABLES); + + doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + + simulatorService.triggerEvent(simulatorRequest); + + assertEventHasExpectedStructure(VES_URL, templateName, SOME_CUSTOM_SOURCE); + assertEventHasReplacedVariables(); + } + + @Test + void shouldTriggerEventWithDefaultVesUrlWhenNotProvidedInRequest() throws IOException, SchedulerException, GeneralSecurityException { + String templateName = "validExampleMeasurementEvent.json"; + SimulatorRequest simulatorRequest = new SimulatorRequest( + new SimulatorParams("", 1, 1), + templateName, VALID_PATCH, new JsonObject()); + + doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + when(simulatorConfigService.getConfiguration()).thenReturn(new SimulatorConfig(SAMPLE_ID, inDbVesUrl)); + + simulatorService.triggerEvent(simulatorRequest); + + assertEventHasExpectedStructure(inDbVesUrl.toString(), templateName, SOME_CUSTOM_SOURCE); + } + + @Test + void shouldThrowJsonSyntaxWhenInvalidJson() { + //given + JsonObject patch = GSON.fromJson("{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"sourceName\": \"" + + SOME_CUSTOM_SOURCE + "\"\n" + + " }\n" + + " }\n" + + "}\n", JsonObject.class); + EventData eventData = EventData.builder().id("1").build(); + + SimulatorParams simulatorParams = new SimulatorParams(VES_URL, 1, 1); + SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, + "invalidJsonStructureEvent.json", patch, new JsonObject()); + doReturn(eventData).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + + //when + assertThrows(JsonSyntaxException.class, + () -> simulatorService.triggerEvent(simulatorRequest)); + } + + @Test + void shouldHandleNonExistingPatchSection() throws IOException, SchedulerException, GeneralSecurityException { + String templateName = "validExampleMeasurementEvent.json"; + SimulatorRequest simulatorRequest = new SimulatorRequest( + new SimulatorParams("", 1, 1), + templateName, null, new JsonObject()); + + doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + doReturn(new SimulatorConfig(SAMPLE_ID, inDbVesUrl)).when(simulatorConfigService).getConfiguration(); + + simulatorService.triggerEvent(simulatorRequest); + + assertEventHasExpectedStructure(inDbVesUrl.toString(), templateName, CLOSED_LOOP_VNF); + } + + @Test + void shouldSuccessfullySendOneTimeEventWithVesUrlWhenPassed() throws IOException, GeneralSecurityException { + SimulatorService spiedTestedService = spy(new SimulatorService( + templatePatcher, templateReader, eventScheduler, + eventDataService, simulatorConfigService, + new TemplateVariablesReplacer(), + new SslAuthenticationHelper())); + + HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); + prepareMocksWithAcceptedResponse(spiedTestedService, adapterMock); + FullEvent event = new FullEvent(VES_URL, VALID_FULL_EVENT); + + spiedTestedService.triggerOneTimeEvent(event); + + assertThat(eventContentCaptor.getValue()).isEqualTo(VALID_FULL_EVENT.toString()); + verify(eventDataService, times(1)).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + verify(adapterMock, times(1)).send(VALID_FULL_EVENT.toString()); + } + + @Test + void shouldSubstituteKeywordsAndSuccessfullySendOneTimeEvent() throws IOException, GeneralSecurityException { + SimulatorService spiedTestedService = spy(new SimulatorService( + templatePatcher, templateReader, eventScheduler, + eventDataService, simulatorConfigService, + new TemplateVariablesReplacer(), + new SslAuthenticationHelper()) + ); + + HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); + prepareMocksWithAcceptedResponse(spiedTestedService, adapterMock); + FullEvent event = new FullEvent(VES_URL, FULL_EVENT_WITH_KEYWORDS); + + spiedTestedService.triggerOneTimeEvent(event); + + JsonObject sentContent = GSON.fromJson(eventContentCaptor.getValue(), JsonElement.class).getAsJsonObject(); + assertThat(sentContent.getAsJsonObject("event").getAsJsonObject("commonEventHeader").get("eventOrderNo").getAsString()).isEqualTo("1"); + assertThat(sentContent.getAsJsonObject("event").getAsJsonObject("commonEventHeader").get("eventName").getAsString()).hasSize(20); + } + + @Test + void shouldGetSimulatorConfiguration() { + SimulatorConfig simulatorConfig = getSimulatorConfig(); + + when(simulatorConfigService.getConfiguration()).thenReturn(simulatorConfig); + + Assertions.assertEquals(simulatorService.getConfiguration(), simulatorConfig); + } + + @Test + void shouldUpdateSimulatorConfiguration() { + SimulatorConfig simulatorConfig = getSimulatorConfig(); + + when(simulatorConfigService.updateConfiguration(simulatorConfig)).thenReturn(simulatorConfig); + + Assertions.assertEquals(simulatorService.updateConfiguration(simulatorConfig), simulatorConfig); + } + + @Test + void shouldCancelAllEvents() throws SchedulerException { + when(eventScheduler.cancelAllEvents()).thenReturn(true); + + assertTrue(simulatorService.cancelAllEvents()); + } + + @Test + void shouldCancelSingleEvent() throws SchedulerException { + final String jobName = "testJobName"; + when(eventScheduler.cancelEvent(jobName)).thenReturn(true); + + assertTrue(simulatorService.cancelEvent(jobName)); + } + + private void prepareMocksWithAcceptedResponse(SimulatorService spiedTestedService, HttpClientAdapter adapterMock) throws IOException, GeneralSecurityException { + HttpResponseAdapter response = new HttpResponseAdapter(HttpStatus.SC_ACCEPTED, HttpTestUtils.HTTP_MESSAGE_ACCEPTER); + doReturn(response).when(adapterMock).send(eventContentCaptor.capture()); + doReturn(adapterMock).when(spiedTestedService).createHttpClientAdapter(any(String.class)); + } + + private void assertEventHasExpectedStructure(String expectedVesUrl, String templateName, String sourceNameString) throws SchedulerException, IOException, GeneralSecurityException { + verify(eventScheduler, times(1)).scheduleEvent(vesUrlCaptor.capture(), intervalCaptor.capture(), + repeatCountCaptor.capture(), templateNameCaptor.capture(), eventIdCaptor.capture(), bodyCaptor.capture()); + assertThat(vesUrlCaptor.getValue()).isEqualTo(expectedVesUrl); + assertThat(intervalCaptor.getValue()).isEqualTo(1); + assertThat(repeatCountCaptor.getValue()).isEqualTo(1); + assertThat(templateNameCaptor.getValue()).isEqualTo(templateName); + String actualSourceName = GSON.fromJson(bodyCaptor.getValue(), JsonObject.class) + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("sourceName").getAsString(); + assertThat(actualSourceName).isEqualTo(sourceNameString); + verify(eventDataService) + .persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), + any(JsonObject.class)); + } + + private SimulatorConfig getSimulatorConfig() { + return new SimulatorConfig(SAMPLE_ID, inDbVesUrl); + } + + private void assertEventHasReplacedVariables() { + String measurementName = GSON.fromJson(bodyCaptor.getValue(), JsonObject.class) + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonArray().get(0).getAsJsonObject() + .get("arrayOfFields").getAsJsonArray().get(0).getAsJsonObject() + .get("name").getAsString(); + + String reportingEntityName = GSON.fromJson(bodyCaptor.getValue(), JsonObject.class) + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("reportingEntityName").getAsString(); + + assertThat(measurementName).isEqualTo("AdditionalM"); + assertThat(reportingEntityName).isEqualTo("TestDN-1"); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplatePatcherTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplatePatcherTest.java new file mode 100644 index 0000000..13179aa --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplatePatcherTest.java @@ -0,0 +1,164 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.assertj.core.api.AssertionsForInterfaceTypes; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +class TemplatePatcherTest { + + private static final String TEMPLATE_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"measurementsForVfScaling\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private TemplatePatcher templatePatcher; + private Gson gson = new Gson(); + private JsonObject templateJson; + + @BeforeEach + void setUp() { + templatePatcher = new TemplatePatcher(); + templateJson = gson.fromJson(TEMPLATE_JSON, JsonObject.class); + } + + @Test + void shouldReplaceJsonElementsInTemplate() { + //given + String patchJsonString = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"newDomain\"\n" + + " }\n" + + " }\n" + + "}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + String newDomain = requestJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); + assertThat(newDomain).isEqualTo("newDomain"); + } + + @Test + void shouldAddWholeJsonObjectToTemplateWhenItFinished() { + //given + String patchJsonString = + "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": {\n" + + " \"extraFields\": {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + JsonElement newDomain = requestJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain"); + assertThat(newDomain.isJsonObject()).isTrue(); + JsonObject newDomainJsonObject = newDomain.getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newDomainJsonObject.keySet()).containsExactly("extraFields"); + JsonObject newDomainExtraFields = newDomainJsonObject.get("extraFields").getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newDomainExtraFields.keySet()).containsExactly("name", "value"); + } + + @Test + void shouldReplaceJsonObjectWithJsonElementFromPatch() { + //given + String patchJsonString = "{ \"event\": \"test\" }"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + assertThat(requestJson.get("event").isJsonObject()).isFalse(); + assertThat(requestJson.get("event").getAsString()).isEqualTo("test"); + } + + @Test + void shouldAddNewKeyIfPatchHasItAndTempleteDoesnt() { + //given + String patchJsonString = "{ \"newTestKey\": { \"newTestKeyChild\":\"newTestValue\" }}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + assertThat(requestJson.get("event").isJsonObject()).isTrue(); + assertThat(requestJson.get("newTestKey").isJsonObject()).isTrue(); + JsonObject newTestKey = requestJson.get("newTestKey").getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newTestKey.keySet()).containsExactly("newTestKeyChild"); + assertThat(newTestKey.get("newTestKeyChild").getAsString()).isEqualTo("newTestValue"); + + } + + + @Test + void shouldNotChangeInputTemplateParam() { + //given + String patchJsonString = "{ \"newTestKey\": { \"newTestKeyChild\":\"newTestValue\" }}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + assertThat(templateJson).isEqualTo(gson.fromJson(TEMPLATE_JSON, JsonObject.class)); + + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplateReaderTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplateReaderTest.java new file mode 100644 index 0000000..d25df49 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplateReaderTest.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.test.context.TestPropertySource; + +import java.io.IOException; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +@TestPropertySource +class TemplateReaderTest { + + private FilesystemTemplateReader templateReader = new FilesystemTemplateReader("src/test/resources/org/onap/integration/simulators/nfsimulator/vesclient/simulator/", new Gson()); + + @Test + void testShouldReadJsonFromFile() throws IOException { + JsonObject readJson = templateReader.readTemplate("validExampleMeasurementEvent.json"); + assertThat(readJson.keySet()).containsOnly("event"); + assertThat(readJson.get("event").getAsJsonObject().keySet()).containsExactlyInAnyOrder("commonEventHeader", "measurementsForVfScalingFields"); + } + + @Test + void testShouldRaiseExceptionWhenInvalidJsonIsRead() { + Assertions.assertThrows(JsonSyntaxException.class, () -> templateReader.readTemplate("invalidJsonStructureEvent.json")); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplateVariablesReplacerTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplateVariablesReplacerTest.java new file mode 100644 index 0000000..9bbc3e1 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/TemplateVariablesReplacerTest.java @@ -0,0 +1,174 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2019 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.integration.simulators.nfsimulator.vesclient.simulator; + + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import lombok.val; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import org.skyscreamer.jsonassert.JSONAssert; + +@TestInstance(Lifecycle.PER_CLASS) +class TemplateVariablesReplacerTest { + + private static final Gson GSON = new Gson(); + + private TemplateVariablesReplacer replacer; + + @BeforeAll + void setUp() { + replacer = new TemplateVariablesReplacer(); + } + + @Test + void shouldReplaceStringVariable() { + val sourceAsString = "{\"test1\":\"#variable1\", \"variable1\":\"value2 #variable1\"}"; + val expectedAsString = "{\"test1\":\"valueOfVariable1\", \"variable1\":\"value2 #variable1\"}"; + val variablesAsString = "{\"variable1\":\"valueOfVariable1\"}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceStringAndNumberVariable() { + val sourceAsString = "{\"test1\":\"#variable1\", \"test2\":\"#variable2\"}"; + val expectedAsString = "{\"test1\":\"valueOfVariable1=1\", \"test2\":2}"; + val variablesAsString = "{\"variable1\":\"valueOfVariable1=1\", \"variable2\":2}"; + + val source = new Gson().fromJson(sourceAsString, JsonObject.class); + val variables = new Gson().fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceSimpleStringVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":\"valueOfVariable1\"}"; + val variablesAsString = "{\"variable1\":\"valueOfVariable1\"}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceObjectVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":{\"replaced1\":\"valueOfVariable1\"}}"; + val variablesAsString = "{\"variable1\":{\"replaced1\":\"valueOfVariable1\"}}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceIntegerVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\": 1}"; + val variablesAsString = "{\"variable1\": 1}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceBoolVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\": true}"; + val variablesAsString = "{\"variable1\": true}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceDifferentVariables() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable\", \"variable2\":\"text #variable\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":{\"replaced1\":\"valueOfVariable1\"}, \"variable2\":\"text #variable\"}"; + val variablesAsString = "{\"variable\":{\"replaced1\":\"valueOfVariable1\"}}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceArrayVariables() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":[1,2,3]}"; + val variablesAsString = "{\"variable1\":[1,2,3]}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceArrayWithStringVariables() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":[\"1\",\"2\",\"3\"]}"; + val variablesAsString = "{\"variable1\":[\"1\",\"2\",\"3\"]}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceArrayAsStringVariables() { + val sourceAsString = "{\"test1\":\"#variable1\", \"variable1\":\"Text #variable1\"}"; + val expectedAsString = "{\"test1\":[1,2,3], \"variable1\": \"Text #variable1\"}"; + val variablesAsString = "{\"variable1\":[1,2,3]}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpApacheResponseAdapterFactoryTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpApacheResponseAdapterFactoryTest.java new file mode 100644 index 0000000..136a7d9 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpApacheResponseAdapterFactoryTest.java @@ -0,0 +1,98 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2021 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpTestUtils.createMockedHttpEntity; +import static org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpTestUtils.createStatusLine; + +class HttpApacheResponseAdapterFactoryTest { + + private HttpResponse httpResponse; + + @BeforeEach + void setup() { + httpResponse = mock(HttpResponse.class); + } + + @Test + void shouldCreateCorrectHttpResponseAdapterFromApacheHttpAcceptedResponse() throws IOException { + // given + final int responseCode = HttpStatus.SC_ACCEPTED; + final String responseBody = HttpTestUtils.HTTP_MESSAGE_ACCEPTER; + prepareHttpResponseMock(responseCode, createMockedHttpEntity(responseBody)); + + // when + HttpResponseAdapter httpResponseAdapter = new HttpApacheResponseAdapterFactory().create(httpResponse); + + // then + assertHttpResponseIsCorrect(responseCode, responseBody, httpResponseAdapter); + } + + + @Test + void shouldCreateCorrectHttpResponseAdapterFromApacheHttpForbiddenResponse() throws IOException { + // given + final int responseCode = HttpStatus.SC_FORBIDDEN; + final String responseBody = HttpTestUtils.HTTP_MESSAGE_FORBIDDEN; + prepareHttpResponseMock(responseCode, createMockedHttpEntity(responseBody)); + + // when + HttpResponseAdapter httpResponseAdapter = new HttpApacheResponseAdapterFactory().create(httpResponse); + + // then + assertHttpResponseIsCorrect(responseCode, responseBody, httpResponseAdapter); + } + + @Test + void shouldCreateCorrectHttpResponseAdapterFromApacheHttpResponseWithEmptyEntity() { + // given + final int responseCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; + prepareHttpResponseMock(responseCode, null); + + // when + HttpResponseAdapter httpResponseAdapter = new HttpApacheResponseAdapterFactory().create(httpResponse); + + + assertHttpResponseIsCorrect(responseCode, "", httpResponseAdapter); + } + + private void prepareHttpResponseMock(int responseCode, HttpEntity httpEntity) { + doReturn(createStatusLine(responseCode)).when(httpResponse).getStatusLine(); + doReturn(httpEntity).when(httpResponse).getEntity(); + } + + private void assertHttpResponseIsCorrect(int responseCode, String responseBody, HttpResponseAdapter httpResponseAdapter) { + assertEquals(responseCode, httpResponseAdapter.getCode()); + assertEquals(responseBody, httpResponseAdapter.getMessage()); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpClientAdapterImplTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpClientAdapterImplTest.java new file mode 100644 index 0000000..34243b6 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpClientAdapterImplTest.java @@ -0,0 +1,157 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client; + +import org.apache.http.Header; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.message.BasicHeader; +import org.apache.tomcat.util.codec.binary.Base64; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl.SslAuthenticationHelper; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpTestUtils.createMockedHttpEntity; +import static org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpTestUtils.createStatusLine; + +class HttpClientAdapterImplTest { + + private static final String HTTPS_URL = "https://0.0.0.0:8443/"; + private static final String HTTP_URL = "http://0.0.0.0:8000/"; + + private HttpClient httpClient; + private HttpResponse httpResponse; + + @BeforeEach + void setup() { + httpClient = mock(HttpClient.class); + httpResponse = mock(HttpResponse.class); + } + + @Test + void sendShouldSuccessfullySendRequestGivenValidUrl() throws IOException { + assertAdapterSentRequest("http://valid-url:8080", + HttpStatus.SC_FORBIDDEN, HttpTestUtils.HTTP_MESSAGE_FORBIDDEN); + } + + @Test + void sendShouldSuccessfullySendRequestGivenValidUrlUsingHttps() throws IOException { + assertAdapterSentRequest("https://valid-url:8443", + HttpStatus.SC_ACCEPTED, HttpTestUtils.HTTP_MESSAGE_ACCEPTER); + } + + @Test + void sendShouldSuccessfullySendRequestUsingBasicAuth() throws IOException { + String testUserInfo = "user1:pass1"; + Header authorizationHeader = createAuthorizationHeader(testUserInfo); + assertAdapterSentRequest("https://" + testUserInfo + "@valid-url:8443", + HttpStatus.SC_ACCEPTED, HttpTestUtils.HTTP_MESSAGE_ACCEPTER, + List.of(authorizationHeader)); + } + + @Test + void sendShouldFailToSendRequestGivenInvalidUrlUsingAdnShouldInformUser() throws IOException { + assertAdapterInformsUserWhenServiceIsUnavailable("https://invalid-url:8080"); + } + + @Test + void shouldThrowExceptionWhenMalformedVesUrlPassed() { + assertThrows(MalformedURLException.class, () -> new HttpClientAdapterImpl("http://blablabla:VES-PORT", new SslAuthenticationHelper())); + } + + @Test + void shouldCreateAdapterWithClientNotSupportingSslConnection() throws IOException, GeneralSecurityException { + HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTPS_URL, new SslAuthenticationHelper()); + try { + adapterWithHttps.send("sample"); + } catch (Exception actualException) { + assertThat(actualException).hasStackTraceContaining(SSLConnectionSocketFactory.class.toString()); + } + } + + @Test + void shouldCreateAdapterWithClientSupportingPlainConnectionOnly() throws IOException, GeneralSecurityException { + HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTP_URL, new SslAuthenticationHelper()); + try { + adapterWithHttps.send("sample"); + } catch (Exception actualException) { + assertThat(actualException).hasStackTraceContaining(PlainConnectionSocketFactory.class.toString()); + } + } + + private Header createAuthorizationHeader(String testUserInfo) { + String encodedUserInfo = new String(Base64.encodeBase64(testUserInfo.getBytes(StandardCharsets.UTF_8))); + return new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedUserInfo); + } + + private void assertAdapterSentRequest(String targetUrl, int responseCode, String responseMessage) throws IOException { + assertAdapterSentRequest(targetUrl, responseCode, responseMessage, List.of()); + } + + private void assertAdapterSentRequest(String targetUrl, int responseCode, String responseMessage, List<Header> expectedHeaders) throws IOException { + HttpClientAdapter adapter = new HttpClientAdapterImpl(httpClient, targetUrl); + doReturn(httpResponse).when(httpClient).execute(any()); + doReturn(createStatusLine(responseCode)).when(httpResponse).getStatusLine(); + doReturn(createMockedHttpEntity(responseMessage)).when(httpResponse).getEntity(); + + HttpResponseAdapter response = adapter.send("test-msg"); + + ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); + verify(httpClient).execute(httpPostCaptor.capture()); + Header[] headers = httpPostCaptor.getValue().getAllHeaders(); + assertEquals(responseCode, response.getCode()); + assertEquals(responseMessage, response.getMessage()); + assertThat(headers).usingFieldByFieldElementComparator().containsAll(expectedHeaders); + } + + private void assertAdapterInformsUserWhenServiceIsUnavailable(String targetUrl) throws IOException { + HttpClientAdapter adapter = new HttpClientAdapterImpl(httpClient, targetUrl); + String exceptionMessage = "test message"; + doThrow(new IOException(exceptionMessage)).when(httpClient).execute(any()); + + HttpResponseAdapter response = adapter.send("test-msg"); + + verify(httpClient).execute(any()); + assertEquals(421, response.getCode()); + assertEquals(String.format("Fail to connect with ves: %s", exceptionMessage), response.getMessage()); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpTestUtils.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpTestUtils.java new file mode 100644 index 0000000..5dc8d8c --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/HttpTestUtils.java @@ -0,0 +1,55 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2021 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client; + +import org.apache.http.HttpEntity; +import org.apache.http.ProtocolVersion; +import org.apache.http.message.BasicStatusLine; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +public class HttpTestUtils { + + private HttpTestUtils() { + } + + public static final String HTTP_MESSAGE_ACCEPTER = "Accepted"; + public static final String HTTP_MESSAGE_FORBIDDEN = "Forbidden"; + + static HttpEntity createMockedHttpEntity(String responseBody) throws IOException { + HttpEntity httpEntity = mock(HttpEntity.class); + doReturn(new ByteArrayInputStream(responseBody.getBytes())).when(httpEntity).getContent(); + return httpEntity; + } + + static BasicStatusLine createStatusLine(int responseCode) { + return new BasicStatusLine( + new ProtocolVersion("1.0.0", 1, 0), + responseCode, + "" + ); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/CertAuthSslContextFactoryTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/CertAuthSslContextFactoryTest.java new file mode 100644 index 0000000..eac7384 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/CertAuthSslContextFactoryTest.java @@ -0,0 +1,141 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.NoSuchFileException; +import java.security.GeneralSecurityException; +import javax.net.ssl.SSLContext; +import org.hamcrest.CoreMatchers; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +public class CertAuthSslContextFactoryTest { + + private static final String CERTIFICATES_DIRECTORY = "src/test/resources/certificates/"; + + private static final String KEYSTORE_FILENAME = "client.p12"; + private static final String VALID_KEYSTORE_PASSWORD_FILENAME = "client.pass"; + private static final String INVALID_KEYSTORE_PASSWORD_FILENAME = "client_invalid.pass"; + + private static final String TRUSTSTORE_FILENAME = "truststore"; + private static final String VALID_TRUSTSTORE_PASSWORD_FILENAME = "truststore.pass"; + private static final String INVALID_TRUSTSTORE_PASSWORD_FILENAME = "truststore_invalid.pass"; + + private static final String NON_EXISTING_PASSWORD_FILENAME = "non_existing.pass"; + private static final String PASSWORD_INCORRECT = "password was incorrect"; + + private CertAuthSslContextFactory certAuthSslContextFactory; + + @Before + public void setup() { + this.certAuthSslContextFactory = new CertAuthSslContextFactory(new CertificateReader()); + } + + @Test + public void shouldCreateSslContextSuccessfully_whenValidPasswordsUsed() + throws GeneralSecurityException, IOException { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + VALID_KEYSTORE_PASSWORD_FILENAME, VALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When + final SSLContext sslContext = certAuthSslContextFactory.createSslContext(sslAuthenticationHelper); + + // Then + assertNotNull(sslContext); + } + + @Test + public void shouldThrowIOException_whenInvalidKeystorePasswordUsed() { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + INVALID_KEYSTORE_PASSWORD_FILENAME, VALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When + final IOException exception = assertThrows(IOException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + + // Then + assertThat(exception.getMessage(), CoreMatchers.containsString(PASSWORD_INCORRECT)); + } + + @Test + public void shouldThrowIOException_whenInvalidTruststorePasswordUsed() { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + VALID_KEYSTORE_PASSWORD_FILENAME, INVALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When + final IOException exception = assertThrows(IOException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + + // Then + assertThat(exception.getMessage(), CoreMatchers.containsString(PASSWORD_INCORRECT)); + } + + @Test + public void shouldThrowNoSuchFileException_whenInvalidKeystoreFilePath() { + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + NON_EXISTING_PASSWORD_FILENAME, INVALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When, Then + assertThrows(NoSuchFileException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + } + + @Test + public void shouldThrowNoSuchFileException_whenInvalidTruststoreFilePath() { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + VALID_KEYSTORE_PASSWORD_FILENAME, NON_EXISTING_PASSWORD_FILENAME); + + // When, Then + assertThrows(NoSuchFileException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + } + + private SslAuthenticationHelper mockSslAuthenticationHelperWithFiles(String keystorePasswordFilename, + String truststorePasswordFilename) { + final SslAuthenticationHelper sslAuthenticationHelper = Mockito.mock(SslAuthenticationHelper.class); + + when(sslAuthenticationHelper.getClientCertificatePath()) + .thenReturn(getPath(KEYSTORE_FILENAME)); + when(sslAuthenticationHelper.getClientCertificatePasswordPath()) + .thenReturn(getPath(keystorePasswordFilename)); + when(sslAuthenticationHelper.getTrustStorePath()) + .thenReturn(getPath(TRUSTSTORE_FILENAME)); + when(sslAuthenticationHelper.getTrustStorePasswordPath()) + .thenReturn(getPath(truststorePasswordFilename)); + + return sslAuthenticationHelper; + } + + private String getPath(String fileName) { + return CERTIFICATES_DIRECTORY + fileName; + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/HttpClientFactoryFacadeTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/HttpClientFactoryFacadeTest.java new file mode 100644 index 0000000..805b54a --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/HttpClientFactoryFacadeTest.java @@ -0,0 +1,35 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertNotNull; + +class HttpClientFactoryFacadeTest { + @Test + void shouldSuccessfullyCreateHttpClient() throws GeneralSecurityException, IOException { + assertNotNull(HttpClientFactoryFacade.create("http://example.com", new SslAuthenticationHelper())); + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/HttpClientFactoryTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/HttpClientFactoryTest.java new file mode 100644 index 0000000..c5b447e --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/HttpClientFactoryTest.java @@ -0,0 +1,143 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl; + +import org.hamcrest.CoreMatchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.security.KeyStoreException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class HttpClientFactoryTest { + private static final String HTTPS_URL = "https://example.com"; + private static final String HTTP_URL = "http://example.com"; + + private SSLContextFactory sslContextFactoryMock; + private HttpClientFactory httpClientFactory; + private SslAuthenticationHelper sslAuthenticationHelper; + + @BeforeEach + public void setup() { + sslContextFactoryMock = mock(SSLContextFactory.class); + httpClientFactory = new HttpClientFactory(sslContextFactoryMock); + sslAuthenticationHelper = new SslAuthenticationHelper(); + } + + @Test + void shouldCreateHttpsClient_whenClientCertificationDisabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(false); + + // when + final var httpClient = httpClientFactory.create(HTTPS_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(0, 1); + } + + @Test + void shouldCreateHttpsClient_whenClientCertificationDisabled_AndCannotCreateTrustAlwaysSslContext() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(false); + when(sslContextFactoryMock.createTrustAlways()).thenThrow(KeyStoreException.class); + + // when + final var httpClient = httpClientFactory.create(HTTPS_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(0, 1); + } + + @Test + void shouldCreateHttpClient_whenClientCertificationDisabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(false); + + // when + final var httpClient = httpClientFactory.create(HTTP_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(0, 0); + } + + + @Test + void shouldCreateHttpClient_whenClientCertificationAndStrictHostnameVerificationAreEnabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(true); + sslAuthenticationHelper.setStrictHostnameVerification(true); + + // when + final var httpClient = httpClientFactory.create(HTTP_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(1, 0); + } + + @Test + void shouldCreateHttpClient_whenClientCertificationEnabledAndStrictHostnameVerificationDisabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(true); + sslAuthenticationHelper.setStrictHostnameVerification(false); + + // when + final var httpClient = httpClientFactory.create(HTTP_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(1, 0); + } + + @Test + void shouldThrowMalformedURLException_whenInvalidUrl() throws GeneralSecurityException, IOException { + // given + var invalidUrl = "invalid"; + + // when + final var exception = assertThrows(MalformedURLException.class, + () -> httpClientFactory.create(invalidUrl, sslAuthenticationHelper)); + + // then + assertThat(exception.getMessage(), CoreMatchers.containsString("invalid")); + } + + private void verifySslContextFactoryMockCalls(int createCalls, int createTrustAlwaysCalls) throws GeneralSecurityException, IOException { + verify(sslContextFactoryMock, times(createCalls)).create(any()); + verify(sslContextFactoryMock, times(createTrustAlwaysCalls)).createTrustAlways(); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/PasswordConverterTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/PasswordConverterTest.java new file mode 100644 index 0000000..67a1599 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/PasswordConverterTest.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class PasswordConverterTest { + + @Test + void shouldSuccessfullyConvert() { + // given, when + final char[] result = PasswordConverter.convert("sw ./#%"); + + // then + assertArrayEquals(new char[]{'s', 'w', ' ', '.', '/', '#', '%'}, result); + } + + @Test + void shouldReturnNull_whenNullPasswordUsed() { + // given, when, then + assertNull(PasswordConverter.convert(null)); + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/SSLContextFactoryTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/SSLContextFactoryTest.java new file mode 100644 index 0000000..cf22ebf --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/client/utils/ssl/SSLContextFactoryTest.java @@ -0,0 +1,61 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class SSLContextFactoryTest { + private CertificateReader certificateReaderMock; + private CertAuthSslContextFactory certAuthSslContextFactory; + private SSLContextFactory sslContextFactory; + + @BeforeEach + void setup() { + certificateReaderMock = mock(CertificateReader.class); + certAuthSslContextFactory = new CertAuthSslContextFactory(certificateReaderMock); + sslContextFactory = new SSLContextFactory(certAuthSslContextFactory); + } + + @Test + void shouldSuccessfullyCreateTrustAlwaysSSLContext() throws GeneralSecurityException, IOException { + // given, when, then + assertNotNull(sslContextFactory.createTrustAlways()); + verify(certificateReaderMock, times(0)).read(any(), any(), any()); + } + + @Test + void shouldSuccessfullyCreateSSLContext() throws GeneralSecurityException, IOException { + // given, when, then + assertNotNull(sslContextFactory.create(new SslAuthenticationHelper())); + verify(certificateReaderMock, times(2)).read(any(), any(), any()); + } + +} + diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/keywords/TwoParameterKeywordTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/keywords/TwoParameterKeywordTest.java new file mode 100644 index 0000000..8e38738 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/keywords/TwoParameterKeywordTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.keywords; + + +import io.vavr.Tuple1; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +class TwoParameterKeywordTest { + @Test + public void whenGivenKeywordShouldReturnTwoParameterKeywordObjectWithParsedValues() { + //given + final String expectedName = "TEST"; + final Integer expectedParam1 = 123; + final Integer expectedParam2 = 456; + + String keyword = "#" + expectedName + "(" + expectedParam1 + "," + expectedParam2 + ")"; + + //when + Tuple1<TwoParameterKeyword> keywordTuple = TwoParameterKeyword.twoParameterKeyword(keyword); + TwoParameterKeyword twoParameterKeyword = keywordTuple._1(); + + //then + assertEquals(twoParameterKeyword.getName(), expectedName); + assertEquals(twoParameterKeyword.getAdditionalParameter1(), expectedParam1); + assertEquals(twoParameterKeyword.getAdditionalParameter2(), expectedParam2); + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/scheduler/EventJobTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/scheduler/EventJobTest.java new file mode 100644 index 0000000..b452956 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/scheduler/EventJobTest.java @@ -0,0 +1,84 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.scheduler; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.KeywordsExtractor; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.KeywordsHandler; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.HttpClientAdapter; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobKey; + +class EventJobTest { + + @Test + void shouldSendEventWhenExecuteCalled() { + //given + EventJob eventJob = new EventJob(); + String templateName = "template name"; + String vesUrl = "http://someurl:80/"; + String eventId = "1"; + JsonParser parser = new JsonParser(); + JsonObject body = parser.parse("{\"a\": \"A\"}").getAsJsonObject(); + HttpClientAdapter clientAdapter = mock(HttpClientAdapter.class); + JobExecutionContext jobExecutionContext = + createMockJobExecutionContext(templateName, eventId, vesUrl, body, clientAdapter); + + ArgumentCaptor<String> vesUrlCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class); + + //when + eventJob.execute(jobExecutionContext); + + //then + verify(clientAdapter).send(bodyCaptor.capture()); + assertThat(bodyCaptor.getValue()).isEqualTo(body.toString()); + } + + private JobExecutionContext createMockJobExecutionContext(String templateName, String eventId, String vesUrl, + JsonObject body, HttpClientAdapter clientAdapter) { + + JobDataMap jobDataMap = new JobDataMap(); + jobDataMap.put(EventJob.TEMPLATE_NAME, templateName); + jobDataMap.put(EventJob.KEYWORDS_HANDLER, new KeywordsHandler(new KeywordsExtractor(), (id) -> 1)); + jobDataMap.put(EventJob.EVENT_ID, eventId); + jobDataMap.put(EventJob.VES_URL, vesUrl); + jobDataMap.put(EventJob.BODY, body); + jobDataMap.put(EventJob.CLIENT_ADAPTER, clientAdapter); + + JobExecutionContext jobExecutionContext = mock(JobExecutionContext.class); + JobDetail jobDetail = mock(JobDetail.class); + when(jobExecutionContext.getJobDetail()).thenReturn(jobDetail); + when(jobDetail.getJobDataMap()).thenReturn(jobDataMap); + when(jobDetail.getKey()).thenReturn(new JobKey("jobId", "group")); + return jobExecutionContext; + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/scheduler/EventSchedulerTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/scheduler/EventSchedulerTest.java new file mode 100644 index 0000000..88abeb5 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/simulator/scheduler/EventSchedulerTest.java @@ -0,0 +1,148 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.integration.simulators.nfsimulator.vesclient.simulator.scheduler; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.integration.simulators.nfsimulator.vesclient.simulator.client.utils.ssl.SslAuthenticationHelper; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.SimpleTrigger; + +class EventSchedulerTest { + + @InjectMocks + EventScheduler eventScheduler; + + @Mock + Scheduler quartzScheduler; + + @Mock + SslAuthenticationHelper sslAuthenticationHelper; + + @BeforeEach + void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + void shouldTriggerEventWithGivenConfiguration() throws SchedulerException, IOException, GeneralSecurityException { + //given + ArgumentCaptor<JobDetail> jobDetailCaptor = ArgumentCaptor.forClass(JobDetail.class); + ArgumentCaptor<SimpleTrigger> triggerCaptor = ArgumentCaptor.forClass(SimpleTrigger.class); + + String vesUrl = "http://some:80/"; + int repeatInterval = 1; + int repeatCount = 4; + String testName = "testName"; + String eventId = "1"; + JsonObject body = new JsonObject(); + + //when + eventScheduler.scheduleEvent(vesUrl, repeatInterval, repeatCount, testName, eventId, body); + + //then + verify(quartzScheduler).scheduleJob(jobDetailCaptor.capture(), triggerCaptor.capture()); + JobDataMap actualJobDataMap = jobDetailCaptor.getValue().getJobDataMap(); + assertThat(actualJobDataMap.get(EventJob.BODY)).isEqualTo(body); + assertThat(actualJobDataMap.get(EventJob.TEMPLATE_NAME)).isEqualTo(testName); + assertThat(actualJobDataMap.get(EventJob.VES_URL)).isEqualTo(vesUrl); + + SimpleTrigger actualTrigger = triggerCaptor.getValue(); + // repeat count adds 1 to given value + assertThat(actualTrigger.getRepeatCount()).isEqualTo(repeatCount - 1); + + //getRepeatInterval returns interval in ms + assertThat(actualTrigger.getRepeatInterval()).isEqualTo(repeatInterval * 1000); + } + + @Test + void shouldCancelAllEvents() throws SchedulerException { + //given + List<JobKey> jobsKeys = Arrays.asList(new JobKey("jobName1"), new JobKey("jobName2"), + new JobKey("jobName3"), new JobKey("jobName4")); + List<JobExecutionContext> jobExecutionContexts = createExecutionContextWithKeys(jobsKeys); + when(quartzScheduler.getCurrentlyExecutingJobs()).thenReturn(jobExecutionContexts); + when(quartzScheduler.deleteJobs(jobsKeys)).thenReturn(true); + + //when + boolean isCancelled = eventScheduler.cancelAllEvents(); + + //then + assertThat(isCancelled).isTrue(); + } + + @Test + void shouldCancelSingleEvent() throws SchedulerException { + //given + JobKey jobToRemove = new JobKey("jobName3"); + List<JobKey> jobsKeys = Arrays.asList(new JobKey("jobName1"), new JobKey("jobName2"), + jobToRemove, new JobKey("jobName4")); + List<JobExecutionContext> jobExecutionContexts = createExecutionContextWithKeys(jobsKeys); + + when(quartzScheduler.getCurrentlyExecutingJobs()).thenReturn(jobExecutionContexts); + when(quartzScheduler.deleteJob(jobToRemove)).thenReturn(true); + + //when + boolean isCancelled = eventScheduler.cancelEvent("jobName3"); + + //then + assertThat(isCancelled).isTrue(); + } + + private List<JobExecutionContext> createExecutionContextWithKeys(List<JobKey> jobsKeys) { + List<JobExecutionContext> contexts = new ArrayList<>(); + for (JobKey key : jobsKeys) { + contexts.add(createExecutionContextFromKey(key)); + } + return contexts; + } + + private JobExecutionContext createExecutionContextFromKey(JobKey key) { + JobExecutionContext context = mock(JobExecutionContext.class); + JobDetail jobDetail = mock(JobDetail.class); + when(context.getJobDetail()).thenReturn(jobDetail); + when(jobDetail.getKey()).thenReturn(key); + return context; + } + + +} |