aboutsummaryrefslogtreecommitdiffstats
path: root/prh-app-server/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'prh-app-server/src/test/java')
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsClientConfigurationResolverTest.java51
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsJsonToPropertyMapConverterTest.java80
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsPropertySourceLocatorTest.java164
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/TestAppConfiguration.java68
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigRefreshSchedulerTest.java138
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigurationTest.java70
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CloudConfigParserTest.java87
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/ConsulConfigurationParserTest.java169
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/PrhAppConfigTest.java108
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/AppInfoControllerTest.java69
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/ScheduleControllerTest.java75
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/PrhWorkflowIntegrationTest.java124
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/PrhWorkflowSchedulingIntegrationTest.java (renamed from prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/ServiceMockProvider.java)36
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/ScheduledXmlContextITest.java63
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/junit5/mockito/MockitoExtension.java82
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/DmaapConsumerJsonParserTest.java559
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImplTest.java79
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiPublisherTaskSpy.java61
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiQueryTaskImplTest.java206
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/BbsActionsTaskTest.java245
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImplTest.java127
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskSpy.java58
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapProducerTaskSpy.java56
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java128
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduleControllerSpy.java56
-rw-r--r--prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduledTasksTest.java186
26 files changed, 2106 insertions, 1039 deletions
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsClientConfigurationResolverTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsClientConfigurationResolverTest.java
new file mode 100644
index 00000000..87dd18ca
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsClientConfigurationResolverTest.java
@@ -0,0 +1,51 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.bootstrap;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class CbsClientConfigurationResolverTest {
+
+ private CbsProperties cbsProperties;
+
+ @BeforeEach
+ void setUp() {
+ cbsProperties = new CbsProperties();
+ cbsProperties.setHostname("some-cbs-host");
+ cbsProperties.setPort(123);
+ cbsProperties.setAppName("client-app-name");
+ }
+
+ @Test
+ @DisabledIfEnvironmentVariable(named = "CONFIG_BINDING_SERVICE", matches = ".+")
+ void whenCbsEnvPropertiesAreNotePresentInEnvironment_ShouldFallbackToLoadingDefaultsFromCbsProperties() {
+ CbsClientConfiguration config = new CbsClientConfigurationResolver(cbsProperties).resolveCbsClientConfiguration();
+
+ assertThat(config.hostname()).isEqualTo(cbsProperties.getHostname());
+ assertThat(config.port()).isEqualTo(cbsProperties.getPort());
+ assertThat(config.appName()).isEqualTo(cbsProperties.getAppName());
+ }
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsJsonToPropertyMapConverterTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsJsonToPropertyMapConverterTest.java
new file mode 100644
index 00000000..55e1b014
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsJsonToPropertyMapConverterTest.java
@@ -0,0 +1,80 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.bootstrap;
+
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class CbsJsonToPropertyMapConverterTest {
+
+ private static final JsonObject SOME_JSON_FROM_CBS = asJsonObject(
+ "{\n" +
+ " \"config\": {\n" +
+ " \"someStringProp\": \"foo\",\n" +
+ " \"someNumericalProp\": 123,\n" +
+ " \"someBooleanProp\": true,\n" +
+ " \"someArrayProp\": [],\n" +
+ " \"someObjectProp\": {\n" +
+ " \"bar\": \"baz\"\n" +
+ " }\n" +
+ " }\n" +
+ "}"
+ );
+
+ private CbsJsonToPropertyMapConverter cbsJsonToPropertyMapConverter = new CbsJsonToPropertyMapConverter();
+
+ @Test
+ void shouldExtractPrimitivePropertiesToSimpleJavaTypes() {
+ Map<String, Object> map = cbsJsonToPropertyMapConverter.convertToMap(SOME_JSON_FROM_CBS);
+
+ assertThat(map).containsEntry("someStringProp", "foo");
+ assertThat(map).containsEntry("someNumericalProp", 123L);
+ assertThat(map).containsEntry("someBooleanProp", true);
+
+ }
+
+ @Test
+ void shouldSkipComplexProperties() {
+ Map<String, Object> map = cbsJsonToPropertyMapConverter.convertToMap(SOME_JSON_FROM_CBS);
+
+ assertThat(map).doesNotContainKeys("someObjectProp");
+ assertThat(map).doesNotContainKeys("someArrayProp");
+ }
+
+ @Test
+ void shouldProduceDescriptiveExceptionInCaseExpectedRootElementInCbsJsonIsMissing() {
+ assertThatThrownBy(() -> cbsJsonToPropertyMapConverter.convertToMap(asJsonObject("{}")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Missing expected 'config' property in json from CBS.");
+ }
+
+
+ private static JsonObject asJsonObject(String jsonString) {
+ return new JsonParser().parse(jsonString).getAsJsonObject();
+ }
+
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsPropertySourceLocatorTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsPropertySourceLocatorTest.java
new file mode 100644
index 00000000..faf1867a
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/bootstrap/CbsPropertySourceLocatorTest.java
@@ -0,0 +1,164 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.bootstrap;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.gson.JsonObject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.onap.dcaegen2.services.prh.configuration.CbsConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.RequestPath;
+import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
+import org.springframework.core.env.Environment;
+import org.springframework.core.env.PropertySource;
+import reactor.core.publisher.Mono;
+import reactor.test.scheduler.VirtualTimeScheduler;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assumptions.assumeThat;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.Mockito.*;
+
+
+@ExtendWith(MockitoExtension.class)
+class CbsPropertySourceLocatorTest {
+
+ private static final RequestPath GET_ALL_REQUEST_PATH = CbsRequests.getAll(RequestDiagnosticContext.create()).requestPath();
+
+ private CbsProperties cbsProperties = new CbsProperties();
+ @Mock
+ private CbsJsonToPropertyMapConverter cbsJsonToPropertyMapConverter;
+ @Mock
+ private CbsClientConfiguration cbsClientConfiguration;
+ @Mock
+ private CbsClientConfigurationResolver cbsClientConfigurationResolver;
+ @Mock
+ private CbsClientFactoryFacade cbsClientFactoryFacade;
+ @Mock
+ private CbsConfiguration cbsConfiguration;
+ @Mock
+ private Environment environment;
+ @Mock
+ private CbsClient cbsClient;
+ @Mock
+ private JsonObject cbsConfigJsonObject;
+ private Map<String, Object> cbsConfigMap = ImmutableMap.of("foo", "bar");
+
+ private VirtualTimeScheduler virtualTimeScheduler;
+
+ private CbsPropertySourceLocator cbsPropertySourceLocator;
+
+
+ @BeforeEach
+ void setup() {
+ virtualTimeScheduler = VirtualTimeScheduler.getOrSet();
+
+ when(cbsClientConfigurationResolver.resolveCbsClientConfiguration()).thenReturn(cbsClientConfiguration);
+ when(cbsClientFactoryFacade.createCbsClient(cbsClientConfiguration)).thenReturn(Mono.just(cbsClient));
+
+ cbsPropertySourceLocator = new CbsPropertySourceLocator(
+ cbsProperties, cbsJsonToPropertyMapConverter, cbsClientConfigurationResolver,
+ cbsClientFactoryFacade, cbsConfiguration);
+ }
+
+ @AfterEach
+ void cleanup() {
+ virtualTimeScheduler.dispose();
+ }
+
+
+ @Test
+ void shouldBuildCbsPropertySourceBasedOnDataFetchedUsingCbsClient() {
+ when(cbsClient.get(argThat(request -> request.requestPath().equals(GET_ALL_REQUEST_PATH))))
+ .thenReturn(Mono.just(cbsConfigJsonObject));
+ when(cbsJsonToPropertyMapConverter.convertToMap(cbsConfigJsonObject)).thenReturn(cbsConfigMap);
+
+ PropertySource<?> propertySource = cbsPropertySourceLocator.locate(environment);
+
+ assertThat(propertySource).extracting(PropertySource::getName).isEqualTo("cbs");
+ assertThat(propertySource).extracting(s -> s.getProperty("foo")).isEqualTo("bar");
+ }
+
+
+ @Test
+ void shouldUpdateCbsConfigurationStateBasedOnDataFetchedUsingCbsClient() {
+ when(cbsClient.get(argThat(request -> request.requestPath().equals(GET_ALL_REQUEST_PATH))))
+ .thenReturn(Mono.just(cbsConfigJsonObject));
+ when(cbsJsonToPropertyMapConverter.convertToMap(cbsConfigJsonObject)).thenReturn(cbsConfigMap);
+
+ cbsPropertySourceLocator.locate(environment);
+
+ verify(cbsConfiguration).parseCBSConfig(cbsConfigJsonObject);
+ }
+
+
+ @Test
+ void shouldPropagateExceptionWhenCbsConfigurationParsingFails() {
+ when(cbsClient.get(any(CbsRequest.class))).thenReturn(Mono.just(cbsConfigJsonObject));
+
+ RuntimeException someCbsConfigParsingException = new RuntimeException("boom!");
+ doThrow(someCbsConfigParsingException).when(cbsConfiguration).parseCBSConfig(cbsConfigJsonObject);
+
+ assertThatThrownBy(() -> cbsPropertySourceLocator.locate(environment))
+ .isSameAs(someCbsConfigParsingException);
+ }
+
+ @Test
+ void shouldRetryFetchingConfigFromCbsInCaseOfFailure() {
+ assumeThat(cbsProperties.getFetchRetries().getMaxAttempts()).isGreaterThan(1);
+ when(cbsClient.get(any(CbsRequest.class)))
+ .thenReturn(Mono.defer(() -> {
+ virtualTimeScheduler.advanceTimeBy(cbsProperties.getFetchRetries().getMaxBackoff());
+ return Mono.error(new RuntimeException("some connection failure"));
+ }))
+ .thenReturn(Mono.just(cbsConfigJsonObject));
+ when(cbsJsonToPropertyMapConverter.convertToMap(cbsConfigJsonObject)).thenReturn(cbsConfigMap);
+
+ PropertySource<?> propertySource = cbsPropertySourceLocator.locate(environment);
+
+ assertThat(propertySource).extracting(s -> s.getProperty("foo")).isEqualTo("bar");
+ }
+
+ @Test
+ void shouldFailAfterExhaustingAllOfConfiguredRetryAttempts() {
+ assumeThat(cbsProperties.getFetchRetries().getMaxAttempts()).isGreaterThan(1);
+ when(cbsClient.get(any(CbsRequest.class)))
+ .thenReturn(Mono.defer(() -> {
+ virtualTimeScheduler.advanceTimeBy(cbsProperties.getFetchRetries().getMaxBackoff());
+ return Mono.error(new RuntimeException("some connection failure"));
+ }));
+
+ assertThatThrownBy(() -> cbsPropertySourceLocator.locate(environment))
+ .hasMessageContaining("Retries exhausted")
+ .hasMessageContaining(cbsProperties.getFetchRetries().getMaxAttempts().toString());
+ }
+}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/TestAppConfiguration.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/TestAppConfiguration.java
index cdfffbd1..c11fe492 100644
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/TestAppConfiguration.java
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/TestAppConfiguration.java
@@ -20,65 +20,57 @@
package org.onap.dcaegen2.services.prh;
+import org.onap.dcaegen2.services.sdk.model.streams.dmaap.ImmutableMessageRouterSink;
+import org.onap.dcaegen2.services.sdk.model.streams.dmaap.ImmutableMessageRouterSource;
import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.ImmutableAaiClientConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.ImmutableDmaapConsumerConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.ImmutableDmaapPublisherConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.ContentType;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterPublishRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterSubscribeRequest;
+
+import java.time.Duration;
public class TestAppConfiguration {
- public static ImmutableDmaapConsumerConfiguration createDefaultDmaapConsumerConfiguration() {
- return new ImmutableDmaapConsumerConfiguration.Builder()
+ public static ImmutableMessageRouterSubscribeRequest createDefaultMessageRouterSubscribeRequest() {
+ return ImmutableMessageRouterSubscribeRequest.builder()
.consumerGroup("OpenDCAE-c12")
+ .sourceDefinition(ImmutableMessageRouterSource.builder()
+ .name("the topic")
+ .topicUrl(String.format("http://%s:%d/events/TOPIC", "www", 1234))
+ .build())
.consumerId("c12")
- .dmaapContentType("application/json")
- .dmaapHostName("message-router.onap.svc.cluster.local")
- .dmaapPortNumber(3904)
- .dmaapProtocol("http")
- .dmaapUserName("admin")
- .dmaapUserPassword("admin")
- .trustStorePath("/opt/app/prh/local/org.onap.prh.trust.jks")
- .trustStorePasswordPath("change_it")
- .keyStorePath("/opt/app/prh/local/org.onap.prh.p12")
- .keyStorePasswordPath("change_it")
- .enableDmaapCertAuth(false)
- .dmaapTopicName("/events/unauthenticated.SEC_OTHER_OUTPUT")
- .timeoutMs(-1)
- .messageLimit(-1)
+ .timeout(Duration.ofMillis(1))
.build();
}
- public static ImmutableDmaapPublisherConfiguration createDefaultDmaapPublisherConfiguration() {
- return new ImmutableDmaapPublisherConfiguration.Builder()
- .dmaapContentType("application/json")
- .dmaapHostName("message-router.onap.svc.cluster.local")
- .dmaapPortNumber(3904)
- .dmaapProtocol("http")
- .dmaapUserName("admin")
- .dmaapUserPassword("admin")
- .trustStorePath("/opt/app/prh/local/org.onap.prh.trust.jks")
- .trustStorePasswordPath("change_it")
- .keyStorePath("/opt/app/prh/local/org.onap.prh.p12")
- .keyStorePasswordPath("change_it")
- .enableDmaapCertAuth(false)
- .dmaapTopicName("/events/unauthenticated.PNF_READY")
+ public static ImmutableMessageRouterPublishRequest createDefaultMessageRouterPublishRequest() {
+ return ImmutableMessageRouterPublishRequest.builder()
+ .contentType(ContentType.APPLICATION_JSON)
+ .sinkDefinition(ImmutableMessageRouterSink.builder()
+ .name("the topic")
+ .topicUrl(String.format("http://%s:%d/events/TOPIC", "www", 1234))
+ .build())
.build();
- }
+
+ }
public static ImmutableAaiClientConfiguration createDefaultAaiClientConfiguration() {
return new ImmutableAaiClientConfiguration.Builder()
- .aaiHost("aai.onap.svc.cluster.local")
- .aaiPort(8443)
- .aaiProtocol("https")
+ .pnfUrl("https://aai.onap.svc.cluster.local:8443/aai/v12/network/pnfs/pnf")
.aaiUserName("AAI")
.aaiUserPassword("AAI")
.aaiIgnoreSslCertificateErrors(true)
- .aaiBasePath("/aai/v12")
- .aaiPnfPath("/network/pnfs/pnf")
+ .aaiServiceInstancePath("/business/customers/customer/${customer}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${serviceInstanceId}")
.trustStorePath("/opt/app/prh/local/org.onap.prh.trust.jks")
.trustStorePasswordPath("change_it")
.keyStorePath("/opt/app/prh/local/org.onap.prh.p12")
.keyStorePasswordPath("change_it")
.enableAaiCertAuth(false)
+ .putAaiHeaders("X-FromAppId","prh")
+ .putAaiHeaders("X-TransactionId","9999")
+ .putAaiHeaders("Accept","application/json")
+ .putAaiHeaders("Real-Time","true")
+ .putAaiHeaders("Authorization","Basic QUFJOkFBSQ==")
.build();
}
} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigRefreshSchedulerTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigRefreshSchedulerTest.java
new file mode 100644
index 00000000..7ea08aea
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigRefreshSchedulerTest.java
@@ -0,0 +1,138 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.prh.configuration;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
+import org.springframework.cloud.context.refresh.ContextRefresher;
+import org.springframework.core.env.Environment;
+import reactor.test.scheduler.VirtualTimeScheduler;
+
+import java.time.Duration;
+import java.util.Collections;
+
+import static org.mockito.Mockito.*;
+
+
+@ExtendWith(MockitoExtension.class)
+class CbsConfigRefreshSchedulerTest {
+
+ private static final Duration SOME_UPDATES_INTERVAL = Duration.ofMinutes(5);
+ private static final String CBS_UPDATES_INTERVAL_PROPERTY = "cbs.updates-interval";
+
+ @Mock
+ private ContextRefresher contextRefresher;
+ @Mock
+ private Environment environment;
+
+ private VirtualTimeScheduler virtualTimeScheduler;
+
+ private CbsConfigRefreshScheduler cbsConfigRefreshScheduler;
+
+
+ @BeforeEach
+ void setUp() {
+ virtualTimeScheduler = VirtualTimeScheduler.getOrSet();
+ when(environment.getProperty(CBS_UPDATES_INTERVAL_PROPERTY, Duration.class, Duration.ZERO))
+ .thenReturn(SOME_UPDATES_INTERVAL);
+
+ cbsConfigRefreshScheduler = new CbsConfigRefreshScheduler(contextRefresher, environment);
+ }
+
+ @AfterEach
+ void tearDown() {
+ virtualTimeScheduler.dispose();
+ }
+
+ @Test
+ void configRefreshUpdatesShouldBeFiredAccordingToConfiguredInterval() {
+ cbsConfigRefreshScheduler.startPollingForCbsUpdates();
+
+ verify(contextRefresher, times(0)).refresh();
+
+ virtualTimeScheduler.advanceTimeBy(SOME_UPDATES_INTERVAL);
+ verify(contextRefresher, times(1)).refresh();
+
+ virtualTimeScheduler.advanceTimeBy(SOME_UPDATES_INTERVAL);
+ verify(contextRefresher, times(2)).refresh();
+ }
+
+ @Test
+ void whenConfigUpdateIntervalIsSetToZero_UpdatesShouldNotBeExecuted() {
+ when(environment.getProperty(CBS_UPDATES_INTERVAL_PROPERTY, Duration.class, Duration.ZERO))
+ .thenReturn(Duration.ZERO);
+
+ cbsConfigRefreshScheduler.startPollingForCbsUpdates();
+
+ virtualTimeScheduler.advanceTimeBy(Duration.ofHours(10));
+
+ verifyZeroInteractions(contextRefresher);
+ }
+
+ @Test
+ void whenUpdateFails_shouldContinueWithUpdateRequestsAccordingToConfiguredSchedule() {
+ when(contextRefresher.refresh())
+ .thenThrow(new RuntimeException("kaboom!"))
+ .thenReturn(Collections.emptySet());
+
+ cbsConfigRefreshScheduler.startPollingForCbsUpdates();
+
+ virtualTimeScheduler.advanceTimeBy(SOME_UPDATES_INTERVAL.plus(SOME_UPDATES_INTERVAL));
+ verify(contextRefresher, times(2)).refresh();
+ }
+
+
+ @Test
+ void whenUpdatesIntervalIsChangedInEnvironment_UpdatesShouldBeRescheduled() {
+ when(environment.getProperty(CBS_UPDATES_INTERVAL_PROPERTY, Duration.class, Duration.ZERO))
+ .thenReturn(Duration.ofMinutes(30))
+ .thenReturn(Duration.ofSeconds(10));
+
+ cbsConfigRefreshScheduler.startPollingForCbsUpdates();
+
+ cbsConfigRefreshScheduler.onEnvironmentChanged(
+ new EnvironmentChangeEvent(Collections.singleton(CBS_UPDATES_INTERVAL_PROPERTY)));
+
+ virtualTimeScheduler.advanceTimeBy(Duration.ofMinutes(1));
+
+ verify(contextRefresher, times(6)).refresh();
+ }
+
+
+ @Test
+ void whenEnvironmentChangeDoesNotAffectUpdatesInterval_UpdatesScheduleShouldNotBeImpacted() {
+ cbsConfigRefreshScheduler.startPollingForCbsUpdates();
+
+ Duration envChangeDelay = Duration.ofMinutes(1);
+ virtualTimeScheduler.advanceTimeBy(envChangeDelay);
+
+ cbsConfigRefreshScheduler.onEnvironmentChanged(new EnvironmentChangeEvent(Collections.emptySet()));
+
+ virtualTimeScheduler.advanceTimeBy(SOME_UPDATES_INTERVAL.minus(envChangeDelay));
+
+ verify(contextRefresher).refresh();
+ }
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigurationTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigurationTest.java
new file mode 100644
index 00000000..7f5d26fc
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CbsConfigurationTest.java
@@ -0,0 +1,70 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.prh.configuration;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import org.junit.jupiter.api.Test;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+import static java.lang.ClassLoader.getSystemResource;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class CbsConfigurationTest {
+
+ private static final String EXPECTED_ERROR_MESSAGE_WHEN_CBS_CONFIG_IS_NOT_INITIALIZED = "CBS config missing";
+
+ @Test
+ void whenConfigurationIsNotInitializedBasedOnDataReceivedFromCbs_shouldThrowExceptionWithDescriptiveMessage() {
+ assertThatThrownBy(() -> new CbsConfiguration().getAaiClientConfiguration())
+ .hasMessage(EXPECTED_ERROR_MESSAGE_WHEN_CBS_CONFIG_IS_NOT_INITIALIZED);
+ assertThatThrownBy(() -> new CbsConfiguration().getMessageRouterPublisher())
+ .hasMessage(EXPECTED_ERROR_MESSAGE_WHEN_CBS_CONFIG_IS_NOT_INITIALIZED);
+ assertThatThrownBy(() -> new CbsConfiguration().getMessageRouterSubscriber())
+ .hasMessage(EXPECTED_ERROR_MESSAGE_WHEN_CBS_CONFIG_IS_NOT_INITIALIZED);
+ assertThatThrownBy(() -> new CbsConfiguration().getMessageRouterSubscribeRequest())
+ .hasMessage(EXPECTED_ERROR_MESSAGE_WHEN_CBS_CONFIG_IS_NOT_INITIALIZED);
+ assertThatThrownBy(() -> new CbsConfiguration().getMessageRouterPublishRequest())
+ .hasMessage(EXPECTED_ERROR_MESSAGE_WHEN_CBS_CONFIG_IS_NOT_INITIALIZED);
+ assertThatThrownBy(() -> new CbsConfiguration().getMessageRouterUpdatePublishRequest())
+ .hasMessage(EXPECTED_ERROR_MESSAGE_WHEN_CBS_CONFIG_IS_NOT_INITIALIZED);
+ }
+
+
+ @Test
+ void cbsConfigurationShouldExposeDataReceivedAsJsonFromCbs() throws Exception {
+ JsonObject cbsConfigJson = new Gson().fromJson(new String(Files.readAllBytes(Paths.get(
+ getSystemResource("configurationFromCbs.json").toURI()))), JsonObject.class);
+ CbsConfiguration cbsConfiguration = new CbsConfiguration();
+
+ cbsConfiguration.parseCBSConfig(cbsConfigJson);
+
+ assertThat(cbsConfiguration.getAaiClientConfiguration()).isNotNull();
+ assertThat(cbsConfiguration.getMessageRouterPublisher()).isNotNull();
+ assertThat(cbsConfiguration.getMessageRouterSubscriber()).isNotNull();
+ assertThat(cbsConfiguration.getMessageRouterPublishRequest()).isNotNull();
+ assertThat(cbsConfiguration.getMessageRouterSubscribeRequest()).isNotNull();
+ assertThat(cbsConfiguration.getMessageRouterUpdatePublishRequest()).isNotNull();
+ }
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CloudConfigParserTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CloudConfigParserTest.java
deleted file mode 100644
index 8f421034..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/CloudConfigParserTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PNF-REGISTRATION-HANDLER
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.configuration;
-
-import static java.lang.ClassLoader.getSystemResource;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonObject;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import org.junit.jupiter.api.Test;
-import org.onap.dcaegen2.services.prh.TestAppConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.AaiClientConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.ImmutableAaiClientConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapConsumerConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.ImmutableDmaapConsumerConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.ImmutableDmaapPublisherConfiguration;
-
-
-class CloudConfigParserTest {
-
- private final String correctJson =
- new String(Files.readAllBytes(Paths.get(getSystemResource("flattened_configuration.json").toURI())));
- private final ImmutableAaiClientConfiguration correctAaiClientConfig =
- TestAppConfiguration.createDefaultAaiClientConfiguration();
- private final ImmutableDmaapConsumerConfiguration correctDmaapConsumerConfig =
- TestAppConfiguration.createDefaultDmaapConsumerConfiguration();
- private final ImmutableDmaapPublisherConfiguration correctDmaapPublisherConfig =
- TestAppConfiguration.createDefaultDmaapPublisherConfiguration();
- private final CloudConfigParser cloudConfigParser = new CloudConfigParser(
- new Gson().fromJson(correctJson, JsonObject.class));
-
- CloudConfigParserTest() throws Exception {
- }
-
- @Test
- void shouldCreateAaiConfigurationCorrectly() {
- // when
- AaiClientConfiguration aaiClientConfig = cloudConfigParser.getAaiClientConfig();
-
- // then
- assertThat(aaiClientConfig).isNotNull();
- assertThat(aaiClientConfig).isEqualToComparingFieldByField(correctAaiClientConfig);
- }
-
-
- @Test
- void shouldCreateDmaapConsumerConfigurationCorrectly() {
- // when
- DmaapConsumerConfiguration dmaapConsumerConfig = cloudConfigParser.getDmaapConsumerConfig();
-
- // then
- assertThat(dmaapConsumerConfig).isNotNull();
- assertThat(dmaapConsumerConfig).isEqualToComparingFieldByField(correctDmaapConsumerConfig);
- }
-
-
- @Test
- void shouldCreateDmaapPublisherConfigurationCorrectly() {
- // when
- DmaapPublisherConfiguration dmaapPublisherConfig = cloudConfigParser.getDmaapPublisherConfig();
-
- // then
- assertThat(dmaapPublisherConfig).isNotNull();
- assertThat(dmaapPublisherConfig).isEqualToComparingFieldByField(correctDmaapPublisherConfig);
- }
-} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/ConsulConfigurationParserTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/ConsulConfigurationParserTest.java
new file mode 100644
index 00000000..3a4db1dd
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/ConsulConfigurationParserTest.java
@@ -0,0 +1,169 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.configuration;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import org.jetbrains.annotations.Nullable;
+import org.junit.jupiter.api.Test;
+import org.onap.dcaegen2.services.prh.TestAppConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.AaiClientConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.ImmutableAaiClientConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.ContentType;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterSubscribeRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.MessageRouterPublisherConfig;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.MessageRouterSubscriberConfig;
+import org.onap.dcaegen2.services.sdk.security.ssl.SecurityKeys;
+
+import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.time.Duration;
+
+import static java.lang.ClassLoader.getSystemResource;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+
+class ConsulConfigurationParserTest {
+
+ private final String correctJson =
+ new String(Files.readAllBytes(Paths.get(getSystemResource("configurationFromCbs.json").toURI())));
+ private final ImmutableAaiClientConfiguration correctAaiClientConfig =
+ TestAppConfiguration.createDefaultAaiClientConfiguration();
+
+ private final JsonObject correctConfig = new Gson().fromJson(correctJson, JsonObject.class);
+ private final CbsContentParser consulConfigurationParser = new CbsContentParser(correctConfig);
+
+ ConsulConfigurationParserTest() throws Exception {
+ }
+
+ @Test
+ void shouldCreateAaiConfigurationCorrectly() {
+ // when
+ AaiClientConfiguration aaiClientConfig = consulConfigurationParser.getAaiClientConfig();
+
+ // then
+ assertThat(aaiClientConfig).isNotNull();
+ assertThat(aaiClientConfig).isEqualToComparingFieldByField(correctAaiClientConfig);
+ }
+
+ @Test
+ void shouldCreateMessageRouterSubscribeRequestCorrectly() {
+ // given
+ MessageRouterSubscribeRequest messageRouterSubscribeRequest = consulConfigurationParser.getMessageRouterSubscribeRequest();
+
+ // then
+ assertThat(messageRouterSubscribeRequest.sourceDefinition().topicUrl()).isEqualTo("http://dmaap-mr:2222/events/unauthenticated.VES_PNFREG_OUTPUT");
+ assertThat(messageRouterSubscribeRequest.consumerGroup()).isEqualTo("OpenDCAE-c12");
+ assertThat(messageRouterSubscribeRequest.consumerId()).isEqualTo("c12");
+ assertThat(messageRouterSubscribeRequest.timeout()).isEqualTo(Duration.ofMillis(-1));
+ }
+
+ @Test
+ void shouldCreateMessageRouterPublishConfigurationCorrectly() {
+ // when
+ MessageRouterPublishRequest messageRouterPublishRequest = consulConfigurationParser.getMessageRouterPublishRequest();
+
+ // then
+ assertThat(messageRouterPublishRequest.contentType()).isEqualTo(ContentType.APPLICATION_JSON);
+ assertThat(messageRouterPublishRequest.sinkDefinition().topicUrl()).isEqualTo("http://dmaap-mr:2222/events/unauthenticated.PNF_READY");
+ }
+
+ @Test
+ void shouldCreateMessageRouterUpdatePublishConfigurationCorrectly() {
+ // when
+ MessageRouterPublishRequest messageRouterPublishRequest = consulConfigurationParser.getMessageRouterUpdatePublishRequest();
+
+ // then
+ assertThat(messageRouterPublishRequest.contentType()).isEqualTo(ContentType.APPLICATION_JSON);
+ assertThat(messageRouterPublishRequest.sinkDefinition().topicUrl()).isEqualTo("http://dmaap-mr:2222/events/unauthenticated.PNF_UPDATE");
+ }
+
+ @Test
+ void whenDmaapCertAuthIsDisabled_MessageRouterPublisherConfigSecurityKeysShouldBeIgnored() {
+ assumeFalse(correctConfig.getAsJsonObject("config").get("security.enableDmaapCertAuth").getAsBoolean());
+
+ MessageRouterPublisherConfig messageRouterPublisherConfig = consulConfigurationParser.getMessageRouterPublisherConfig();
+
+ assertThat(messageRouterPublisherConfig.securityKeys()).isNull();
+ }
+
+ @Test
+ void whenDmaapCertAuthIsDisabled_MessageRouterSubscriberConfigSecurityKeysShouldBeIgnored() {
+ assumeFalse(correctConfig.getAsJsonObject("config").get("security.enableDmaapCertAuth").getAsBoolean());
+
+ MessageRouterSubscriberConfig messageRouterSubscriberConfig = consulConfigurationParser.getMessageRouterSubscriberConfig();
+
+ assertThat(messageRouterSubscriberConfig.securityKeys()).isNull();
+ }
+
+
+ @Test
+ void whenDmaapCertAuthIsEnabled_MessageRouterPublisherConfigSecurityKeysShouldBeLoaded() {
+ CbsContentParser consulConfigurationParser = new CbsContentParser(getConfigWithSslEnabled(correctJson));
+
+ MessageRouterPublisherConfig messageRouterPublisherConfig = consulConfigurationParser.getMessageRouterPublisherConfig();
+
+ verifySecurityKeys(messageRouterPublisherConfig.securityKeys());
+ }
+
+
+ @Test
+ void whenDmaapCertAuthIsEnabled_MessageRouterSubscriberConfigSecurityKeysShouldBeLoaded() {
+ CbsContentParser consulConfigurationParser = new CbsContentParser(getConfigWithSslEnabled(correctJson));
+
+ MessageRouterSubscriberConfig messageRouterSubscriberConfig = consulConfigurationParser.getMessageRouterSubscriberConfig();
+
+ verifySecurityKeys(messageRouterSubscriberConfig.securityKeys());
+ }
+
+ private static void verifySecurityKeys(@Nullable SecurityKeys securityKeys) {
+ assertThat(securityKeys).isNotNull();
+ assertThat(securityKeys.trustStore().path().endsWith("org.onap.dcae.trust.jks")).isTrue();
+ assertThat(securityKeys.keyStore().path().endsWith("org.onap.dcae.jks")).isTrue();
+ securityKeys.trustStorePassword().use(chars -> assertThat(new String(chars)).isEqualTo("*TQH?Lnszprs4LmlAj38yds("));
+ securityKeys.keyStorePassword().use(chars -> assertThat(new String(chars)).isEqualTo("mYHC98!qX}7h?W}jRv}MIXTJ"));
+ }
+
+ private static JsonObject getConfigWithSslEnabled(String configJsonString) {
+ JsonObject configJson = new Gson().fromJson(configJsonString, JsonObject.class);
+ JsonObject config = configJson.getAsJsonObject("config");
+ config.addProperty("security.enableDmaapCertAuth", true);
+ config.addProperty("security.enableAaiCertAuth", true);
+ config.addProperty("security.trustStorePath", testResourceToPath("/org.onap.dcae.trust.jks"));
+ config.addProperty("security.trustStorePasswordPath", testResourceToPath("/truststore.password"));
+ config.addProperty("security.keyStorePath", testResourceToPath("/org.onap.dcae.jks"));
+ config.addProperty("security.keyStorePasswordPath", testResourceToPath("/keystore.password"));
+ return configJson;
+ }
+
+
+ private static String testResourceToPath(String resource) {
+ try {
+ return Paths.get(ConsulConfigurationParserTest.class.getResource(resource).toURI()).toString();
+ } catch (URISyntaxException e) {
+ throw new RuntimeException("Failed resolving test resource path", e);
+ }
+ }
+
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/PrhAppConfigTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/PrhAppConfigTest.java
deleted file mode 100644
index 42acc592..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/configuration/PrhAppConfigTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PNF-REGISTRATION-HANDLER
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.configuration;
-
-import static java.lang.ClassLoader.getSystemResource;
-import static java.nio.file.Files.readAllBytes;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Paths;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.onap.dcaegen2.services.prh.integration.junit5.mockito.MockitoExtension;
-import org.springframework.core.io.InputStreamResource;
-import org.springframework.core.io.Resource;
-
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/9/18
- */
-@ExtendWith({MockitoExtension.class})
-class PrhAppConfigTest {
-
- private static final String CORRECT_CONFIG_FILE = "correct_config.json";
- private static final String INCORRECT_CONFIG_FILE = "incorrect_config.json";
- private static final String NOT_JSON_OBJECT_FILE = "not_json_object.json";
- private AppConfig appConfig;
-
- @BeforeEach
- void setUp() {
- appConfig = new AppConfig();
- }
-
- @Test
- void whenTheConfigurationFits() throws Exception {
- InputStream inputStream = createInputStream(CORRECT_CONFIG_FILE);
- appConfig.setResourceFile(new InputStreamResource(inputStream));
- appConfig.initFileStreamReader();
-
- assertNotNull(appConfig.getDmaapConsumerConfiguration());
- assertNotNull(appConfig.getDmaapPublisherConfiguration());
- assertNotNull(appConfig.getAaiClientConfiguration());
- }
-
- @Test
- void whenFileDoesNotExist() throws Exception {
- InputStream inputStream = createInputStream(CORRECT_CONFIG_FILE);
- Resource resource = spy(new InputStreamResource(inputStream));
- when(resource.getInputStream()).thenThrow(new IOException());
- appConfig.setResourceFile(resource);
- appConfig.initFileStreamReader();
-
- assertNull(appConfig.getAaiClientConfiguration());
- assertNull(appConfig.getDmaapConsumerConfiguration());
- assertNull(appConfig.getDmaapPublisherConfiguration());
- }
-
- @Test
- void whenFileExistsButDmaapPublisherJsonConfigurationIsIncorrect() throws Exception {
- InputStream inputStream = createInputStream(INCORRECT_CONFIG_FILE);
- appConfig.setResourceFile(new InputStreamResource(inputStream));
- appConfig.initFileStreamReader();
-
- assertNotNull(appConfig.getAaiClientConfiguration());
- assertNotNull(appConfig.getDmaapConsumerConfiguration());
- assertNull(appConfig.getDmaapPublisherConfiguration());
- }
-
- @Test
- void whenRootElementIsNotAJsonObject() throws Exception {
- InputStream inputStream = createInputStream(NOT_JSON_OBJECT_FILE);
- appConfig.setResourceFile(new InputStreamResource(inputStream));
- appConfig.initFileStreamReader();
-
-
- assertNull(appConfig.getAaiClientConfiguration());
- assertNull(appConfig.getDmaapConsumerConfiguration());
- assertNull(appConfig.getDmaapPublisherConfiguration());
- }
-
- private InputStream createInputStream(String jsonFile) throws Exception {
- return new ByteArrayInputStream(readAllBytes(Paths.get(getSystemResource(jsonFile).toURI())));
- }
-} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/AppInfoControllerTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/AppInfoControllerTest.java
new file mode 100644
index 00000000..1dba66a1
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/AppInfoControllerTest.java
@@ -0,0 +1,69 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.prh.controllers;
+
+import org.junit.jupiter.api.Test;
+import org.onap.dcaegen2.services.prh.configuration.PrhAppConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.http.MediaType;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.web.reactive.server.WebTestClient;
+
+import static org.mockito.Mockito.when;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@DirtiesContext
+class AppInfoControllerTest {
+
+ private static final String SAMPLE_GIT_INFO_CONTENT = "{ \"git.commit.id\" : \"37444e\" }";
+
+ @MockBean
+ private PrhAppConfig prhAppConfig;
+
+ @Autowired
+ private WebTestClient webTestClient;
+
+ @Test
+ void shouldProvideHeartbeatResponse() {
+ webTestClient
+ .get().uri("/heartbeat")
+ .accept(MediaType.TEXT_PLAIN)
+ .exchange()
+ .expectStatus().isOk()
+ .expectBody(String.class).isEqualTo("alive");
+ }
+
+
+ @Test
+ void shouldProvideVersionInfo() {
+ when(prhAppConfig.getGitInfo()).thenReturn(new ByteArrayResource(SAMPLE_GIT_INFO_CONTENT.getBytes()));
+
+ webTestClient
+ .get().uri("/version")
+ .accept(MediaType.APPLICATION_JSON)
+ .exchange()
+ .expectStatus().isOk()
+ .expectBody(String.class).isEqualTo(SAMPLE_GIT_INFO_CONTENT);
+ }
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/ScheduleControllerTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/ScheduleControllerTest.java
new file mode 100644
index 00000000..ebdec09e
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/controllers/ScheduleControllerTest.java
@@ -0,0 +1,75 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.prh.controllers;
+
+import org.junit.jupiter.api.Test;
+import org.onap.dcaegen2.services.prh.tasks.ScheduledTasksRunner;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.HttpStatus;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.web.reactive.server.WebTestClient;
+
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@DirtiesContext
+class ScheduleControllerTest {
+
+ @MockBean
+ private ScheduledTasksRunner scheduledTasksRunner;
+
+ @Autowired
+ private WebTestClient webTestClient;
+
+ @Test
+ void startEndpointShouldAllowStartingPrhTasks() {
+ when(scheduledTasksRunner.tryToStartTask()).thenReturn(true);
+ webTestClient
+ .get().uri("/start")
+ .exchange()
+ .expectStatus().isCreated()
+ .expectBody(String.class).isEqualTo("PRH Service has been started!");
+ }
+
+ @Test
+ void whenPrhTasksAreAlreadyStarted_shouldRespondThatRequestWasNotAccepted() {
+ when(scheduledTasksRunner.tryToStartTask()).thenReturn(false);
+ webTestClient
+ .get().uri("/start")
+ .exchange()
+ .expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE)
+ .expectBody(String.class).isEqualTo("PRH Service is already running!");
+ }
+
+ @Test
+ void stopEndpointShouldAllowStoppingPrhTasks() {
+ webTestClient
+ .get().uri("/stopPrh")
+ .exchange()
+ .expectStatus().isOk()
+ .expectBody(String.class).isEqualTo("PRH Service has been stopped!");
+
+ verify(scheduledTasksRunner).cancelTasks();
+ }
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/PrhWorkflowIntegrationTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/PrhWorkflowIntegrationTest.java
new file mode 100644
index 00000000..672cfc47
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/PrhWorkflowIntegrationTest.java
@@ -0,0 +1,124 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.prh.integration;
+
+import com.github.tomakehurst.wiremock.client.WireMock;
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.onap.dcaegen2.services.prh.MainApp;
+import org.onap.dcaegen2.services.prh.configuration.CbsConfiguration;
+import org.onap.dcaegen2.services.prh.tasks.ScheduledTasks;
+import org.onap.dcaegen2.services.prh.tasks.ScheduledTasksRunner;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.*;
+import static java.lang.ClassLoader.getSystemResource;
+import static java.util.Collections.singletonList;
+
+
+@SpringBootTest
+@AutoConfigureWireMock(port = 0)
+class PrhWorkflowIntegrationTest {
+
+ @Autowired
+ private ScheduledTasks scheduledTasks;
+
+ @MockBean
+ private ScheduledTasksRunner scheduledTasksRunner; // just to disable scheduling - some configurability in ScheduledTaskRunner not to start tasks at app startup would be welcome
+
+
+ @Configuration
+ @Import(MainApp.class)
+ static class CbsConfigTestConfig {
+
+ @Value("http://localhost:${wiremock.server.port}")
+ private String wiremockServerAddress;
+
+ @Bean
+ public CbsConfiguration cbsConfiguration() {
+ JsonObject cbsConfigJson = new Gson().fromJson(getResourceContent("configurationFromCbs.json")
+ .replaceAll("https?://dmaap-mr[\\w.]*:\\d+", wiremockServerAddress)
+ .replaceAll("https?://aai[\\w.]*:\\d+", wiremockServerAddress),
+ JsonObject.class);
+
+ CbsConfiguration cbsConfiguration = new CbsConfiguration();
+ cbsConfiguration.parseCBSConfig(cbsConfigJson);
+ return cbsConfiguration;
+ }
+ }
+
+ @BeforeEach
+ void resetWireMock() {
+ WireMock.reset();
+ }
+
+
+ @Test
+ void whenThereAreNoEventsInDmaap_WorkflowShouldFinish() {
+ stubFor(get(urlEqualTo("/events/unauthenticated.VES_PNFREG_OUTPUT/OpenDCAE-c12/c12"))
+ .willReturn(aResponse().withBody("[]")));
+
+ scheduledTasks.scheduleMainPrhEventTask();
+
+ verify(0, anyRequestedFor(urlPathMatching("/aai.*")));
+ verify(0, postRequestedFor(urlPathMatching("/events.*")));
+ }
+
+
+ @Test
+ void whenThereIsAnEventsInDmaap_ShouldSendPnfReadyNotification() {
+ String event = getResourceContent("integration/event.json");
+ String pnfName = JsonPath.read(event, "$.event.commonEventHeader.sourceName");
+
+ stubFor(get(urlEqualTo("/events/unauthenticated.VES_PNFREG_OUTPUT/OpenDCAE-c12/c12"))
+ .willReturn(ok().withBody(new Gson().toJson(singletonList(event)))));
+ stubFor(get(urlEqualTo("/aai/v12/network/pnfs/pnf/" + pnfName)).willReturn(ok().withBody("{}")));
+ stubFor(patch(urlEqualTo("/aai/v12/network/pnfs/pnf/" + pnfName)));
+ stubFor(post(urlEqualTo("/events/unauthenticated.PNF_READY")));
+
+ scheduledTasks.scheduleMainPrhEventTask();
+
+ verify(1, postRequestedFor(urlEqualTo("/events/unauthenticated.PNF_READY"))
+ .withRequestBody(matchingJsonPath("$[0].correlationId", equalTo(pnfName))));
+ }
+
+
+ private static String getResourceContent(String resourceName) {
+ try {
+ return new String(Files.readAllBytes(Paths.get(getSystemResource(resourceName).toURI())));
+ } catch (Exception e) {
+ throw new RuntimeException("failed loading content of '" + resourceName + "'", e);
+ }
+ }
+}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/ServiceMockProvider.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/PrhWorkflowSchedulingIntegrationTest.java
index 2660e3e5..44dcabfa 100644
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/ServiceMockProvider.java
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/PrhWorkflowSchedulingIntegrationTest.java
@@ -1,8 +1,8 @@
/*
* ============LICENSE_START=======================================================
- * PROJECT
+ * PNF-REGISTRATION-HANDLER
* ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved.
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.
@@ -20,26 +20,22 @@
package org.onap.dcaegen2.services.prh.integration;
-import static org.mockito.Mockito.mock;
+import org.junit.jupiter.api.Test;
+import org.onap.dcaegen2.services.prh.tasks.ScheduledTasks;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
-import org.onap.dcaegen2.services.prh.configuration.PrhAppConfig;
-import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
+import static org.mockito.Mockito.verify;
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/10/18
- */
-@Configuration
-class ServiceMockProvider {
- @Bean
- public PrhAppConfig getPrhAppConfig() {
- return mock(PrhAppConfig.class);
- }
+@SpringBootTest
+class PrhWorkflowSchedulingIntegrationTest {
+
+ @MockBean
+ private ScheduledTasks scheduledTasks;
- @Bean
- public ConsumerDmaapModel getRequestDetails() {
- return mock(ConsumerDmaapModel.class);
+ @Test
+ void prhWorkflowShouldBeExecutedRightAfterApplicationStart() {
+ verify(scheduledTasks).scheduleMainPrhEventTask();
}
-}
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/ScheduledXmlContextITest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/ScheduledXmlContextITest.java
deleted file mode 100644
index 934f572f..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/ScheduledXmlContextITest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.integration;
-
-import static org.mockito.Mockito.atLeast;
-import static org.mockito.Mockito.verify;
-
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.onap.dcaegen2.services.prh.integration.junit5.mockito.MockitoExtension;
-import org.onap.dcaegen2.services.prh.tasks.ScheduledTasks;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit.jupiter.SpringExtension;
-import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 3/27/18
- */
-@Configuration
-@ComponentScan("org.onap.dcaegen2.services.sdk.rest.services.cbs.client.providers")
-@ExtendWith({MockitoExtension.class, SpringExtension.class})
-@ContextConfiguration(locations = "classpath:scheduled-context.xml")
-class ScheduledXmlContextITest extends AbstractTestNGSpringContextTests {
-
- private static final int WAIT_FOR_SCHEDULING = 1;
-
- @Autowired
- private ScheduledTasks scheduledTask;
-
- @Test
- void testScheduling() {
- final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
- executorService.scheduleWithFixedDelay(this::verifyDmaapConsumerTask, 0, WAIT_FOR_SCHEDULING, TimeUnit.SECONDS);
- }
-
- private void verifyDmaapConsumerTask() {
- verify(scheduledTask, atLeast(1)).scheduleMainPrhEventTask();
- }
-}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/junit5/mockito/MockitoExtension.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/junit5/mockito/MockitoExtension.java
deleted file mode 100644
index af9c2b44..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/integration/junit5/mockito/MockitoExtension.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.integration.junit5.mockito;
-
-import static org.mockito.Mockito.mock;
-
-import java.lang.reflect.Parameter;
-import org.junit.jupiter.api.extension.ExtensionContext;
-import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
-import org.junit.jupiter.api.extension.ExtensionContext.Store;
-import org.junit.jupiter.api.extension.ParameterContext;
-import org.junit.jupiter.api.extension.ParameterResolver;
-import org.junit.jupiter.api.extension.TestInstancePostProcessor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 3/27/18
- *
- * {@code MockitoExtension } showcases the {@link TestInstancePostProcessor} and {@link ParameterResolver}
- * extension APIs of JUnit 5 by providing dependency injection support at the field level and at the method
- * parameter level viaMockito 2.x's {@link Mock @Mock} annotation.
- */
-public class MockitoExtension implements TestInstancePostProcessor, ParameterResolver {
-
- @Override
- public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
- MockitoAnnotations.initMocks(testInstance);
- }
-
- @Override
- public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
- return parameterContext.getParameter().isAnnotationPresent(Mock.class);
- }
-
- @Override
- public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
- return getMock(parameterContext.getParameter(), extensionContext);
- }
-
- private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
- Class<?> mockType = parameter.getType();
- Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType));
- String mockName = getMockName(parameter);
-
- if (mockName != null) {
- return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName));
- } else {
- return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType));
- }
- }
-
- private String getMockName(Parameter parameter) {
- String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
- if (!explicitMockName.isEmpty()) {
- return explicitMockName;
- } else if (parameter.isNamePresent()) {
- return parameter.getName();
- }
- return null;
- }
-
-
-}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/DmaapConsumerJsonParserTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/DmaapConsumerJsonParserTest.java
index 01ce7419..342460e3 100644
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/DmaapConsumerJsonParserTest.java
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/DmaapConsumerJsonParserTest.java
@@ -20,210 +20,300 @@
package org.onap.dcaegen2.services.prh.service;
-import static org.mockito.Mockito.spy;
-
import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-import java.util.Optional;
+import io.vavr.collection.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
import org.onap.dcaegen2.services.prh.model.ImmutableConsumerDmaapModel;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterSubscribeResponse;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterSubscribeResponse;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
+import java.util.Optional;
+
+import static org.mockito.Mockito.spy;
+
/**
* @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/8/18
*/
class DmaapConsumerJsonParserTest {
+ private JsonParser jsonParser = new JsonParser();
+
@Test
void whenPassingCorrectJson_validationNotThrowingAnException() {
//given
- String message = "[{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ String message = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
+ " \"oamV4IpAddress\": \"10.16.123.234\","
+ " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
- + "}}}]";
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {\"attachmentPoint\":\"bla-bla-30-3\",\"cvlan\":\"678\",\"svlan\":\"1005\"}"
+ + "}}}";
String parsed = "{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
+ " \"oamV4IpAddress\": \"10.16.123.234\","
+ " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {\"attachmentPoint\":\"bla-bla-30-3\",\"cvlan\":\"678\",\"svlan\":\"1005\"}"
+ "}}}";
- ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234")
+ JsonObject jsonObject = new JsonParser().parse("{\n"
+ + " \"attachmentPoint\": \"bla-bla-30-3\",\n"
+ + " \"cvlan\": \"678\",\n"
+ + " \"svlan\": \"1005\"\n"
+ + " }").getAsJsonObject();
+
+ ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder()
+ .ipv4("10.16.123.234")
.ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
- .correlationId("NOKQTFCOC540002E").build();
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .additionalFields(jsonObject)
+ .build();
+
+ List<JsonElement> messageAsJsonElementList = List.of(message).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(messageAsJsonElementList).build();
+
//when
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
- JsonElement jsonElement = new JsonParser().parse(parsed);
+ JsonElement jsonElement = jsonParser.parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
+
ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser
- .getJsonObject(Mono.just((message))).blockFirst();
+ .getJsonObject(Mono.just((response))).blockFirst();
//then
Assertions.assertNotNull(consumerDmaapModel);
Assertions.assertEquals(expectedObject, consumerDmaapModel);
}
@Test
- void whenPassingCorrectJsonWithoutIpv4_validationNotThrowingAnException() {
+ void whenPassingJsonWithoutAdditionalFields_validationNotThrowingAnException() {
//given
- String message = "[{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ String message = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
- + "}}}]";
+ + " \"oamV4IpAddress\": \"10.16.123.234\","
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"softwareVersion\": \"v4.5.0.1\""
+ + "}}}";
String parsed = "{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
+ + " \"oamV4IpAddress\": \"10.16.123.234\","
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"softwareVersion\": \"v4.5.0.1\""
+ "}}}";
+ ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder()
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .ipv4("10.16.123.234")
+ .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .build();
+ List<JsonElement> messageAsJsonElementList = List.of(message).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(messageAsJsonElementList).build();
//when
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
JsonElement jsonElement = new JsonParser().parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
- dmaapConsumerJsonParser.getJsonObject(Mono.just((message)));
- ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser.getJsonObject(Mono.just((message)))
- .blockFirst();
+ ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser
+ .getJsonObject(Mono.just((response))).blockFirst();
//then
- ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder().ipv4("")
- .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
- .correlationId("NOKQTFCOC540002E").build();
Assertions.assertNotNull(consumerDmaapModel);
Assertions.assertEquals(expectedObject, consumerDmaapModel);
}
@Test
- void whenPassingCorrectJsonWithoutIpv6_validationNotThrowingAnException() {
+ void whenPassingJsonWithEmptyAdditionalFields_validationNotThrowingAnException() {
//given
- String message = "[{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ String message = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ " \"oamV4IpAddress\": \"10.16.123.234\","
- + " \"softwareVersion\": \"v4.5.0.1\""
- + "}}}]";
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ + "}}}";
String parsed = "{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ " \"oamV4IpAddress\": \"10.16.123.234\","
- + " \"softwareVersion\": \"v4.5.0.1\""
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ "}}}";
- ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234").ipv6("")
- .correlationId("NOKQTFCOC540002E").build();
+ ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder()
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .ipv4("10.16.123.234")
+ .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .additionalFields(new JsonObject())
+ .build();
+
+ List<JsonElement> messageAsJsonElementList = List.of(message).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(messageAsJsonElementList).build();
+
//when
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
- JsonElement jsonElement = new JsonParser().parse(parsed);
+ JsonElement jsonElement = jsonParser.parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
- ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser.getJsonObject(Mono.just((message)))
- .blockFirst();
+
+ ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser
+ .getJsonObject(Mono.just((response))).blockFirst();
//then
Assertions.assertNotNull(consumerDmaapModel);
Assertions.assertEquals(expectedObject, consumerDmaapModel);
}
@Test
- void whenPassingCorrectJsonWithoutIpv4andIpv6_validationAddingAnException() {
+ void whenPassingCorrectJsonWithoutIpv4andIpv6_validationNotThrowingAnException() {
//given
- String message = "[{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ String message = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\""
- + "}}}]";
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ + " \"additionalFields\": {}"
+ + "}}}";
String parsed = "{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\""
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ + " \"additionalFields\": {}"
+ "}}}";
+ ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder()
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .ipv4("")
+ .ipv6("")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .additionalFields(new JsonObject())
+ .build();
+
+ List<JsonElement> messageAsJsonElementList = List.of(message).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(messageAsJsonElementList).build();
+
+ //when
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
- JsonElement jsonElement = new JsonParser().parse(parsed);
+ JsonElement jsonElement = jsonParser.parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
- StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(message)))
- .expectSubscription().thenRequest(1).verifyComplete();
+ ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser
+ .getJsonObject(Mono.just((response))).blockFirst();
+ //then
+ Assertions.assertNotNull(consumerDmaapModel);
+ Assertions.assertEquals(expectedObject, consumerDmaapModel);
}
+
@Test
void whenPassingJsonWithoutMandatoryHeaderInformation_validationAddingAnException() {
String parsed = "{\"event\": {"
@@ -237,14 +327,17 @@ class DmaapConsumerJsonParserTest {
+ " \"lastServiceDate\": \"1535014037024\","
+ " \"unitFamily\": \"BBU\","
+ " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\""
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ + " \"oamV4IpAddress\": \"10.16.123.234\","
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ "}}}";
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
- JsonElement jsonElement = new JsonParser().parse(parsed);
+ JsonElement jsonElement = jsonParser.parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
- String incorrectMessage = "[{\"event\": {"
+ String incorrectMessage = "{\"event\": {"
+ "\"commonEventHeader\": {},"
+ "\"pnfRegistrationFields\": {"
+ " \"unitType\": \"AirScale\","
@@ -255,9 +348,16 @@ class DmaapConsumerJsonParserTest {
+ " \"lastServiceDate\": \"1535014037024\","
+ " \"unitFamily\": \"BBU\","
+ " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\""
- + "}}}]";
- StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(incorrectMessage)))
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ + " \"oamV4IpAddress\": \"10.16.123.234\","
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ + "}}}";
+
+ List<JsonElement> incorrectMessageAsJsonElementList = List.of(incorrectMessage).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(incorrectMessageAsJsonElementList).build();
+
+ StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(response)))
.expectSubscription().thenRequest(1).verifyComplete();
}
@@ -275,15 +375,16 @@ class DmaapConsumerJsonParserTest {
+ " \"unitFamily\": \"BBU\","
+ " \"vendorName\": \"Nokia\","
+ " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ "}}}";
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
- JsonElement jsonElement = new JsonParser().parse(parsed);
+ JsonElement jsonElement = jsonParser.parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
String jsonWithoutSourceName =
- "[{\"event\": {"
+ "{\"event\": {"
+ "\"commonEventHeader\": {},"
+ "\"pnfRegistrationFields\": {"
+ " \"unitType\": \"AirScale\","
@@ -295,19 +396,24 @@ class DmaapConsumerJsonParserTest {
+ " \"unitFamily\": \"BBU\","
+ " \"vendorName\": \"Nokia\","
+ " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
- + "}}}]";
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ + "}}}";
+
+ List<JsonElement> jsonWithoutSourceNameAsJsonElementList = List.of(jsonWithoutSourceName).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(jsonWithoutSourceNameAsJsonElementList).build();
StepVerifier
- .create(dmaapConsumerJsonParser.getJsonObject(Mono.just(jsonWithoutSourceName)))
+ .create(dmaapConsumerJsonParser.getJsonObject(Mono.just(response)))
.expectSubscription().thenRequest(1)
.verifyComplete();
+
}
@Test
- void whenPassingJsonWithoutIpInformation_validationAddingAnException() {
+ void whenPassingJsonWithoutSourceNameValue_validationAddingAnException() {
String parsed =
"{\"event\": {"
- + "\"commonEventHeader\": {\"sourceName\": \"NOKQTFCOC540002E\"},"
+ + "\"commonEventHeader\": {\"sourceName\": \"\"},"
+ "\"pnfRegistrationFields\": {"
+ " \"unitType\": \"AirScale\","
+ " \"serialNumber\": \"QTFCOC540002E\","
@@ -318,37 +424,16 @@ class DmaapConsumerJsonParserTest {
+ " \"unitFamily\": \"BBU\","
+ " \"vendorName\": \"Nokia\","
+ " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV4IpAddress\": \"\","
- + " \"oamV6IpAddress\": \"\""
+ + " \"oamV4IpAddress\": \"10.16.123.234\","
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ "}}}";
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
- JsonElement jsonElement = new JsonParser().parse(parsed);
+ JsonElement jsonElement = jsonParser.parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
String jsonWithoutIpInformation =
- "[{\"event\": {"
- + "\"commonEventHeader\": {\"sourceName\": \"NOKQTFCOC540002E\"},"
- + "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
- + " \"serialNumber\": \"QTFCOC540002E\","
- + " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
- + " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV4IpAddress\": \"\","
- + " \"oamV6IpAddress\": \"\""
- + "}}}]";
- StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(jsonWithoutIpInformation)))
- .expectSubscription().thenRequest(1).verifyComplete();
- }
-
- @Test
- void whenPassingJsonWithoutSourceNameValue_validationAddingAnException() {
- String parsed =
"{\"event\": {"
+ "\"commonEventHeader\": {\"sourceName\": \"\"},"
+ "\"pnfRegistrationFields\": {"
@@ -362,76 +447,204 @@ class DmaapConsumerJsonParserTest {
+ " \"vendorName\": \"Nokia\","
+ " \"softwareVersion\": \"v4.5.0.1\","
+ " \"oamV4IpAddress\": \"10.16.123.234\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ "}}}";
+ List<JsonElement> jsonWithoutIpInformationAsJsonElementList = List.of(jsonWithoutIpInformation).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(jsonWithoutIpInformationAsJsonElementList).build();
+
+ StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(response)))
+ .expectSubscription().thenRequest(1).verifyComplete();
+ }
+
+ @Test
+ void whenPassingCorrectJsonWithoutIpv4_validationNotThrowingAnException() {
+ //given
+ String message = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ + "\"pnfRegistrationFields\": {"
+ + " \"vendorName\": \"nokia\","
+ + " \"serialNumber\": \"QTFCOC540002E\","
+ + " \"pnfRegistrationFieldsVersion\": \"2.0\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ + " \"unitFamily\": \"BBU\","
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
+ + "}}}";
+
+ String parsed = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ + "\"pnfRegistrationFields\": {"
+ + " \"vendorName\": \"nokia\","
+ + " \"serialNumber\": \"QTFCOC540002E\","
+ + " \"pnfRegistrationFieldsVersion\": \"2.0\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ + " \"unitFamily\": \"BBU\","
+ + " \"softwareVersion\": \"v4.5.0.1\","
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
+ + "}}}";
+
+ List<JsonElement> messageAsJsonElementList = List.of(message).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(messageAsJsonElementList).build();
+ //when
DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
- JsonElement jsonElement = new JsonParser().parse(parsed);
+ JsonElement jsonElement = jsonParser.parse(parsed);
Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
.when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
- String jsonWithoutIpInformation =
- "[{\"event\": {"
- + "\"commonEventHeader\": {\"sourceName\": \"\"},"
- + "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
- + " \"serialNumber\": \"QTFCOC540002E\","
- + " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
- + " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV4IpAddress\": \"10.16.123.234\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
- + "}}}]";
- StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(jsonWithoutIpInformation)))
- .expectSubscription().thenRequest(1).verifyComplete();
+
+ dmaapConsumerJsonParser.getJsonObject(Mono.just((response)));
+ ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser.getJsonObject(Mono.just(response))
+ .blockFirst();
+ //then
+ ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder()
+ .ipv4("")
+ .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .build();
+ Assertions.assertNotNull(consumerDmaapModel);
+ Assertions.assertEquals(expectedObject, consumerDmaapModel);
+
}
@Test
- void whenPassingCorrectJsoArraynWithoutIpv4_validationNotThrowingAnException() {
+ void whenPassingCorrectJsonWithoutIpv6_validationNotThrowingAnException() {
//given
- String message = "[{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ String message = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
+ " \"oamV4IpAddress\": \"10.16.123.234\","
+ + " \"softwareVersion\": \"v4.5.0.1\""
+ + "}}}";
+
+ String parsed = "{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ + "\"pnfRegistrationFields\": {"
+ + " \"vendorName\": \"nokia\","
+ + " \"serialNumber\": \"QTFCOC540002E\","
+ + " \"pnfRegistrationFieldsVersion\": \"2.0\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ + " \"unitFamily\": \"BBU\","
+ + " \"oamV4IpAddress\": \"10.16.123.234\","
+ + " \"softwareVersion\": \"v4.5.0.1\""
+ + "}}}";
+
+ ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder()
+ .ipv4("10.16.123.234")
+ .ipv6("")
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .build();
+
+ List<JsonElement> messageAsJsonElementList = List.of(message).map(jsonParser::parse);
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(messageAsJsonElementList).build();
+
+ //when
+ DmaapConsumerJsonParser dmaapConsumerJsonParser = spy(new DmaapConsumerJsonParser());
+ JsonElement jsonElement = jsonParser.parse(parsed);
+ Mockito.doReturn(Optional.of(jsonElement.getAsJsonObject()))
+ .when(dmaapConsumerJsonParser).getJsonObjectFromAnArray(jsonElement);
+ ConsumerDmaapModel consumerDmaapModel = dmaapConsumerJsonParser.getJsonObject(Mono.just(response))
+ .blockFirst();
+
+ //then
+ Assertions.assertNotNull(consumerDmaapModel);
+ Assertions.assertEquals(expectedObject, consumerDmaapModel);
+
+ }
+
+ @Test
+ void whenPassingCorrectJsonArrayWithoutIpv4_validationNotThrowingAnException() {
+ //given
+ String message = "[{\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + " },"
+ + "\"pnfRegistrationFields\": {"
+ + " \"vendorName\": \"nokia\","
+ + " \"serialNumber\": \"QTFCOC540002E\","
+ + " \"pnfRegistrationFieldsVersion\": \"2.0\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ + " \"unitFamily\": \"BBU\","
+ " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ "}}},"
- + "{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
+ + " {\"event\": {"
+ + "\"commonEventHeader\": { "
+ + " \"sourceName\":\"NOKQTFCOC540002E\","
+ + " \"nfNamingCode\":\"gNB\" "
+ + "},"
+ "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
+ + " \"vendorName\": \"nokia\","
+ " \"serialNumber\": \"QTFCOC540002E\","
+ " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
+ + " \"modelNumber\": \"3310\","
+ + " \"unitType\": \"type\",\n"
+ " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"oamV4IpAddress\": \"10.16.123.234\","
+ " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
- + "}}}"
- + "]";
+ + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\","
+ + " \"additionalFields\": {}"
+ + "}}}]";
- ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234")
+ ConsumerDmaapModel expectedObject = ImmutableConsumerDmaapModel.builder()
+ .ipv4("")
.ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
- .correlationId("NOKQTFCOC540002E").build();
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .additionalFields(new JsonObject())
+ .build();
+
+ List<JsonElement> messageAsJsonElementList = List.empty();
+ for(JsonElement el : jsonParser.parse(message).getAsJsonArray()) {
+ messageAsJsonElementList = messageAsJsonElementList.append(el);
+ }
+
+ MessageRouterSubscribeResponse response = ImmutableMessageRouterSubscribeResponse.builder().items(messageAsJsonElementList).build();
+
//when
DmaapConsumerJsonParser dmaapConsumerJsonParser = new DmaapConsumerJsonParser();
//then
- StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(message)))
- .expectSubscription().expectNext(expectedObject).expectNext(expectedObject).verifyComplete();
+ StepVerifier.create(dmaapConsumerJsonParser.getJsonObject(Mono.just(response))).expectSubscription().expectNext(expectedObject).expectNext(expectedObject).verifyComplete();
}
}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImplTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImplTest.java
index 32e66386..0077a6a6 100644
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImplTest.java
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImplTest.java
@@ -20,34 +20,28 @@
package org.onap.dcaegen2.services.prh.tasks;
-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.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-
-import javax.net.ssl.SSLException;
+import com.google.gson.JsonObject;
+import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.onap.dcaegen2.services.prh.TestAppConfiguration;
-import org.onap.dcaegen2.services.prh.configuration.AppConfig;
+import org.onap.dcaegen2.services.prh.configuration.CbsConfiguration;
import org.onap.dcaegen2.services.prh.exceptions.PrhTaskException;
import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
import org.onap.dcaegen2.services.prh.model.ImmutableConsumerDmaapModel;
import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.AaiClientConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.aai.client.service.http.patch.AaiReactiveHttpPatchClient;
-
-import org.springframework.http.HttpStatus;
-import org.springframework.web.reactive.function.client.ClientResponse;
+import org.onap.dcaegen2.services.sdk.rest.services.aai.client.service.http.patch.AaiHttpPatchClient;
+import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpResponse;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
+import javax.net.ssl.SSLException;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
/**
* @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/14/18
*/
@@ -56,26 +50,35 @@ class AaiProducerTaskImplTest {
private ConsumerDmaapModel consumerDmaapModel;
private AaiProducerTaskImpl aaiProducerTask;
private AaiClientConfiguration aaiClientConfiguration;
- private AaiReactiveHttpPatchClient aaiReactiveHttpPatchClient;
- private AppConfig appConfig;
- private ClientResponse clientResponse;
+ private AaiHttpPatchClient aaiReactiveHttpPatchClient;
+ private CbsConfiguration cbsConfiguration;
+ private HttpResponse clientResponse;
@BeforeEach
void setUp() {
- clientResponse = mock(ClientResponse.class);
+ clientResponse = mock(HttpResponse.class);
aaiClientConfiguration = TestAppConfiguration.createDefaultAaiClientConfiguration();
- consumerDmaapModel = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234")
- .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
- .correlationId("NOKQTFCOC540002E").build();
- appConfig = mock(AppConfig.class);
+ consumerDmaapModel = ImmutableConsumerDmaapModel.builder()
+ .ipv4("10.16.123.234")
+ .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("role")
+ .swVersion("v4.5.0.1")
+ .additionalFields(new JsonObject())
+ .build();
+ cbsConfiguration = mock(CbsConfiguration.class);
}
@Test
void whenPassedObjectDoesntFit_ThrowsPrhTaskException() {
//given/when/
- when(appConfig.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration);
- aaiProducerTask = new AaiProducerTaskImpl(appConfig);
+ when(cbsConfiguration.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration);
+ aaiProducerTask = new AaiProducerTaskImpl(aaiReactiveHttpPatchClient);
Executable executableCode = () -> aaiProducerTask.execute(null);
//then
@@ -86,11 +89,11 @@ class AaiProducerTaskImplTest {
@Test
void whenPassedObjectFits_ReturnsCorrectStatus() throws PrhTaskException, SSLException {
//given/when
- getAaiProducerTask_whenMockingResponseObject(200);
+ getAaiProducerTask_whenMockingResponseObject(HttpResponseStatus.OK);
Mono<ConsumerDmaapModel> response = aaiProducerTask.execute(consumerDmaapModel);
//then
- verify(aaiReactiveHttpPatchClient, times(1)).getAaiProducerResponse(any());
+ verify(aaiReactiveHttpPatchClient, times(1)).getAaiResponse(any());
verifyNoMoreInteractions(aaiReactiveHttpPatchClient);
Assertions.assertEquals(consumerDmaapModel, response.block());
@@ -99,24 +102,22 @@ class AaiProducerTaskImplTest {
@Test
void whenPassedObjectFits_butIncorrectResponseReturns() throws PrhTaskException, SSLException {
//given/when
- getAaiProducerTask_whenMockingResponseObject(400);
+ getAaiProducerTask_whenMockingResponseObject(HttpResponseStatus.BAD_REQUEST);
StepVerifier.create(aaiProducerTask.execute(consumerDmaapModel)).expectSubscription()
.expectError(PrhTaskException.class).verify();
//then
- verify(aaiReactiveHttpPatchClient, times(1)).getAaiProducerResponse(any());
+ verify(aaiReactiveHttpPatchClient, times(1)).getAaiResponse(any());
verifyNoMoreInteractions(aaiReactiveHttpPatchClient);
}
- private void getAaiProducerTask_whenMockingResponseObject(int statusCode) throws SSLException {
+ private void getAaiProducerTask_whenMockingResponseObject(HttpResponseStatus httpResponseStatus) throws SSLException {
//given
- doReturn(HttpStatus.valueOf(statusCode)).when(clientResponse).statusCode();
- Mono<ClientResponse> clientResponseMono = Mono.just(clientResponse);
- aaiReactiveHttpPatchClient = mock(AaiReactiveHttpPatchClient.class);
- when(aaiReactiveHttpPatchClient.getAaiProducerResponse(any()))
+ doReturn(httpResponseStatus.code()).when(clientResponse).statusCode();
+ Mono<HttpResponse> clientResponseMono = Mono.just(clientResponse);
+ aaiReactiveHttpPatchClient = mock(AaiHttpPatchClient.class);
+ when(aaiReactiveHttpPatchClient.getAaiResponse(any()))
.thenReturn(clientResponseMono);
- when(appConfig.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration);
- aaiProducerTask = spy(new AaiProducerTaskImpl(appConfig));
- when(aaiProducerTask.resolveConfiguration()).thenReturn(aaiClientConfiguration);
- doReturn(aaiReactiveHttpPatchClient).when(aaiProducerTask).resolveClient();
+ when(cbsConfiguration.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration);
+ aaiProducerTask = spy(new AaiProducerTaskImpl(aaiReactiveHttpPatchClient));
}
} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiPublisherTaskSpy.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiPublisherTaskSpy.java
deleted file mode 100644
index a63910c0..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiPublisherTaskSpy.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
-
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-
-import javax.net.ssl.SSLException;
-import org.onap.dcaegen2.services.prh.configuration.AppConfig;
-import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
-import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.AaiClientConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.aai.client.service.http.patch.AaiReactiveHttpPatchClient;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
-
-
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/13/18
- */
-@Configuration
-public class AaiPublisherTaskSpy {
-
- /**
- * Mocking bean for tests.
- *
- * @return A&AI ProducerTask spy
- */
- @Bean
- @Primary
- public AaiProducerTask registerSimpleAaiPublisherTask() throws SSLException {
- AppConfig appConfig = spy(AppConfig.class);
- ConsumerDmaapModel consumerDmaapModel = spy(ConsumerDmaapModel.class);
- doReturn(mock(AaiClientConfiguration.class)).when(appConfig).getAaiClientConfiguration();
- AaiProducerTaskImpl aaiProducerTask = spy(new AaiProducerTaskImpl(appConfig));
- AaiReactiveHttpPatchClient aaiReactiveHttpPatchClient = mock(AaiReactiveHttpPatchClient.class);
- doReturn(mock(AaiClientConfiguration.class)).when(aaiProducerTask).resolveConfiguration();
- doReturn(aaiReactiveHttpPatchClient).when(aaiProducerTask).resolveClient();
- return aaiProducerTask;
- }
-}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiQueryTaskImplTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiQueryTaskImplTest.java
new file mode 100644
index 00000000..512d1eda
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/AaiQueryTaskImplTest.java
@@ -0,0 +1,206 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PROJECT
+ * ================================================================================
+ * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
+
+import org.assertj.core.util.Lists;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.onap.dcaegen2.services.prh.model.AaiPnfResultModel;
+import org.onap.dcaegen2.services.prh.model.AaiServiceInstanceResultModel;
+import org.onap.dcaegen2.services.prh.model.ImmutableRelationshipData;
+import org.onap.dcaegen2.services.prh.model.Relationship;
+import org.onap.dcaegen2.services.prh.model.RelationshipData;
+import org.onap.dcaegen2.services.prh.model.RelationshipDict;
+import org.onap.dcaegen2.services.sdk.rest.services.aai.client.service.http.AaiHttpClient;
+import org.onap.dcaegen2.services.sdk.rest.services.model.AaiModel;
+import org.onap.dcaegen2.services.sdk.rest.services.model.AaiServiceInstanceQueryModel;
+import reactor.core.publisher.Mono;
+
+import java.util.Collections;
+import java.util.List;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.BDDMockito.given;
+
+@ExtendWith(MockitoExtension.class)
+class AaiQueryTaskImplTest {
+ @Mock
+ private AaiHttpClient<AaiModel, AaiPnfResultModel> getPnfModelClient;
+
+ @Mock
+ private AaiHttpClient<AaiServiceInstanceQueryModel, AaiServiceInstanceResultModel> getServiceClient;
+
+ @Mock
+ private AaiPnfResultModel pnfResultModel;
+
+ @Mock
+ private Relationship pnfRelationships;
+
+ @Mock
+ private RelationshipDict pnfRelation;
+
+ @Mock
+ private AaiServiceInstanceResultModel serviceModel;
+
+ private List<RelationshipData> allRelationData;
+
+ private AaiQueryTask sut;
+
+ private final AaiModel aaiModel = () -> "SomePNF";
+
+ @BeforeEach
+ void setUp() {
+ allRelationData = Lists.list(
+ ImmutableRelationshipData.builder()
+ .relationshipKey(AaiQueryTaskImpl.CUSTOMER).relationshipValue("Foo").build(),
+ ImmutableRelationshipData.builder()
+ .relationshipKey(AaiQueryTaskImpl.SERVICE_TYPE).relationshipValue("Bar").build(),
+ ImmutableRelationshipData.builder()
+ .relationshipKey(AaiQueryTaskImpl.SERVICE_INSTANCE_ID).relationshipValue("Baz").build()
+ );
+
+ sut = new AaiQueryTaskImpl(getPnfModelClient, getServiceClient);
+ }
+
+ @Test
+ void whenPnfIsUnavailable_ShouldThrowException() {
+ //given
+ given(getPnfModelClient.getAaiResponse(aaiModel)).willReturn(Mono.error(new Exception("404")));
+
+ //when
+ final Mono<Boolean> task = sut.execute(aaiModel);
+
+ //then
+ Assertions.assertThrows(Exception.class, task::block);
+ }
+
+ @Test
+ void whenPnfIsAvailableButRelationshipIsNull_ShouldReturnFalse() {
+ //given
+ given(pnfResultModel.getRelationshipList()).willReturn(null);
+
+ configurePnfClient(aaiModel, pnfResultModel);
+
+ //when
+ final Mono<Boolean> task = sut.execute(aaiModel);
+
+ //then
+ Assertions.assertFalse(task::block);
+ }
+
+ @Test
+ void whenPnfIsAvailableButRelationshipIsEmpty_ShouldReturnFalse() {
+ //given
+ given(pnfRelationships.getRelationship()).willReturn(Collections.emptyList());
+ given(pnfResultModel.getRelationshipList()).willReturn(pnfRelationships);
+ configurePnfClient(aaiModel, pnfResultModel);
+
+ //when
+ final Mono<Boolean> task = sut.execute(aaiModel);
+
+ //then
+ Assertions.assertFalse(task::block);
+ }
+
+ @Test
+ void whenPnfIsAvailableButServiceRelationIsMissing_ShouldReturnFalse() {
+ //given
+ given(pnfRelation.getRelatedTo()).willReturn("some-other-relation");
+ given(pnfRelationships.getRelationship()).willReturn(Collections.singletonList(pnfRelation));
+ given(pnfResultModel.getRelationshipList()).willReturn(pnfRelationships);
+
+ configurePnfClient(aaiModel, pnfResultModel);
+
+ //when
+ final Mono<Boolean> task = sut.execute(aaiModel);
+
+ //then
+ Assertions.assertFalse(task::block);
+ }
+
+ @Test
+ void whenPnfIsAvailableButServiceRelationIsMissingRequiredKey_ShouldReturnFalse() {
+ //given
+ Collections.shuffle(allRelationData);
+ allRelationData.remove(0);
+
+ given(pnfRelation.getRelatedTo()).willReturn(AaiQueryTaskImpl.RELATED_TO);
+ given(pnfRelation.getRelationshipData()).willReturn(allRelationData);
+ given(pnfRelationships.getRelationship()).willReturn(Collections.singletonList(pnfRelation));
+ given(pnfResultModel.getRelationshipList()).willReturn(pnfRelationships);
+
+ configurePnfClient(aaiModel, pnfResultModel);
+
+ //when
+ final Mono<Boolean> task = sut.execute(aaiModel);
+
+ //then
+ Assertions.assertFalse(task::block);
+ }
+
+ @Test
+ void whenPnfIsAvailableAndServiceRelationIsCompleteButServiceIsInactive_ShouldReturnFalse() {
+ //given
+ given(serviceModel.getOrchestrationStatus()).willReturn("Inactive");
+ given(getServiceClient.getAaiResponse(any())).willReturn(Mono.just(serviceModel));
+
+ given(pnfRelation.getRelatedTo()).willReturn(AaiQueryTaskImpl.RELATED_TO);
+ given(pnfRelation.getRelationshipData()).willReturn(allRelationData);
+ given(pnfRelationships.getRelationship()).willReturn(Collections.singletonList(pnfRelation));
+ given(pnfResultModel.getRelationshipList()).willReturn(pnfRelationships);
+
+ configurePnfClient(aaiModel, pnfResultModel);
+
+ //when
+ final Mono<Boolean> task = sut.execute(aaiModel);
+
+ //then
+ Assertions.assertFalse(task::block);
+ }
+
+ @Test
+ void whenPnfIsAvailableAndServiceRelationIsCompleteButServiceIsActive_ShouldReturnFalse() {
+ //given
+ given(serviceModel.getOrchestrationStatus()).willReturn("Active");
+ given(getServiceClient.getAaiResponse(any())).willReturn(Mono.just(serviceModel));
+
+ given(pnfRelation.getRelatedTo()).willReturn(AaiQueryTaskImpl.RELATED_TO);
+ given(pnfRelation.getRelationshipData()).willReturn(allRelationData);
+ given(pnfRelationships.getRelationship()).willReturn(Collections.singletonList(pnfRelation));
+ given(pnfResultModel.getRelationshipList()).willReturn(pnfRelationships);
+
+ configurePnfClient(aaiModel, pnfResultModel);
+
+ //when
+ final Mono<Boolean> task = sut.execute(aaiModel);
+
+ //then
+ Assertions.assertTrue(task::block);
+ }
+
+ private void configurePnfClient(final AaiModel aaiModel, final AaiPnfResultModel pnfResultModel) {
+ given(getPnfModelClient.getAaiResponse(aaiModel)).willReturn(Mono.just(pnfResultModel));
+ }
+}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/BbsActionsTaskTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/BbsActionsTaskTest.java
new file mode 100644
index 00000000..1c5c3837
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/BbsActionsTaskTest.java
@@ -0,0 +1,245 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpMethod.DELETE;
+import static org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpMethod.GET;
+import static org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpMethod.PUT;
+
+import com.google.gson.JsonObject;
+import io.netty.buffer.ByteBuf;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Scanner;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.ArgumentMatchers;
+import org.onap.dcaegen2.services.prh.TestAppConfiguration;
+import org.onap.dcaegen2.services.prh.configuration.CbsConfiguration;
+import org.onap.dcaegen2.services.prh.exceptions.AaiFailureException;
+import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
+import org.onap.dcaegen2.services.prh.model.ImmutableConsumerDmaapModel;
+import org.onap.dcaegen2.services.sdk.rest.services.aai.client.config.AaiClientConfiguration;
+import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpResponse;
+import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.ImmutableHttpResponse;
+import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.RxHttpClient;
+import reactor.core.publisher.Mono;
+
+class BbsActionsTaskTest {
+
+ private static final String AAI_URL = "https://aai.onap.svc.cluster.local:8443/aai/v12/network";
+ private static final String PNF_URL = "/pnfs/pnf";
+ private static final String LOGICAL_LINK_URL = "/logical-links/logical-link";
+ private static final String ATTACHMENT_POINT = "attachment-point";
+
+ private static final String PNF_WITHOUT_LINK_JSON = "BbsActionsTaskTestFiles/pnfWithoutLinks.json";
+ private static final String PNF_WITH_LINK_JSON = "BbsActionsTaskTestFiles/pnfWithLogicalLink.json";
+ private static final String LOGICAL_LINK_JSON = "BbsActionsTaskTestFiles/oldLogicalLink.json";
+ private static final String LOGICAL_LINK_BODY = "BbsActionsTaskTestFiles/logicalLinkBody.json";
+
+
+ private CbsConfiguration cbsConfiguration = mock(CbsConfiguration.class);
+ private AaiClientConfiguration aaiClientConfiguration = TestAppConfiguration.createDefaultAaiClientConfiguration();
+ private RxHttpClient httpClient = mock(RxHttpClient.class);
+
+ private ClassLoader loader = getClass().getClassLoader();
+
+ @Test
+ void whenPassedObjectDoesntHaveAdditionalFields_ReturnPayloadTransparently() {
+ // given
+ given(cbsConfiguration.getAaiClientConfiguration()).willReturn(aaiClientConfiguration);
+ ConsumerDmaapModel consumerDmaapModel = buildConsumerDmaapModel(null);
+
+ // when
+ ConsumerDmaapModel result = new BbsActionsTaskImpl(cbsConfiguration, httpClient).execute(consumerDmaapModel).block();
+
+ // then
+ verifyZeroInteractions(httpClient);
+ assertThat(result).isEqualTo(consumerDmaapModel);
+ }
+
+ @Test
+ void whenPassedObjectHasEmptyLogicalLink_ReturnPayloadTransparently() {
+ // given
+ given(cbsConfiguration.getAaiClientConfiguration()).willReturn(aaiClientConfiguration);
+
+ JsonObject additionalFields = new JsonObject();
+ additionalFields.addProperty(ATTACHMENT_POINT, "");
+ ConsumerDmaapModel consumerDmaapModel = buildConsumerDmaapModel(additionalFields);
+
+ // when
+ ConsumerDmaapModel result = new BbsActionsTaskImpl(cbsConfiguration, httpClient).execute(consumerDmaapModel).block();
+
+ // then
+ verifyZeroInteractions(httpClient);
+ assertThat(result).isEqualTo(consumerDmaapModel);
+ }
+
+ @Test
+ void whenPassedObjectHasLogicalLink_and_pnfHasNoLogicalLink_createLogicalLink_and_associateWithPnf_and_ReturnPayloadTransparently() {
+ // given
+ given(cbsConfiguration.getAaiClientConfiguration()).willReturn(aaiClientConfiguration);
+
+ JsonObject additionalFields = new JsonObject();
+ String linkName = "some-link";
+ additionalFields.addProperty(ATTACHMENT_POINT, linkName);
+ ConsumerDmaapModel consumerDmaapModel = buildConsumerDmaapModel(additionalFields);
+
+ given(httpClient.call(any()))
+ .willReturn(Mono.just(buildAaiResponse(OK, getBodyJson(PNF_WITHOUT_LINK_JSON))),
+ Mono.just(buildAaiResponse(OK, "")));
+
+ // when
+ Mono<ConsumerDmaapModel> response = new BbsActionsTaskImpl(cbsConfiguration, httpClient).execute(consumerDmaapModel);
+
+ // then
+ assertEquals(consumerDmaapModel, response.block());
+
+ ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
+ verify(httpClient, times(2)).call(captor.capture());
+
+ List<HttpRequest> args = captor.getAllValues();
+ assertEquals(2, args.size());
+
+ HttpRequest pnfGet = args.get(0);
+ HttpRequest linkPut = args.get(1);
+
+ assertEquals(AAI_URL + PNF_URL + "/Nokia123", pnfGet.url());
+ assertEquals(GET, pnfGet.method());
+ assertEquals(AAI_URL + LOGICAL_LINK_URL + "/" + linkName, linkPut.url());
+ assertEquals(PUT, linkPut.method());
+ assertEquals(getBodyJson(LOGICAL_LINK_BODY), extractBodyFromRequest(linkPut));
+ }
+
+ @Test
+ void whenPassedObjectHasLogicalLink_and_pnfHasLogicalLink_deleteOldLogicalLink_and_createLogicalLink_and_associateWithPnf_and_ReturnPayloadTransparently() {
+ // given
+ given(cbsConfiguration.getAaiClientConfiguration()).willReturn(aaiClientConfiguration);
+
+ JsonObject additionalFields = new JsonObject();
+ String linkName = "some-link";
+ additionalFields.addProperty(ATTACHMENT_POINT, linkName);
+ ConsumerDmaapModel consumerDmaapModel = buildConsumerDmaapModel(additionalFields);
+
+ given(httpClient.call(any()))
+ .willReturn(Mono.just(buildAaiResponse(OK, getBodyJson(PNF_WITH_LINK_JSON))),
+ Mono.just(buildAaiResponse(OK, "")),
+ Mono.just(buildAaiResponse(OK, getBodyJson(LOGICAL_LINK_JSON))),
+ Mono.just(buildAaiResponse(OK, "")));
+
+ // when
+ Mono<ConsumerDmaapModel> response = new BbsActionsTaskImpl(cbsConfiguration, httpClient).execute(consumerDmaapModel);
+
+ // then
+ assertEquals(consumerDmaapModel, response.block());
+
+ ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
+ verify(httpClient, times(4)).call(captor.capture());
+
+ List<HttpRequest> args = captor.getAllValues();
+ assertEquals(4, args.size());
+
+ HttpRequest pnfGet = args.get(0);
+ HttpRequest linkPut = args.get(1);
+ HttpRequest linkGet = args.get(2);
+ HttpRequest linkDelete = args.get(3);
+
+ assertEquals(AAI_URL + PNF_URL + "/Nokia123", pnfGet.url());
+ assertEquals(GET, pnfGet.method());
+ assertEquals(AAI_URL + LOGICAL_LINK_URL + "/" + linkName, linkPut.url());
+ assertEquals(PUT, linkPut.method());
+ assertEquals(AAI_URL + LOGICAL_LINK_URL + "/" + linkName, linkGet.url());
+ assertEquals(GET, linkGet.method());
+ assertEquals(AAI_URL + LOGICAL_LINK_URL + "/" + linkName + "?resource-version=1560171816043", linkDelete.url());
+ assertEquals(DELETE, linkDelete.method());
+ assertEquals(getBodyJson(LOGICAL_LINK_BODY), extractBodyFromRequest(linkPut));
+ }
+
+ @Test
+ void whenPassedObjectHasLogicalLink_butAaiQueryFails_returnError() {
+ // given
+ given(cbsConfiguration.getAaiClientConfiguration()).willReturn(aaiClientConfiguration);
+
+ JsonObject additionalFields = new JsonObject();
+ String linkName = "some-link";
+ additionalFields.addProperty(ATTACHMENT_POINT, linkName);
+ ConsumerDmaapModel consumerDmaapModel = buildConsumerDmaapModel(additionalFields);
+
+ given(httpClient.call(
+ ArgumentMatchers.argThat(argument -> argument.url().equals(AAI_URL + PNF_URL + "/Nokia123")
+ || argument.url().equals(AAI_URL + LOGICAL_LINK_URL + "/" + linkName))))
+ .willReturn(Mono.just(buildAaiResponse(INTERNAL_SERVER_ERROR, "")));
+
+ // when
+ Mono<ConsumerDmaapModel> response = new BbsActionsTaskImpl(cbsConfiguration, httpClient)
+ .execute(consumerDmaapModel);
+
+ // then
+ assertThatThrownBy(response::block).hasCauseInstanceOf(AaiFailureException.class).hasMessage(
+ "org.onap.dcaegen2.services.prh.exceptions.AaiFailureException: "
+ + "Incorrect response when performing BBS-related actions: 500. Occurred in GET PNF request. Pnf name: Nokia123");
+ }
+
+ private ConsumerDmaapModel buildConsumerDmaapModel(JsonObject additionalFields) {
+ return ImmutableConsumerDmaapModel.builder()
+ .ipv4("10.16.123.234")
+ .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
+ .correlationId("Nokia123")
+ .serialNumber("QTFCOC540002E")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("role")
+ .swVersion("v4.5.0.1")
+ .additionalFields(additionalFields)
+ .build();
+ }
+
+ private HttpResponse buildAaiResponse(HttpResponseStatus status, String body) {
+ return ImmutableHttpResponse
+ .builder()
+ .statusCode(status.code())
+ .url("")
+ .rawBody(body.getBytes())
+ .build();
+ }
+
+ private String extractBodyFromRequest(HttpRequest request) {
+ return Mono.from(request.body().contents()).block().toString(StandardCharsets.UTF_8);
+ }
+
+ private String getBodyJson(String filename) {
+ return new Scanner(loader.getResourceAsStream(filename)).useDelimiter("\\A").next();
+ }
+} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImplTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImplTest.java
deleted file mode 100644
index fc85b98b..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImplTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PNF-REGISTRATION-HANDLER
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.onap.dcaegen2.services.prh.TestAppConfiguration.createDefaultDmaapConsumerConfiguration;
-
-import java.util.Optional;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-import org.onap.dcaegen2.services.prh.configuration.AppConfig;
-import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
-import org.onap.dcaegen2.services.prh.model.ImmutableConsumerDmaapModel;
-import org.onap.dcaegen2.services.prh.service.DmaapConsumerJsonParser;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapConsumerConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.service.consumer.ConsumerReactiveHttpClientFactory;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.service.consumer.DMaaPConsumerReactiveHttpClient;
-
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/17/18
- */
-class DmaapConsumerTaskImplTest {
-
- private static ConsumerDmaapModel consumerDmaapModel;
- private static DmaapConsumerTaskImpl dmaapConsumerTask;
- private static DMaaPConsumerReactiveHttpClient dMaaPConsumerReactiveHttpClient;
- private static AppConfig appConfig;
- private static DmaapConsumerConfiguration dmaapConsumerConfiguration;
- private static String message;
-
- @BeforeAll
- static void setUp() {
- dmaapConsumerConfiguration = createDefaultDmaapConsumerConfiguration();
-
- consumerDmaapModel = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234")
- .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
- .correlationId("NOKQTFCOC540002E").build();
- appConfig = mock(AppConfig.class);
-
- message = "[{\"event\": {"
- + "\"commonEventHeader\": { \"sourceName\":\"NOKQTFCOC540002E\"},"
- + "\"pnfRegistrationFields\": {"
- + " \"unitType\": \"AirScale\","
- + " \"serialNumber\": \"QTFCOC540002E\","
- + " \"pnfRegistrationFieldsVersion\": \"2.0\","
- + " \"manufactureDate\": \"1535014037024\","
- + " \"modelNumber\": \"7BEA\",\n"
- + " \"lastServiceDate\": \"1535014037024\","
- + " \"unitFamily\": \"BBU\","
- + " \"vendorName\": \"Nokia\","
- + " \"oamV4IpAddress\": \"10.16.123.234\","
- + " \"softwareVersion\": \"v4.5.0.1\","
- + " \"oamV6IpAddress\": \"0:0:0:0:0:FFFF:0A10:7BEA\""
- + "}}}]";
- }
-
- @Test
- void whenPassedObjectDoesntFit_DoesNotThrowPrhTaskException() throws Exception {
- //given
- prepareMocksForDmaapConsumer(Optional.empty());
-
- //when
- Flux<ConsumerDmaapModel> response = dmaapConsumerTask.execute("Sample input");
-
- //then
- verify(dMaaPConsumerReactiveHttpClient).getDMaaPConsumerResponse();
- assertNull(response.blockFirst());
- }
-
- @Test
- void whenPassedObjectFits_ReturnsCorrectResponse() throws Exception {
- //given
- prepareMocksForDmaapConsumer(Optional.of(message));
-
- //when
- Flux<ConsumerDmaapModel> response = dmaapConsumerTask.execute("Sample input");
-
- //then
- verify(dMaaPConsumerReactiveHttpClient).getDMaaPConsumerResponse();
- assertEquals(consumerDmaapModel, response.blockFirst());
- }
-
- @Test
- void whenInitConfigs_initStreamReader() {
- //when
- dmaapConsumerTask.initConfigs();
-
- //then
- verify(appConfig).initFileStreamReader();
- }
-
- private void prepareMocksForDmaapConsumer(Optional<String> message) throws Exception {
- dMaaPConsumerReactiveHttpClient = mock(DMaaPConsumerReactiveHttpClient.class);
- when(dMaaPConsumerReactiveHttpClient.getDMaaPConsumerResponse()).thenReturn(Mono.just(message.orElse("")));
- when(appConfig.getDmaapConsumerConfiguration()).thenReturn(dmaapConsumerConfiguration);
- ConsumerReactiveHttpClientFactory httpClientFactory = mock(ConsumerReactiveHttpClientFactory.class);
- doReturn(dMaaPConsumerReactiveHttpClient).when(httpClientFactory).create(dmaapConsumerConfiguration);
- dmaapConsumerTask = new DmaapConsumerTaskImpl(appConfig, new DmaapConsumerJsonParser(), httpClientFactory);
- }
-} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskSpy.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskSpy.java
deleted file mode 100644
index cb31c86b..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskSpy.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
-
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-
-import javax.net.ssl.SSLException;
-import org.onap.dcaegen2.services.prh.configuration.AppConfig;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapConsumerConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.service.consumer.DMaaPConsumerReactiveHttpClient;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
-
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 3/27/18
- */
-@Configuration
-public class DmaapConsumerTaskSpy {
-
- /**
- * Mocking bean for tests.
- *
- * @return DMaaP ConsumerTask spy
- */
- @Bean
- @Primary
- public DmaapConsumerTask registerSimpleDmaapConsumerTask() throws SSLException {
- AppConfig appConfig = spy(AppConfig.class);
- doReturn(mock(DmaapConsumerConfiguration.class)).when(appConfig).getDmaapConsumerConfiguration();
- DmaapConsumerTaskImpl dmaapConsumerTask = spy(new DmaapConsumerTaskImpl(appConfig));
- DMaaPConsumerReactiveHttpClient dmaapConsumerReactiveHttpClient = mock(
- DMaaPConsumerReactiveHttpClient.class);
- doReturn(dmaapConsumerReactiveHttpClient).when(dmaapConsumerTask).resolveClient();
- return dmaapConsumerTask;
- }
-}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapProducerTaskSpy.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapProducerTaskSpy.java
deleted file mode 100644
index 07cdc5d8..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapProducerTaskSpy.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PROJECT
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
-
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-
-import org.onap.dcaegen2.services.prh.configuration.AppConfig;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.service.producer.DMaaPPublisherReactiveHttpClient;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/13/18
- */
-@Configuration
-public class DmaapProducerTaskSpy {
-
- /**
- * Mocking bean for tests.
- *
- * @return DMaaP PublisherTask spy
- */
- @Bean
- @Primary
- public DmaapPublisherTask registerSimpleDmaapPublisherTask() {
- AppConfig appConfig = spy(AppConfig.class);
- doReturn(mock(DmaapPublisherConfiguration.class)).when(appConfig).getDmaapPublisherConfiguration();
- DmaapPublisherTaskImpl dmaapPublisherTask = spy(new DmaapPublisherTaskImpl(appConfig));
- DMaaPPublisherReactiveHttpClient extendedDmaapProducerHttpClient = mock(
- DMaaPPublisherReactiveHttpClient.class);
- doReturn(extendedDmaapProducerHttpClient).when(dmaapPublisherTask).resolveClient();
- return dmaapPublisherTask;
- }
-}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java
index f4a1c2e6..7e00a441 100644
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java
@@ -20,108 +20,94 @@
package org.onap.dcaegen2.services.prh.tasks;
-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.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-import static org.onap.dcaegen2.services.prh.TestAppConfiguration.createDefaultDmaapPublisherConfiguration;
-
-import org.junit.jupiter.api.BeforeAll;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.function.Executable;
-import org.onap.dcaegen2.services.prh.configuration.AppConfig;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.dcaegen2.services.prh.exceptions.DmaapNotFoundException;
import org.onap.dcaegen2.services.prh.exceptions.PrhTaskException;
-import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
import org.onap.dcaegen2.services.prh.model.ImmutableConsumerDmaapModel;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.service.producer.DMaaPPublisherReactiveHttpClient;
-import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.service.producer.PublisherReactiveHttpClientFactory;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import reactor.core.publisher.Mono;
+import org.onap.dcaegen2.services.sdk.model.streams.dmaap.ImmutableMessageRouterSink;
+import org.onap.dcaegen2.services.sdk.model.streams.dmaap.MessageRouterSink;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterPublisher;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterPublishRequest;
+import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishRequest;
+import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+
/**
* @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/17/18
*/
+@ExtendWith(MockitoExtension.class)
class DmaapPublisherTaskImplTest {
- private static ConsumerDmaapModel consumerDmaapModel;
- private static DmaapPublisherTaskImpl dmaapPublisherTask;
- private static DMaaPPublisherReactiveHttpClient dMaaPPublisherReactiveHttpClient;
- private static AppConfig appConfig;
- private static DmaapPublisherConfiguration dmaapPublisherConfiguration;
+ private DmaapPublisherTaskImpl dmaapPublisherTask;
- @BeforeAll
- static void setUp() {
- dmaapPublisherConfiguration = createDefaultDmaapPublisherConfiguration();
- consumerDmaapModel = ImmutableConsumerDmaapModel.builder().ipv4("10.16.123.234")
- .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
- .correlationId("NOKQTFCOC540002E").build();
- appConfig = mock(AppConfig.class);
- }
+ private MessageRouterPublishRequest mrRequest = createMRRequest();
+
+ @Mock
+ private static MessageRouterPublisher messageRouterPublisher;
+
+ @Captor
+ private ArgumentCaptor<Flux<JsonElement>> fluxCaptor;
@Test
- void whenPassedObjectDoesntFit_ThrowsPrhTaskException() {
+ void execute_whenPassedObjectDoesntFit_ThrowsPrhTaskException() {
//given
- when(appConfig.getDmaapPublisherConfiguration()).thenReturn(dmaapPublisherConfiguration);
- dmaapPublisherTask = new DmaapPublisherTaskImpl(appConfig);
-
+ dmaapPublisherTask = new DmaapPublisherTaskImpl(() -> mrRequest, () -> messageRouterPublisher);
//when
Executable executableFunction = () -> dmaapPublisherTask.execute(null);
-
//then
assertThrows(PrhTaskException.class, executableFunction, "The specified parameter is incorrect");
}
@Test
- void whenPassedObjectFits_ReturnsCorrectStatus() throws PrhTaskException {
+ void execute_whenPassedObjectFits_ReturnsCorrectStatus() throws DmaapNotFoundException {
//given
- ResponseEntity<String> responseEntity = prepareMocksForTests(HttpStatus.OK.value());
-
+ dmaapPublisherTask = new DmaapPublisherTaskImpl(() -> mrRequest, () -> messageRouterPublisher);
//when
- when(responseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
- StepVerifier.create(dmaapPublisherTask.execute(consumerDmaapModel)).expectSubscription()
- .expectNext(responseEntity).verifyComplete();
-
+ dmaapPublisherTask.execute(createConsumerDmaapModel());
//then
- verify(dMaaPPublisherReactiveHttpClient, times(1))
- .getDMaaPProducerResponse(consumerDmaapModel);
- verifyNoMoreInteractions(dMaaPPublisherReactiveHttpClient);
- }
-
+ verify(messageRouterPublisher).put(eq(mrRequest), fluxCaptor.capture());
- @Test
- void whenPassedObjectFits_butIncorrectResponseReturns() throws DmaapNotFoundException {
- //given
- ResponseEntity<String> responseEntity = prepareMocksForTests(HttpStatus.UNAUTHORIZED.value());
+ StepVerifier.create(fluxCaptor.getValue())
+ .expectNext(new JsonParser().parse("{\"correlationId\":\"NOKQTFCOC540002E\"}"))
+ .verifyComplete();
+ }
- //when
- when(responseEntity.getStatusCode()).thenReturn(HttpStatus.UNAUTHORIZED);
- StepVerifier.create(dmaapPublisherTask.execute(consumerDmaapModel)).expectSubscription()
- .expectNext(responseEntity).verifyComplete();
- //then
- verify(dMaaPPublisherReactiveHttpClient, times(1))
- .getDMaaPProducerResponse(consumerDmaapModel);
- verifyNoMoreInteractions(dMaaPPublisherReactiveHttpClient);
+ private ImmutableConsumerDmaapModel createConsumerDmaapModel() {
+ return ImmutableConsumerDmaapModel.builder()
+ .ipv4("10.16.123.234")
+ .ipv6("0:0:0:0:0:FFFF:0A10:7BEA")
+ .correlationId("NOKQTFCOC540002E")
+ .serialNumber("QTFCOC540002E")
+ .equipVendor("nokia")
+ .equipModel("3310")
+ .equipType("type")
+ .nfRole("gNB")
+ .swVersion("v4.5.0.1")
+ .additionalFields(null)
+ .build();
}
+ private MessageRouterPublishRequest createMRRequest() {
+ final MessageRouterSink sinkDefinition = ImmutableMessageRouterSink.builder()
+ .name("the topic")
+ .topicUrl("http://dmaap-mr:2222/events/unauthenticated.PNF_READY")
+ .build();
- private ResponseEntity<String> prepareMocksForTests(Integer httpResponseCode) {
- ResponseEntity<String> responseEntity = mock(ResponseEntity.class);
- when(responseEntity.getStatusCode()).thenReturn(HttpStatus.valueOf(httpResponseCode));
- dMaaPPublisherReactiveHttpClient = mock(DMaaPPublisherReactiveHttpClient.class);
- when(dMaaPPublisherReactiveHttpClient.getDMaaPProducerResponse(any()))
- .thenReturn(Mono.just(responseEntity));
- PublisherReactiveHttpClientFactory httpClientFactory = mock(PublisherReactiveHttpClientFactory.class);
- doReturn(dMaaPPublisherReactiveHttpClient).when(httpClientFactory).create(dmaapPublisherConfiguration);
- dmaapPublisherTask = new DmaapPublisherTaskImpl(appConfig, httpClientFactory);
- return responseEntity;
+ return ImmutableMessageRouterPublishRequest.builder()
+ .sinkDefinition(sinkDefinition)
+ .build();
}
} \ No newline at end of file
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduleControllerSpy.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduleControllerSpy.java
deleted file mode 100644
index 2f7ff61c..00000000
--- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduleControllerSpy.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * PNF-REGISTRATION-HANDLER
- * ================================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
-
-import static org.mockito.Mockito.spy;
-
-import java.util.Map;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
-
-/**
- * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/5/18
- */
-@Configuration
-public class ScheduleControllerSpy {
-
- @Autowired
- private DmaapConsumerTask dmaapConsumerTaskImplSpy;
-
- @Autowired
- private DmaapPublisherTask dmaapPublisherTaskImplSpy;
-
- @Autowired
- private AaiProducerTask aaiPublisherTaskImplSpy;
-
- @Autowired
- private Map<String, String> mdcContextMap;
-
- @Bean
- @Primary
- public ScheduledTasks registerSimpleScheduledTask() {
- return spy(new ScheduledTasks(dmaapConsumerTaskImplSpy, dmaapPublisherTaskImplSpy, aaiPublisherTaskImplSpy,
- mdcContextMap));
- }
-}
diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduledTasksTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduledTasksTest.java
new file mode 100644
index 00000000..cefc5c76
--- /dev/null
+++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/ScheduledTasksTest.java
@@ -0,0 +1,186 @@
+/*
+ * ============LICENSE_START=======================================================
+ * PNF-REGISTRATION-HANDLER
+ * ================================================================================
+ * Copyright (C) 2019 NOKIA Intellectual Property. 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.dcaegen2.services.prh.tasks;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.onap.dcaegen2.services.prh.exceptions.PrhTaskException;
+import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
+import org.onap.dcaegen2.services.prh.model.ImmutableConsumerDmaapModel;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+import javax.net.ssl.SSLException;
+import java.util.Collections;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+@ExtendWith(MockitoExtension.class)
+class ScheduledTasksTest {
+ private final static ConsumerDmaapModel DMAAP_MODEL =
+ ImmutableConsumerDmaapModel
+ .builder()
+ .correlationId("SomeId")
+ .ipv4("ipv4")
+ .ipv6("ipv6")
+ .build();
+
+ @Mock
+ private DmaapPublisherTask readyPublisher;
+
+ @Mock
+ private DmaapPublisherTask updatePublisher;
+
+ @Mock
+ private DmaapConsumerTask consumer;
+
+ @Mock
+ private BbsActionsTask bbsActions;
+
+ @Mock
+ private AaiQueryTask aaiQuery;
+
+ @Mock
+ private AaiProducerTask aaiProducer;
+
+ private final Map<String, String> context = Collections.emptyMap();
+
+ private ScheduledTasks sut;
+
+ @BeforeEach
+ void setUp() {
+ sut = new ScheduledTasks(
+ consumer,
+ readyPublisher,
+ updatePublisher,
+ aaiQuery,
+ aaiProducer,
+ bbsActions,
+ context);
+ }
+
+ @Test
+ void whenEmptyResultFromDMaaPConsumer_NotActionShouldBePerformed() throws SSLException, PrhTaskException {
+ //given
+ given(consumer.execute()).willReturn(Flux.empty());
+
+ //when
+ sut.scheduleMainPrhEventTask();
+
+ //then
+ verifyThatPnfUpdateWasNotSentToAai();
+ verifyIfLogicalLinkWasNotCreated();
+ verifyThatPnfModelWasNotSentDmaapPnfReadyTopic();
+ verifyThatPnfModelWasNotSentDmaapPnfUpdateTopic();
+ }
+
+ @Test
+ void whenPnfNotFoundInAai_NotActionShouldBePerformed() throws SSLException, PrhTaskException {
+ //given
+ given(consumer.execute()).willReturn(Flux.just(DMAAP_MODEL));
+ given(aaiQuery.execute(any())).willReturn(Mono.error(new PrhTaskException("404 Not Found")));
+
+ //when
+ sut.scheduleMainPrhEventTask();
+
+ verifyThatPnfUpdateWasNotSentToAai();
+ verifyIfLogicalLinkWasNotCreated();
+ verifyThatPnfModelWasNotSentDmaapPnfReadyTopic();
+ verifyThatPnfModelWasNotSentDmaapPnfUpdateTopic();
+ }
+
+ @Test
+ void whenPnfWithoutService_PatchToAaiAndPostToPnfReadyShouldBePerformed() throws SSLException, PrhTaskException {
+ //given
+ Mono<ConsumerDmaapModel> consumerModel = Mono.just(DMAAP_MODEL);
+
+ given(aaiProducer.execute(DMAAP_MODEL)).willReturn(consumerModel);
+ given(bbsActions.execute(DMAAP_MODEL)).willReturn(consumerModel);
+
+
+ given(consumer.execute()).willReturn(Flux.just(DMAAP_MODEL));
+ given(aaiQuery.execute(any())).willReturn(Mono.just(false));
+
+ //when
+ sut.scheduleMainPrhEventTask();
+
+ //then
+ verifyThatPnfUpdateWasSentToAai();
+ verifyIfLogicalLinkWasCreated();
+ verifyThatPnfModelWasSentDmaapPnfReadyTopic();
+ verifyThatPnfModelWasNotSentDmaapPnfUpdateTopic();
+ }
+
+ @Test
+ void whenPnfHasActiveService_OnlyPostToPnfUpdateShouldBePerformed() throws SSLException, PrhTaskException {
+ //given
+ given(consumer.execute()).willReturn(Flux.just(DMAAP_MODEL));
+ given(aaiQuery.execute(any())).willReturn(Mono.just(true));
+
+ //when
+ sut.scheduleMainPrhEventTask();
+
+ //then
+ verifyThatPnfUpdateWasNotSentToAai();
+ verifyIfLogicalLinkWasNotCreated();
+ verifyThatPnfModelWasNotSentDmaapPnfReadyTopic();
+ verifyThatPnfModelWasSentDmaapPnfUpdateTopic();
+ }
+
+ private void verifyThatPnfModelWasNotSentDmaapPnfReadyTopic() throws PrhTaskException {
+ verify(readyPublisher, never()).execute(DMAAP_MODEL);
+ }
+
+ private void verifyThatPnfModelWasNotSentDmaapPnfUpdateTopic() throws PrhTaskException {
+ verify(updatePublisher, never()).execute(DMAAP_MODEL);
+ }
+
+ private void verifyThatPnfModelWasSentDmaapPnfReadyTopic() throws PrhTaskException {
+ verify(readyPublisher, atLeastOnce()).execute(DMAAP_MODEL);
+ }
+
+ private void verifyThatPnfModelWasSentDmaapPnfUpdateTopic() throws PrhTaskException {
+ verify(updatePublisher, atLeastOnce()).execute(DMAAP_MODEL);
+ }
+
+ private void verifyThatPnfUpdateWasNotSentToAai() throws PrhTaskException, SSLException {
+ verify(aaiProducer, never()).execute(DMAAP_MODEL);
+ }
+
+ private void verifyThatPnfUpdateWasSentToAai() throws PrhTaskException, SSLException {
+ verify(aaiProducer, atLeastOnce()).execute(DMAAP_MODEL);
+ }
+
+ private void verifyIfLogicalLinkWasCreated(){
+ verify(bbsActions, atLeastOnce()).execute(DMAAP_MODEL);
+ }
+
+ private void verifyIfLogicalLinkWasNotCreated(){
+ verify(bbsActions, never()).execute(DMAAP_MODEL);
+ }
+} \ No newline at end of file